context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
// 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 CompareEqualInt16()
{
var test = new SimpleBinaryOpTest__CompareEqualInt16();
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 works
test.RunLclFldScenario();
// Validates passing an instance member works
test.RunFldScenario();
}
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 SimpleBinaryOpTest__CompareEqualInt16
{
private const int VectorSize = 16;
private const int Op1ElementCount = VectorSize / sizeof(Int16);
private const int Op2ElementCount = VectorSize / sizeof(Int16);
private const int RetElementCount = VectorSize / sizeof(Int16);
private static Int16[] _data1 = new Int16[Op1ElementCount];
private static Int16[] _data2 = new Int16[Op2ElementCount];
private static Vector128<Int16> _clsVar1;
private static Vector128<Int16> _clsVar2;
private Vector128<Int16> _fld1;
private Vector128<Int16> _fld2;
private SimpleBinaryOpTest__DataTable<Int16, Int16, Int16> _dataTable;
static SimpleBinaryOpTest__CompareEqualInt16()
{
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (short)(random.Next(short.MinValue, short.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _clsVar1), ref Unsafe.As<Int16, byte>(ref _data1[0]), VectorSize);
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (short)(random.Next(short.MinValue, short.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _clsVar2), ref Unsafe.As<Int16, byte>(ref _data2[0]), VectorSize);
}
public SimpleBinaryOpTest__CompareEqualInt16()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (short)(random.Next(short.MinValue, short.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), VectorSize);
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (short)(random.Next(short.MinValue, short.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), VectorSize);
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (short)(random.Next(short.MinValue, short.MaxValue)); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (short)(random.Next(short.MinValue, short.MaxValue)); }
_dataTable = new SimpleBinaryOpTest__DataTable<Int16, Int16, Int16>(_data1, _data2, new Int16[RetElementCount], VectorSize);
}
public bool IsSupported => Sse2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Sse2.CompareEqual(
Unsafe.Read<Vector128<Int16>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Int16>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
var result = Sse2.CompareEqual(
Sse2.LoadVector128((Int16*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Int16*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
var result = Sse2.CompareEqual(
Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.CompareEqual), new Type[] { typeof(Vector128<Int16>), typeof(Vector128<Int16>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Int16>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Int16>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.CompareEqual), new Type[] { typeof(Vector128<Int16>), typeof(Vector128<Int16>) })
.Invoke(null, new object[] {
Sse2.LoadVector128((Int16*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Int16*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.CompareEqual), new Type[] { typeof(Vector128<Int16>), typeof(Vector128<Int16>) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
var result = Sse2.CompareEqual(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
var left = Unsafe.Read<Vector128<Int16>>(_dataTable.inArray1Ptr);
var right = Unsafe.Read<Vector128<Int16>>(_dataTable.inArray2Ptr);
var result = Sse2.CompareEqual(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
var left = Sse2.LoadVector128((Int16*)(_dataTable.inArray1Ptr));
var right = Sse2.LoadVector128((Int16*)(_dataTable.inArray2Ptr));
var result = Sse2.CompareEqual(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
var left = Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArray1Ptr));
var right = Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArray2Ptr));
var result = Sse2.CompareEqual(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclFldScenario()
{
var test = new SimpleBinaryOpTest__CompareEqualInt16();
var result = Sse2.CompareEqual(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunFldScenario()
{
var result = Sse2.CompareEqual(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunUnsupportedScenario()
{
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector128<Int16> left, Vector128<Int16> right, void* result, [CallerMemberName] string method = "")
{
Int16[] inArray1 = new Int16[Op1ElementCount];
Int16[] inArray2 = new Int16[Op2ElementCount];
Int16[] outArray = new Int16[RetElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left);
Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "")
{
Int16[] inArray1 = new Int16[Op1ElementCount];
Int16[] inArray2 = new Int16[Op2ElementCount];
Int16[] outArray = new Int16[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Int16[] left, Int16[] right, Int16[] result, [CallerMemberName] string method = "")
{
if (result[0] != ((left[0] == right[0]) ? unchecked((short)(-1)) : 0))
{
Succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (result[i] != ((left[i] == right[i]) ? unchecked((short)(-1)) : 0))
{
Succeeded = false;
break;
}
}
}
if (!Succeeded)
{
Console.WriteLine($"{nameof(Sse2)}.{nameof(Sse2.CompareEqual)}<Int16>(Vector128<Int16>, Vector128<Int16>): {method} failed:");
Console.WriteLine($" left: ({string.Join(", ", left)})");
Console.WriteLine($" right: ({string.Join(", ", right)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
namespace DisasterReport.Migrations
{
using System;
using System.Collections.Generic;
using System.Data.Entity.Infrastructure.Annotations;
using System.Data.Entity.Migrations;
public partial class AbpZero_Initial : DbMigration
{
public override void Up()
{
CreateTable(
"dbo.AbpAuditLogs",
c => new
{
Id = c.Long(nullable: false, identity: true),
TenantId = c.Int(),
UserId = c.Long(),
ServiceName = c.String(maxLength: 256),
MethodName = c.String(maxLength: 256),
Parameters = c.String(maxLength: 1024),
ExecutionTime = c.DateTime(nullable: false),
ExecutionDuration = c.Int(nullable: false),
ClientIpAddress = c.String(maxLength: 64),
ClientName = c.String(maxLength: 128),
BrowserInfo = c.String(maxLength: 256),
Exception = c.String(maxLength: 2000),
ImpersonatorUserId = c.Long(),
ImpersonatorTenantId = c.Int(),
CustomData = c.String(maxLength: 2000),
},
annotations: new Dictionary<string, object>
{
{ "DynamicFilter_AuditLog_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.AbpBackgroundJobs",
c => new
{
Id = c.Long(nullable: false, identity: true),
JobType = c.String(nullable: false, maxLength: 512),
JobArgs = c.String(nullable: false),
TryCount = c.Short(nullable: false),
NextTryTime = c.DateTime(nullable: false),
LastTryTime = c.DateTime(),
IsAbandoned = c.Boolean(nullable: false),
Priority = c.Byte(nullable: false),
CreationTime = c.DateTime(nullable: false),
CreatorUserId = c.Long(),
})
.PrimaryKey(t => t.Id)
.Index(t => new { t.IsAbandoned, t.NextTryTime });
CreateTable(
"dbo.AbpFeatures",
c => new
{
Id = c.Long(nullable: false, identity: true),
Name = c.String(nullable: false, maxLength: 128),
Value = c.String(nullable: false, maxLength: 2000),
CreationTime = c.DateTime(nullable: false),
CreatorUserId = c.Long(),
EditionId = c.Int(),
TenantId = c.Int(),
Discriminator = c.String(nullable: false, maxLength: 128),
},
annotations: new Dictionary<string, object>
{
{ "DynamicFilter_TenantFeatureSetting_MustHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.AbpEditions", t => t.EditionId, cascadeDelete: true)
.Index(t => t.EditionId);
CreateTable(
"dbo.AbpEditions",
c => new
{
Id = c.Int(nullable: false, identity: true),
Name = c.String(nullable: false, maxLength: 32),
DisplayName = c.String(nullable: false, maxLength: 64),
IsDeleted = c.Boolean(nullable: false),
DeleterUserId = c.Long(),
DeletionTime = c.DateTime(),
LastModificationTime = c.DateTime(),
LastModifierUserId = c.Long(),
CreationTime = c.DateTime(nullable: false),
CreatorUserId = c.Long(),
},
annotations: new Dictionary<string, object>
{
{ "DynamicFilter_Edition_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.AbpLanguages",
c => new
{
Id = c.Int(nullable: false, identity: true),
TenantId = c.Int(),
Name = c.String(nullable: false, maxLength: 10),
DisplayName = c.String(nullable: false, maxLength: 64),
Icon = c.String(maxLength: 128),
IsDeleted = c.Boolean(nullable: false),
DeleterUserId = c.Long(),
DeletionTime = c.DateTime(),
LastModificationTime = c.DateTime(),
LastModifierUserId = c.Long(),
CreationTime = c.DateTime(nullable: false),
CreatorUserId = c.Long(),
},
annotations: new Dictionary<string, object>
{
{ "DynamicFilter_ApplicationLanguage_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
{ "DynamicFilter_ApplicationLanguage_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.AbpLanguageTexts",
c => new
{
Id = c.Long(nullable: false, identity: true),
TenantId = c.Int(),
LanguageName = c.String(nullable: false, maxLength: 10),
Source = c.String(nullable: false, maxLength: 128),
Key = c.String(nullable: false, maxLength: 256),
Value = c.String(nullable: false),
LastModificationTime = c.DateTime(),
LastModifierUserId = c.Long(),
CreationTime = c.DateTime(nullable: false),
CreatorUserId = c.Long(),
},
annotations: new Dictionary<string, object>
{
{ "DynamicFilter_ApplicationLanguageText_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.AbpNotifications",
c => new
{
Id = c.Guid(nullable: false),
NotificationName = c.String(nullable: false, maxLength: 96),
Data = c.String(),
DataTypeName = c.String(maxLength: 512),
EntityTypeName = c.String(maxLength: 250),
EntityTypeAssemblyQualifiedName = c.String(maxLength: 512),
EntityId = c.String(maxLength: 96),
Severity = c.Byte(nullable: false),
UserIds = c.String(),
ExcludedUserIds = c.String(),
TenantIds = c.String(),
CreationTime = c.DateTime(nullable: false),
CreatorUserId = c.Long(),
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.AbpNotificationSubscriptions",
c => new
{
Id = c.Guid(nullable: false),
TenantId = c.Int(),
UserId = c.Long(nullable: false),
NotificationName = c.String(maxLength: 96),
EntityTypeName = c.String(maxLength: 250),
EntityTypeAssemblyQualifiedName = c.String(maxLength: 512),
EntityId = c.String(maxLength: 96),
CreationTime = c.DateTime(nullable: false),
CreatorUserId = c.Long(),
},
annotations: new Dictionary<string, object>
{
{ "DynamicFilter_NotificationSubscriptionInfo_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
})
.PrimaryKey(t => t.Id)
.Index(t => new { t.NotificationName, t.EntityTypeName, t.EntityId, t.UserId });
CreateTable(
"dbo.AbpOrganizationUnits",
c => new
{
Id = c.Long(nullable: false, identity: true),
TenantId = c.Int(),
ParentId = c.Long(),
Code = c.String(nullable: false, maxLength: 95),
DisplayName = c.String(nullable: false, maxLength: 128),
IsDeleted = c.Boolean(nullable: false),
DeleterUserId = c.Long(),
DeletionTime = c.DateTime(),
LastModificationTime = c.DateTime(),
LastModifierUserId = c.Long(),
CreationTime = c.DateTime(nullable: false),
CreatorUserId = c.Long(),
},
annotations: new Dictionary<string, object>
{
{ "DynamicFilter_OrganizationUnit_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
{ "DynamicFilter_OrganizationUnit_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.AbpOrganizationUnits", t => t.ParentId)
.Index(t => t.ParentId);
CreateTable(
"dbo.AbpPermissions",
c => new
{
Id = c.Long(nullable: false, identity: true),
TenantId = c.Int(),
Name = c.String(nullable: false, maxLength: 128),
IsGranted = c.Boolean(nullable: false),
CreationTime = c.DateTime(nullable: false),
CreatorUserId = c.Long(),
RoleId = c.Int(),
UserId = c.Long(),
Discriminator = c.String(nullable: false, maxLength: 128),
},
annotations: new Dictionary<string, object>
{
{ "DynamicFilter_PermissionSetting_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
{ "DynamicFilter_RolePermissionSetting_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
{ "DynamicFilter_UserPermissionSetting_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.AbpUsers", t => t.UserId, cascadeDelete: true)
.ForeignKey("dbo.AbpRoles", t => t.RoleId, cascadeDelete: true)
.Index(t => t.RoleId)
.Index(t => t.UserId);
CreateTable(
"dbo.AbpRoles",
c => new
{
Id = c.Int(nullable: false, identity: true),
DisplayName = c.String(nullable: false, maxLength: 64),
IsStatic = c.Boolean(nullable: false),
IsDefault = c.Boolean(nullable: false),
TenantId = c.Int(),
Name = c.String(nullable: false, maxLength: 32),
IsDeleted = c.Boolean(nullable: false),
DeleterUserId = c.Long(),
DeletionTime = c.DateTime(),
LastModificationTime = c.DateTime(),
LastModifierUserId = c.Long(),
CreationTime = c.DateTime(nullable: false),
CreatorUserId = c.Long(),
},
annotations: new Dictionary<string, object>
{
{ "DynamicFilter_Role_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
{ "DynamicFilter_Role_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.AbpUsers", t => t.CreatorUserId)
.ForeignKey("dbo.AbpUsers", t => t.DeleterUserId)
.ForeignKey("dbo.AbpUsers", t => t.LastModifierUserId)
.Index(t => t.DeleterUserId)
.Index(t => t.LastModifierUserId)
.Index(t => t.CreatorUserId);
CreateTable(
"dbo.AbpUsers",
c => new
{
Id = c.Long(nullable: false, identity: true),
AuthenticationSource = c.String(maxLength: 64),
Name = c.String(nullable: false, maxLength: 32),
Surname = c.String(nullable: false, maxLength: 32),
Password = c.String(nullable: false, maxLength: 128),
IsEmailConfirmed = c.Boolean(nullable: false),
EmailConfirmationCode = c.String(maxLength: 328),
PasswordResetCode = c.String(maxLength: 328),
LockoutEndDateUtc = c.DateTime(),
AccessFailedCount = c.Int(nullable: false),
IsLockoutEnabled = c.Boolean(nullable: false),
PhoneNumber = c.String(),
IsPhoneNumberConfirmed = c.Boolean(nullable: false),
SecurityStamp = c.String(),
IsTwoFactorEnabled = c.Boolean(nullable: false),
IsActive = c.Boolean(nullable: false),
UserName = c.String(nullable: false, maxLength: 32),
TenantId = c.Int(),
EmailAddress = c.String(nullable: false, maxLength: 256),
LastLoginTime = c.DateTime(),
IsDeleted = c.Boolean(nullable: false),
DeleterUserId = c.Long(),
DeletionTime = c.DateTime(),
LastModificationTime = c.DateTime(),
LastModifierUserId = c.Long(),
CreationTime = c.DateTime(nullable: false),
CreatorUserId = c.Long(),
},
annotations: new Dictionary<string, object>
{
{ "DynamicFilter_User_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
{ "DynamicFilter_User_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.AbpUsers", t => t.CreatorUserId)
.ForeignKey("dbo.AbpUsers", t => t.DeleterUserId)
.ForeignKey("dbo.AbpUsers", t => t.LastModifierUserId)
.Index(t => t.DeleterUserId)
.Index(t => t.LastModifierUserId)
.Index(t => t.CreatorUserId);
CreateTable(
"dbo.AbpUserClaims",
c => new
{
Id = c.Long(nullable: false, identity: true),
TenantId = c.Int(),
UserId = c.Long(nullable: false),
ClaimType = c.String(),
ClaimValue = c.String(),
CreationTime = c.DateTime(nullable: false),
CreatorUserId = c.Long(),
},
annotations: new Dictionary<string, object>
{
{ "DynamicFilter_UserClaim_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.AbpUsers", t => t.UserId, cascadeDelete: true)
.Index(t => t.UserId);
CreateTable(
"dbo.AbpUserLogins",
c => new
{
Id = c.Long(nullable: false, identity: true),
TenantId = c.Int(),
UserId = c.Long(nullable: false),
LoginProvider = c.String(nullable: false, maxLength: 128),
ProviderKey = c.String(nullable: false, maxLength: 256),
},
annotations: new Dictionary<string, object>
{
{ "DynamicFilter_UserLogin_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.AbpUsers", t => t.UserId, cascadeDelete: true)
.Index(t => t.UserId);
CreateTable(
"dbo.AbpUserRoles",
c => new
{
Id = c.Long(nullable: false, identity: true),
TenantId = c.Int(),
UserId = c.Long(nullable: false),
RoleId = c.Int(nullable: false),
CreationTime = c.DateTime(nullable: false),
CreatorUserId = c.Long(),
},
annotations: new Dictionary<string, object>
{
{ "DynamicFilter_UserRole_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.AbpUsers", t => t.UserId, cascadeDelete: true)
.Index(t => t.UserId);
CreateTable(
"dbo.AbpSettings",
c => new
{
Id = c.Long(nullable: false, identity: true),
TenantId = c.Int(),
UserId = c.Long(),
Name = c.String(nullable: false, maxLength: 256),
Value = c.String(maxLength: 2000),
LastModificationTime = c.DateTime(),
LastModifierUserId = c.Long(),
CreationTime = c.DateTime(nullable: false),
CreatorUserId = c.Long(),
},
annotations: new Dictionary<string, object>
{
{ "DynamicFilter_Setting_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.AbpUsers", t => t.UserId)
.Index(t => t.UserId);
CreateTable(
"dbo.AbpTenantNotifications",
c => new
{
Id = c.Guid(nullable: false),
TenantId = c.Int(),
NotificationName = c.String(nullable: false, maxLength: 96),
Data = c.String(),
DataTypeName = c.String(maxLength: 512),
EntityTypeName = c.String(maxLength: 250),
EntityTypeAssemblyQualifiedName = c.String(maxLength: 512),
EntityId = c.String(maxLength: 96),
Severity = c.Byte(nullable: false),
CreationTime = c.DateTime(nullable: false),
CreatorUserId = c.Long(),
},
annotations: new Dictionary<string, object>
{
{ "DynamicFilter_TenantNotificationInfo_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.AbpTenants",
c => new
{
Id = c.Int(nullable: false, identity: true),
EditionId = c.Int(),
Name = c.String(nullable: false, maxLength: 128),
IsActive = c.Boolean(nullable: false),
TenancyName = c.String(nullable: false, maxLength: 64),
ConnectionString = c.String(maxLength: 1024),
IsDeleted = c.Boolean(nullable: false),
DeleterUserId = c.Long(),
DeletionTime = c.DateTime(),
LastModificationTime = c.DateTime(),
LastModifierUserId = c.Long(),
CreationTime = c.DateTime(nullable: false),
CreatorUserId = c.Long(),
},
annotations: new Dictionary<string, object>
{
{ "DynamicFilter_Tenant_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.AbpUsers", t => t.CreatorUserId)
.ForeignKey("dbo.AbpUsers", t => t.DeleterUserId)
.ForeignKey("dbo.AbpEditions", t => t.EditionId)
.ForeignKey("dbo.AbpUsers", t => t.LastModifierUserId)
.Index(t => t.EditionId)
.Index(t => t.DeleterUserId)
.Index(t => t.LastModifierUserId)
.Index(t => t.CreatorUserId);
CreateTable(
"dbo.AbpUserAccounts",
c => new
{
Id = c.Long(nullable: false, identity: true),
TenantId = c.Int(),
UserId = c.Long(nullable: false),
UserLinkId = c.Long(),
UserName = c.String(),
EmailAddress = c.String(),
LastLoginTime = c.DateTime(),
IsDeleted = c.Boolean(nullable: false),
DeleterUserId = c.Long(),
DeletionTime = c.DateTime(),
LastModificationTime = c.DateTime(),
LastModifierUserId = c.Long(),
CreationTime = c.DateTime(nullable: false),
CreatorUserId = c.Long(),
},
annotations: new Dictionary<string, object>
{
{ "DynamicFilter_UserAccount_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.AbpUserLoginAttempts",
c => new
{
Id = c.Long(nullable: false, identity: true),
TenantId = c.Int(),
TenancyName = c.String(maxLength: 64),
UserId = c.Long(),
UserNameOrEmailAddress = c.String(maxLength: 255),
ClientIpAddress = c.String(maxLength: 64),
ClientName = c.String(maxLength: 128),
BrowserInfo = c.String(maxLength: 256),
Result = c.Byte(nullable: false),
CreationTime = c.DateTime(nullable: false),
},
annotations: new Dictionary<string, object>
{
{ "DynamicFilter_UserLoginAttempt_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
})
.PrimaryKey(t => t.Id)
.Index(t => new { t.UserId, t.TenantId })
.Index(t => new { t.TenancyName, t.UserNameOrEmailAddress, t.Result });
CreateTable(
"dbo.AbpUserNotifications",
c => new
{
Id = c.Guid(nullable: false),
TenantId = c.Int(),
UserId = c.Long(nullable: false),
TenantNotificationId = c.Guid(nullable: false),
State = c.Int(nullable: false),
CreationTime = c.DateTime(nullable: false),
},
annotations: new Dictionary<string, object>
{
{ "DynamicFilter_UserNotificationInfo_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
})
.PrimaryKey(t => t.Id)
.Index(t => new { t.UserId, t.State, t.CreationTime });
CreateTable(
"dbo.AbpUserOrganizationUnits",
c => new
{
Id = c.Long(nullable: false, identity: true),
TenantId = c.Int(),
UserId = c.Long(nullable: false),
OrganizationUnitId = c.Long(nullable: false),
CreationTime = c.DateTime(nullable: false),
CreatorUserId = c.Long(),
},
annotations: new Dictionary<string, object>
{
{ "DynamicFilter_UserOrganizationUnit_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
})
.PrimaryKey(t => t.Id);
CreateIndex("AbpAuditLogs", new[] { "TenantId", "ExecutionTime" });
CreateIndex("AbpAuditLogs", new[] { "UserId", "ExecutionTime" });
CreateIndex("AbpEditions", new[] { "Name" });
CreateIndex("AbpFeatures", new[] { "Discriminator", "TenantId", "Name" });
CreateIndex("AbpFeatures", new[] { "Discriminator", "EditionId", "Name" });
CreateIndex("AbpFeatures", new[] { "TenantId", "Name" });
CreateIndex("AbpLanguages", new[] { "TenantId", "Name" });
CreateIndex("AbpLanguageTexts", new[] { "TenantId", "LanguageName", "Source", "Key" });
CreateIndex("AbpOrganizationUnits", new[] { "TenantId", "ParentId" });
CreateIndex("AbpOrganizationUnits", new[] { "TenantId", "Code" });
DropIndex("AbpPermissions", new[] { "UserId" });
DropIndex("AbpPermissions", new[] { "RoleId" });
CreateIndex("AbpPermissions", new[] { "UserId", "Name" });
CreateIndex("AbpPermissions", new[] { "RoleId", "Name" });
CreateIndex("AbpRoles", new[] { "TenantId", "Name" });
CreateIndex("AbpRoles", new[] { "IsDeleted", "TenantId", "Name" });
DropIndex("AbpSettings", new[] { "UserId" });
CreateIndex("AbpSettings", new[] { "TenantId", "Name" });
CreateIndex("AbpSettings", new[] { "UserId", "Name" });
CreateIndex("AbpTenants", new[] { "TenancyName" });
CreateIndex("AbpTenants", new[] { "IsDeleted", "TenancyName" });
DropIndex("AbpUserLogins", new[] { "UserId" });
CreateIndex("AbpUserLogins", new[] { "UserId", "LoginProvider" });
CreateIndex("AbpUserOrganizationUnits", new[] { "TenantId", "UserId" });
CreateIndex("AbpUserOrganizationUnits", new[] { "TenantId", "OrganizationUnitId" });
CreateIndex("AbpUserOrganizationUnits", new[] { "UserId" });
CreateIndex("AbpUserOrganizationUnits", new[] { "OrganizationUnitId" });
DropIndex("AbpUserRoles", new[] { "UserId" });
CreateIndex("AbpUserRoles", new[] { "UserId", "RoleId" });
CreateIndex("AbpUserRoles", new[] { "RoleId" });
CreateIndex("AbpUsers", new[] { "TenantId", "UserName" });
CreateIndex("AbpUsers", new[] { "TenantId", "EmailAddress" });
CreateIndex("AbpUsers", new[] { "IsDeleted", "TenantId", "UserName" });
CreateIndex("AbpUsers", new[] { "IsDeleted", "TenantId", "EmailAddress" });
}
public override void Down()
{
DropIndex("AbpAuditLogs", new[] { "TenantId", "ExecutionTime" });
DropIndex("AbpAuditLogs", new[] { "UserId", "ExecutionTime" });
DropIndex("AbpEditions", new[] { "Name" });
DropIndex("AbpFeatures", new[] { "Discriminator", "TenantId", "Name" });
DropIndex("AbpFeatures", new[] { "Discriminator", "EditionId", "Name" });
DropIndex("AbpFeatures", new[] { "TenantId", "Name" });
DropIndex("AbpLanguages", new[] { "TenantId", "Name" });
DropIndex("AbpLanguageTexts", new[] { "TenantId", "LanguageName", "Source", "Key" });
DropIndex("AbpOrganizationUnits", new[] { "TenantId", "ParentId" });
DropIndex("AbpOrganizationUnits", new[] { "TenantId", "Code" });
CreateIndex("AbpPermissions", new[] { "UserId" });
CreateIndex("AbpPermissions", new[] { "RoleId" });
DropIndex("AbpPermissions", new[] { "UserId", "Name" });
DropIndex("AbpPermissions", new[] { "RoleId", "Name" });
DropIndex("AbpRoles", new[] { "TenantId", "Name" });
DropIndex("AbpRoles", new[] { "IsDeleted", "TenantId", "Name" });
CreateIndex("AbpSettings", new[] { "UserId" });
DropIndex("AbpSettings", new[] { "TenantId", "Name" });
DropIndex("AbpSettings", new[] { "UserId", "Name" });
DropIndex("AbpTenants", new[] { "TenancyName" });
DropIndex("AbpTenants", new[] { "IsDeleted", "TenancyName" });
CreateIndex("AbpUserLogins", new[] { "UserId" });
DropIndex("AbpUserLogins", new[] { "UserId", "LoginProvider" });
DropIndex("AbpUserOrganizationUnits", new[] { "TenantId", "UserId" });
DropIndex("AbpUserOrganizationUnits", new[] { "TenantId", "OrganizationUnitId" });
DropIndex("AbpUserOrganizationUnits", new[] { "UserId" });
DropIndex("AbpUserOrganizationUnits", new[] { "OrganizationUnitId" });
CreateIndex("AbpUserRoles", new[] { "UserId" });
DropIndex("AbpUserRoles", new[] { "UserId", "RoleId" });
DropIndex("AbpUserRoles", new[] { "RoleId" });
DropIndex("AbpUsers", new[] { "TenantId", "UserName" });
DropIndex("AbpUsers", new[] { "TenantId", "EmailAddress" });
DropIndex("AbpUsers", new[] { "IsDeleted", "TenantId", "UserName" });
DropIndex("AbpUsers", new[] { "IsDeleted", "TenantId", "EmailAddress" });
DropForeignKey("dbo.AbpTenants", "LastModifierUserId", "dbo.AbpUsers");
DropForeignKey("dbo.AbpTenants", "EditionId", "dbo.AbpEditions");
DropForeignKey("dbo.AbpTenants", "DeleterUserId", "dbo.AbpUsers");
DropForeignKey("dbo.AbpTenants", "CreatorUserId", "dbo.AbpUsers");
DropForeignKey("dbo.AbpPermissions", "RoleId", "dbo.AbpRoles");
DropForeignKey("dbo.AbpRoles", "LastModifierUserId", "dbo.AbpUsers");
DropForeignKey("dbo.AbpRoles", "DeleterUserId", "dbo.AbpUsers");
DropForeignKey("dbo.AbpRoles", "CreatorUserId", "dbo.AbpUsers");
DropForeignKey("dbo.AbpSettings", "UserId", "dbo.AbpUsers");
DropForeignKey("dbo.AbpUserRoles", "UserId", "dbo.AbpUsers");
DropForeignKey("dbo.AbpPermissions", "UserId", "dbo.AbpUsers");
DropForeignKey("dbo.AbpUserLogins", "UserId", "dbo.AbpUsers");
DropForeignKey("dbo.AbpUsers", "LastModifierUserId", "dbo.AbpUsers");
DropForeignKey("dbo.AbpUsers", "DeleterUserId", "dbo.AbpUsers");
DropForeignKey("dbo.AbpUsers", "CreatorUserId", "dbo.AbpUsers");
DropForeignKey("dbo.AbpUserClaims", "UserId", "dbo.AbpUsers");
DropForeignKey("dbo.AbpOrganizationUnits", "ParentId", "dbo.AbpOrganizationUnits");
DropForeignKey("dbo.AbpFeatures", "EditionId", "dbo.AbpEditions");
DropIndex("dbo.AbpUserNotifications", new[] { "UserId", "State", "CreationTime" });
DropIndex("dbo.AbpUserLoginAttempts", new[] { "TenancyName", "UserNameOrEmailAddress", "Result" });
DropIndex("dbo.AbpUserLoginAttempts", new[] { "UserId", "TenantId" });
DropIndex("dbo.AbpTenants", new[] { "CreatorUserId" });
DropIndex("dbo.AbpTenants", new[] { "LastModifierUserId" });
DropIndex("dbo.AbpTenants", new[] { "DeleterUserId" });
DropIndex("dbo.AbpTenants", new[] { "EditionId" });
DropIndex("dbo.AbpSettings", new[] { "UserId" });
DropIndex("dbo.AbpUserRoles", new[] { "UserId" });
DropIndex("dbo.AbpUserLogins", new[] { "UserId" });
DropIndex("dbo.AbpUserClaims", new[] { "UserId" });
DropIndex("dbo.AbpUsers", new[] { "CreatorUserId" });
DropIndex("dbo.AbpUsers", new[] { "LastModifierUserId" });
DropIndex("dbo.AbpUsers", new[] { "DeleterUserId" });
DropIndex("dbo.AbpRoles", new[] { "CreatorUserId" });
DropIndex("dbo.AbpRoles", new[] { "LastModifierUserId" });
DropIndex("dbo.AbpRoles", new[] { "DeleterUserId" });
DropIndex("dbo.AbpPermissions", new[] { "UserId" });
DropIndex("dbo.AbpPermissions", new[] { "RoleId" });
DropIndex("dbo.AbpOrganizationUnits", new[] { "ParentId" });
DropIndex("dbo.AbpNotificationSubscriptions", new[] { "NotificationName", "EntityTypeName", "EntityId", "UserId" });
DropIndex("dbo.AbpFeatures", new[] { "EditionId" });
DropIndex("dbo.AbpBackgroundJobs", new[] { "IsAbandoned", "NextTryTime" });
DropTable("dbo.AbpUserOrganizationUnits",
removedAnnotations: new Dictionary<string, object>
{
{ "DynamicFilter_UserOrganizationUnit_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
});
DropTable("dbo.AbpUserNotifications",
removedAnnotations: new Dictionary<string, object>
{
{ "DynamicFilter_UserNotificationInfo_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
});
DropTable("dbo.AbpUserLoginAttempts",
removedAnnotations: new Dictionary<string, object>
{
{ "DynamicFilter_UserLoginAttempt_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
});
DropTable("dbo.AbpUserAccounts",
removedAnnotations: new Dictionary<string, object>
{
{ "DynamicFilter_UserAccount_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
});
DropTable("dbo.AbpTenants",
removedAnnotations: new Dictionary<string, object>
{
{ "DynamicFilter_Tenant_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
});
DropTable("dbo.AbpTenantNotifications",
removedAnnotations: new Dictionary<string, object>
{
{ "DynamicFilter_TenantNotificationInfo_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
});
DropTable("dbo.AbpSettings",
removedAnnotations: new Dictionary<string, object>
{
{ "DynamicFilter_Setting_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
});
DropTable("dbo.AbpUserRoles",
removedAnnotations: new Dictionary<string, object>
{
{ "DynamicFilter_UserRole_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
});
DropTable("dbo.AbpUserLogins",
removedAnnotations: new Dictionary<string, object>
{
{ "DynamicFilter_UserLogin_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
});
DropTable("dbo.AbpUserClaims",
removedAnnotations: new Dictionary<string, object>
{
{ "DynamicFilter_UserClaim_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
});
DropTable("dbo.AbpUsers",
removedAnnotations: new Dictionary<string, object>
{
{ "DynamicFilter_User_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
{ "DynamicFilter_User_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
});
DropTable("dbo.AbpRoles",
removedAnnotations: new Dictionary<string, object>
{
{ "DynamicFilter_Role_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
{ "DynamicFilter_Role_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
});
DropTable("dbo.AbpPermissions",
removedAnnotations: new Dictionary<string, object>
{
{ "DynamicFilter_PermissionSetting_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
{ "DynamicFilter_RolePermissionSetting_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
{ "DynamicFilter_UserPermissionSetting_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
});
DropTable("dbo.AbpOrganizationUnits",
removedAnnotations: new Dictionary<string, object>
{
{ "DynamicFilter_OrganizationUnit_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
{ "DynamicFilter_OrganizationUnit_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
});
DropTable("dbo.AbpNotificationSubscriptions",
removedAnnotations: new Dictionary<string, object>
{
{ "DynamicFilter_NotificationSubscriptionInfo_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
});
DropTable("dbo.AbpNotifications");
DropTable("dbo.AbpLanguageTexts",
removedAnnotations: new Dictionary<string, object>
{
{ "DynamicFilter_ApplicationLanguageText_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
});
DropTable("dbo.AbpLanguages",
removedAnnotations: new Dictionary<string, object>
{
{ "DynamicFilter_ApplicationLanguage_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
{ "DynamicFilter_ApplicationLanguage_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
});
DropTable("dbo.AbpEditions",
removedAnnotations: new Dictionary<string, object>
{
{ "DynamicFilter_Edition_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
});
DropTable("dbo.AbpFeatures",
removedAnnotations: new Dictionary<string, object>
{
{ "DynamicFilter_TenantFeatureSetting_MustHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
});
DropTable("dbo.AbpBackgroundJobs");
DropTable("dbo.AbpAuditLogs",
removedAnnotations: new Dictionary<string, object>
{
{ "DynamicFilter_AuditLog_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
});
}
}
}
| |
/*
* QUANTCONNECT.COM -
* QC.Statistics - Generate statistics on the equity and orders
*/
/**********************************************************
* USING NAMESPACES
**********************************************************/
using System;
using System.Linq;
using System.Collections.Generic;
//QuantConnect Project Libraries:
using QuantConnect.Logging;
using QuantConnect.Models;
namespace QuantConnect {
/********************************************************
* CLASS DEFINITIONS
*********************************************************/
public class Statistics {
/********************************************************
* CLASS VARIABLES
*********************************************************/
/********************************************************
* CONSTRUCTOR/DELEGATE DEFINITIONS
*********************************************************/
/********************************************************
* CLASS METHODS
*********************************************************/
/// <summary>
/// Run a full set of orders and return a
/// </summary>
/// <param name="equity">Equity value over time.</param>
/// <param name="profitLoss">profit loss from trades</param>
/// <param name="startingCash">Amount of starting cash in USD </param>
/// <param name="fractionOfYears">Number of years as a double number 1 = 1 year. </param>
/// <returns>Statistics Array, Broken into Annual Periods</returns>
public static Dictionary<string, Dictionary<string, string>> Generate(SortedDictionary<DateTime, decimal> equity, SortedDictionary<DateTime, decimal> profitLoss, SortedDictionary<DateTime, decimal> performance, decimal startingCash, double fractionOfYears = 1) {
//Initialise the response:
decimal profitLossValue = 0, runningCash = startingCash;
List<int> years = new List<int>();
SortedDictionary<int, int> annualTrades = new SortedDictionary<int,int>();
SortedDictionary<int, int> annualWins = new SortedDictionary<int,int>();
SortedDictionary<int, int> annualLosses = new SortedDictionary<int,int>();
SortedDictionary<int, decimal> annualLossTotal = new SortedDictionary<int, decimal>();
SortedDictionary<int, decimal> annualWinTotal = new SortedDictionary<int, decimal>();
SortedDictionary<int, decimal> annualNetProfit = new SortedDictionary<int, decimal>();
Dictionary<string, Dictionary<string, string>> statistics = new Dictionary<string, Dictionary<string, string>>();
//Set defaults in case of failure:
decimal totalTrades = 0;
decimal totalWins = 0;
decimal totalLosses = 0;
decimal averageWin = 0;
decimal averageLoss = 0;
decimal averageWinRatio = 0;
decimal winRate = 0;
decimal lossRate = 0;
decimal totalNetProfit = 0;
decimal averageAnnualReturn = 0;
TradeFrequency frequency = TradeFrequency.Daily;
try {
//Run over each equity day:
foreach (DateTime closedTrade in profitLoss.Keys) {
profitLossValue = profitLoss[closedTrade];
//Check if this date is in the "years" array:
int year = closedTrade.Year;
if (!years.Contains(year)) {
//Initialise a new year holder:
years.Add(year);
annualTrades.Add(year, 0);
annualWins.Add(year, 0);
annualWinTotal.Add(year, 0);
annualLosses.Add(year, 0);
annualLossTotal.Add(year, 0);
//lStatistics.Add(iYear.ToString(), new Dictionary<Statistic, decimal>());
}
//Add another trade:
annualTrades[year]++;
//Profit loss tracking:
if (profitLossValue > 0) {
annualWins[year]++;
annualWinTotal[year] += profitLossValue / runningCash;
} else {
annualLosses[year]++;
annualLossTotal[year] += profitLossValue / runningCash;
}
//Increment the cash:
runningCash += profitLossValue;
}
//Get the annual percentage of profit and loss:
foreach (int year in years) {
annualNetProfit[year] = (annualWinTotal[year] + annualLossTotal[year]);
}
//Sum the totals:
try {
if (profitLoss.Keys.Count > 0) {
totalTrades = annualTrades.Values.Sum();
totalWins = annualWins.Values.Sum();
totalLosses = annualLosses.Values.Sum();
totalNetProfit = (equity.Values.LastOrDefault() / startingCash) - 1;
try {
if (fractionOfYears > 0) {
averageAnnualReturn = totalNetProfit / Convert.ToDecimal(fractionOfYears);
} else {
averageAnnualReturn = totalNetProfit;
}
} catch (Exception err) {
Log.Error("Statistics() Annual Average Return: " + err.Message);
averageAnnualReturn = annualNetProfit.Values.Average();
}
//-> Handle Div/0 Errors
if (totalWins == 0) {
averageWin = 0;
} else {
averageWin = annualWinTotal.Values.Sum() / totalWins;
}
if (totalLosses == 0) {
averageLoss = 0;
averageWinRatio = 0;
} else {
averageLoss = annualLossTotal.Values.Sum() / totalLosses;
averageWinRatio = Math.Abs(averageWin / averageLoss);
}
if (totalTrades == 0) {
winRate = 0;
lossRate = 0;
} else {
winRate = Math.Round(totalWins / totalTrades, 5);
lossRate = Math.Round(totalLosses / totalTrades, 5);
}
//Get the frequency:
frequency = Statistics.Frequency(totalTrades, equity.Keys.FirstOrDefault(), equity.Keys.LastOrDefault());
}
} catch (Exception err) {
Log.Error("Statistics.RunOrders(): Second Half: " + err.Message);
}
decimal profitLossRatio = Statistics.ProfitLossRatio(averageWin, averageLoss);
string profitLossRatioHuman = profitLossRatio.ToString();
if (profitLossRatio == -1) profitLossRatioHuman = "0";
//Add the over all results first, break down by year later:
statistics.Add("Overall", new Dictionary<string, string>() {
{ "Total Trades", Math.Round(totalTrades, 0).ToString() },
{ "Average Win", Math.Round(averageWin * 100, 2) + "%" },
{ "Average Loss", Math.Round(averageLoss * 100, 2) + "%" },
{ "Annual Return", Math.Round(averageAnnualReturn * 100, 3) + "%" },
{ "Drawdown", (Statistics.Drawdown(equity, 3) * 100) + "%" },
{ "Expectancy", Math.Round((winRate * averageWinRatio) - (lossRate), 3).ToString() },
{ "Net Profit", Math.Round(totalNetProfit * 100, 3) + "%"},
{ "Sharpe Ratio", Statistics.SharpeRatio(equity, performance, startingCash, averageAnnualReturn).ToString() },
{ "Loss Rate", Math.Round(lossRate * 100) + "%" },
{ "Win Rate", Math.Round(winRate * 100) + "%" },
{ "Profit-Loss Ratio", profitLossRatioHuman },
{ "Trade Frequency", frequency.ToString() + " trades" }
});
} catch (Exception err) {
Log.Error("QC.Statistics.RunOrders(): " + err.Message + err.InnerException + err.TargetSite);
}
return statistics;
}
/// <summary>
/// Return profit loss ratio safely.
/// </summary>
/// <param name="averageWin"></param>
/// <param name="averageLoss"></param>
/// <returns></returns>
public static decimal ProfitLossRatio(decimal averageWin, decimal averageLoss) {
if (averageLoss == 0) {
return -1;
} else {
return Math.Round(averageWin / Math.Abs(averageLoss), 2);
}
}
/// <summary>
/// Get an approximation of the trade frequency:
/// </summary>
/// <param name="dTotalTrades">Number of trades in this period</param>
/// <param name="dtStart">Start of Period</param>
/// <param name="dtEnd">End of Period</param>
/// <returns>Enum Frequency</returns>
public static TradeFrequency Frequency(decimal totalTrades, DateTime start, DateTime end) {
//Average number of trades per day:
decimal period = Convert.ToDecimal((end - start).TotalDays);
if (period == 0) {
return TradeFrequency.Weekly;
}
decimal averageDaily = totalTrades / period;
if (averageDaily > 200m) {
return TradeFrequency.Secondly;
} else if (averageDaily > 50m) {
return TradeFrequency.Minutely;
} else if (averageDaily > 5m) {
return TradeFrequency.Hourly;
} else if (averageDaily > 0.75m) {
return TradeFrequency.Daily;
} else {
return TradeFrequency.Weekly;
}
}
/// <summary>
/// Get the Drawdown Statistic for this Period.
/// </summary>
/// <param name="equityOverTime">Array of portfolio value over time.</param>
/// <param name="rounding">Round the drawdown statistics </param>
/// <returns>Draw down percentage over period.</returns>
public static decimal Drawdown(SortedDictionary<DateTime, decimal> equityOverTime, int rounding = 2) {
//Initialise:
int priceMaximum = 0;
int previousMinimum = 0;
int previousMaximum = 0;
try
{
List<decimal> lPrices = equityOverTime.Values.ToList<decimal>();
for (int id = 0; id < lPrices.Count; id++) {
if (lPrices[id] >= lPrices[priceMaximum]) {
priceMaximum = id;
} else {
if ((lPrices[priceMaximum] - lPrices[id]) > (lPrices[previousMaximum] - lPrices[previousMinimum])) {
previousMaximum = priceMaximum;
previousMinimum = id;
}
}
}
return Math.Round((lPrices[previousMaximum] - lPrices[previousMinimum]) / lPrices[previousMaximum], rounding);
} catch(Exception err)
{
Log.Error("Statistics.Drawdown(): " + err.Message);
}
return 0;
} // End Drawdown:
/// <summary>
/// Get the Sharpe Ratio of this period:
/// </summary>
/// <param name="equity">Equity of this period.</param>
/// <param name="averageAnnualGrowth">Percentage annual growth</param>
/// <param name="rounding">decimal rounding</param>
/// <param name="startingCash">Starting cash for the conversion to percentages</param>
/// <returns>decimal sharpe.</returns>
public static decimal SharpeRatio(SortedDictionary<DateTime, decimal> equity, SortedDictionary<DateTime, decimal> performance, decimal startingCash, decimal averageAnnualGrowth, int rounding = 1)
{
//Initialise
decimal sharpe = 0;
try {
decimal[] equityCash = equity.Values.ToArray();
decimal[] dailyPerformance = performance.Values.ToArray();
List<decimal> equityPercent = new List<decimal>();
//Sharpe = Mean Daily Performance * Sqrt (252) / StdDeviation of Returns
decimal averageDailyPerformance = dailyPerformance.Average();
decimal standardDeviationOfReturns = QCMath.StandardDeviation(dailyPerformance);
Log.Trace("Avg Daily Performance: " + averageDailyPerformance + " Std Dev: " + standardDeviationOfReturns.ToString());
if (standardDeviationOfReturns > 0)
{
sharpe = (averageDailyPerformance * Convert.ToDecimal(Math.Sqrt(252))) / standardDeviationOfReturns;
}
Log.Trace("SHARPE RATIO: " + sharpe.ToString());
} catch (Exception err) {
Log.Error("Statistics.SharpeRatio(): " + err.Message);
}
if (sharpe > 10) {
sharpe = Math.Round(sharpe, 0);
} else if (sharpe > 0 & sharpe < 10) {
sharpe = Math.Round(sharpe, 1);
} else if (sharpe < 0) {
sharpe = Math.Round(sharpe, 1);
}
return sharpe;
}
} // End of Statistics
} // End of Namespace
| |
//
// FacebookExport.cs
//
// Author:
// Stephane Delcroix <stephane@delcroix.org>
// Jim Ramsay <i.am@jimramsay.com>
// Stephen Shaw <sshaw@decriptor.com>
//
// Copyright (C) 2007-2009 Novell, Inc.
// Copyright (C) 2007-2009 Stephane Delcroix
// Copyright (C) 2009 Jim Ramsay
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using Mono.Unix;
using Gtk;
using Gnome.Keyring;
using FSpot.Core;
using FSpot.UI.Dialog;
using FSpot.Extensions;
using FSpot.Filters;
using Hyena;
using Hyena.Widgets;
using Mono.Facebook;
namespace FSpot.Exporters.Facebook
{
internal class FacebookAccount
{
static string keyring_item_name = "Facebook Account";
static string api_key = "c23d1683e87313fa046954ea253a240e";
/* INSECURE! According to:
*
* http://wiki.developers.facebook.com/index.php/Desktop_App_Auth_Process
*
* We should *NOT* put our secret code here, but do an external
* authorization using our own PHP page somewhere.
*/
static string secret = "743e9a2e6a1c35ce961321bceea7b514";
FacebookSession facebookSession;
bool connected = false;
public FacebookAccount ()
{
SessionInfo info = ReadSessionInfo ();
if (info != null) {
facebookSession = new FacebookSession (api_key, info);
try {
/* This basically functions like a ping to ensure the
* session is still valid:
*/
facebookSession.HasAppPermission("offline_access");
connected = true;
} catch (FacebookException) {
connected = false;
}
}
}
public Uri GetLoginUri ()
{
FacebookSession session = new FacebookSession (api_key, secret);
Uri uri = session.CreateToken();
facebookSession = session;
connected = false;
return uri;
}
public bool RevokePermission (string permission)
{
return facebookSession.RevokeAppPermission(permission);
}
public bool GrantPermission (string permission, Window parent)
{
if (facebookSession.HasAppPermission(permission))
return true;
Uri uri = facebookSession.GetGrantUri (permission);
GtkBeans.Global.ShowUri (parent.Screen, uri.ToString ());
HigMessageDialog mbox = new HigMessageDialog (parent, Gtk.DialogFlags.DestroyWithParent | Gtk.DialogFlags.Modal,
Gtk.MessageType.Info, Gtk.ButtonsType.Ok, Catalog.GetString ("Waiting for authorization"),
Catalog.GetString ("F-Spot will now launch your browser so that you can enable the permission you just selected.\n\nOnce you are directed by Facebook to return to this application, click \"Ok\" below." ));
mbox.Run ();
mbox.Destroy ();
return facebookSession.HasAppPermission(permission);
}
public bool HasPermission(string permission)
{
return facebookSession.HasAppPermission(permission);
}
public FacebookSession Facebook
{
get { return facebookSession; }
}
public bool Authenticated
{
get { return connected; }
}
bool SaveSessionInfo (SessionInfo info)
{
string keyring;
try {
keyring = Ring.GetDefaultKeyring();
} catch (KeyringException e) {
Log.DebugException (e);
return false;
}
Hashtable attribs = new Hashtable();
//Dictionary<string,string> attribs = new Dictionary<string, string> ();
attribs["name"] = keyring_item_name;
attribs["uid"] = info.uid.ToString ();
attribs["session_key"] = info.session_key;
try {
Ring.CreateItem (keyring, ItemType.GenericSecret, keyring_item_name, attribs, info.secret, true);
} catch (KeyringException e) {
Log.DebugException (e);
return false;
}
return true;
}
SessionInfo ReadSessionInfo ()
{
SessionInfo info = null;
Hashtable request_attributes = new Hashtable ();
//Dictionary<string, string> request_attributes = new Dictionary<string, string> ();
request_attributes["name"] = keyring_item_name;
try {
foreach (ItemData result in Ring.Find (ItemType.GenericSecret, request_attributes)) {
if (!result.Attributes.ContainsKey ("name") ||
!result.Attributes.ContainsKey ("uid") ||
!result.Attributes.ContainsKey ("session_key") ||
(result.Attributes["name"] as string) != keyring_item_name)
continue;
string session_key = (string)result.Attributes["session_key"];
long uid = Int64.Parse((string)result.Attributes["uid"]);
string secret = result.Secret;
info = new SessionInfo (session_key, uid, secret);
break;
}
} catch (KeyringException e) {
Log.DebugException (e);
}
return info;
}
bool ForgetSessionInfo()
{
string keyring;
bool success = false;
try {
keyring = Ring.GetDefaultKeyring();
} catch (KeyringException e) {
Log.DebugException (e);
return false;
}
Hashtable request_attributes = new Hashtable ();
//Dictionary<string,string> request_attributes = new Dictionary<string, string> ();
request_attributes["name"] = keyring_item_name;
try {
foreach (ItemData result in Ring.Find (ItemType.GenericSecret, request_attributes)) {
Ring.DeleteItem(keyring, result.ItemID);
success = true;
}
} catch (KeyringException e) {
Log.DebugException (e);
}
return success;
}
public bool Authenticate ()
{
if (connected)
return true;
try {
SessionInfo info = facebookSession.GetSession();
connected = true;
if (SaveSessionInfo (info))
Log.Information ("Saved session information to keyring");
else
Log.Warning ("Could not save session information to keyring");
} catch (KeyringException e) {
connected = false;
Log.DebugException (e);
} catch (FacebookException fe) {
connected = false;
Log.DebugException (fe);
}
return connected;
}
public void Deauthenticate ()
{
connected = false;
ForgetSessionInfo ();
}
}
internal class TagStore : ListStore
{
private List<Mono.Facebook.Tag> _tags;
private Dictionary<long, User> _friends;
public TagStore (FacebookSession session, List<Mono.Facebook.Tag> tags, Dictionary<long, User> friends) : base (typeof (string))
{
_tags = tags;
_friends = friends;
foreach (Mono.Facebook.Tag tag in Tags) {
long subject = tag.Subject;
User info = _friends [subject];
if (info == null ) {
try {
info = session.GetUserInfo (new long[] { subject }, new string[] { "first_name", "last_name" }) [0];
}
catch (FacebookException) {
continue;
}
}
AppendValues (String.Format ("{0} {1}", info.first_name ?? "", info.last_name ?? ""));
}
}
public List<Mono.Facebook.Tag> Tags
{
get { return _tags ?? new List<Mono.Facebook.Tag> (); }
}
}
public class FacebookExport : IExporter
{
private int size = 720;
private int max_photos_per_album = 200;
FacebookExportDialog dialog;
ThreadProgressDialog progress_dialog;
System.Threading.Thread command_thread;
Album album = null;
public FacebookExport ()
{
}
public void Run (IBrowsableCollection selection)
{
dialog = new FacebookExportDialog (selection);
if (selection.Items.Length > max_photos_per_album) {
HigMessageDialog mbox = new HigMessageDialog (dialog,
Gtk.DialogFlags.DestroyWithParent | Gtk.DialogFlags.Modal, Gtk.MessageType.Error,
Gtk.ButtonsType.Ok, Catalog.GetString ("Too many images to export"),
String.Format (Catalog.GetString ("Facebook only permits {0} photographs per album. Please refine your selection and try again."), max_photos_per_album));
mbox.Run ();
mbox.Destroy ();
return;
}
if (dialog.Run () != (int)ResponseType.Ok) {
dialog.Destroy ();
return;
}
if (dialog.CreateAlbum) {
string name = dialog.AlbumName;
if (String.IsNullOrEmpty (name)) {
HigMessageDialog mbox = new HigMessageDialog (dialog, Gtk.DialogFlags.DestroyWithParent | Gtk.DialogFlags.Modal,
Gtk.MessageType.Error, Gtk.ButtonsType.Ok, Catalog.GetString ("Album must have a name"),
Catalog.GetString ("Please name your album or choose an existing album."));
mbox.Run ();
mbox.Destroy ();
return;
}
string description = dialog.AlbumDescription;
string location = dialog.AlbumLocation;
try {
album = dialog.Account.Facebook.CreateAlbum (name, description, location);
}
catch (FacebookException fe) {
HigMessageDialog mbox = new HigMessageDialog (dialog, Gtk.DialogFlags.DestroyWithParent | Gtk.DialogFlags.Modal,
Gtk.MessageType.Error, Gtk.ButtonsType.Ok, Catalog.GetString ("Creating a new album failed"),
String.Format (Catalog.GetString ("An error occurred creating a new album.\n\n{0}"), fe.Message));
mbox.Run ();
mbox.Destroy ();
return;
}
} else {
album = dialog.ActiveAlbum;
}
if (dialog.Account != null) {
dialog.Hide ();
command_thread = new System.Threading.Thread (new System.Threading.ThreadStart (Upload));
command_thread.Name = Mono.Unix.Catalog.GetString ("Uploading Pictures");
progress_dialog = new ThreadProgressDialog (command_thread, selection.Items.Length);
progress_dialog.Start ();
}
dialog.Destroy ();
}
void Upload ()
{
IPhoto [] items = dialog.Items;
string [] captions = dialog.Captions;
dialog.StoreCaption ();
long sent_bytes = 0;
FilterSet filters = new FilterSet ();
filters.Add (new JpegFilter ());
filters.Add (new ResizeFilter ((uint) size));
for (int i = 0; i < items.Length; i++) {
try {
IPhoto item = items [i];
FileInfo file_info;
Log.DebugFormat ("uploading {0}", i);
progress_dialog.Message = String.Format (Catalog.GetString ("Uploading picture \"{0}\" ({1} of {2})"), item.Name, i + 1, items.Length);
progress_dialog.ProgressText = string.Empty;
progress_dialog.Fraction = i / (double) items.Length;
FilterRequest request = new FilterRequest (item.DefaultVersion.Uri);
filters.Convert (request);
file_info = new FileInfo (request.Current.LocalPath);
album.Upload (captions [i] ?? "", request.Current.LocalPath);
sent_bytes += file_info.Length;
}
catch (Exception e) {
progress_dialog.Message = String.Format (Catalog.GetString ("Error Uploading To Facebook: {0}"), e.Message);
progress_dialog.ProgressText = Catalog.GetString ("Error");
Log.DebugException (e);
if (progress_dialog.PerformRetrySkip ())
i--;
}
}
progress_dialog.Message = Catalog.GetString ("Done Sending Photos");
progress_dialog.Fraction = 1.0;
progress_dialog.ProgressText = Catalog.GetString ("Upload Complete");
progress_dialog.ButtonLabel = Gtk.Stock.Ok;
var li = new LinkButton ("http://www.facebook.com/group.php?gid=158960179844&ref=mf", Catalog.GetString ("Visit F-Spot group on Facebook"));
progress_dialog.VBoxPackEnd (li);
li.ShowAll ();
}
}
}
| |
#region Apache License
//
// 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.
//
#endregion
using System;
using System.Collections;
using Ctrip.Log4.Appender;
using Ctrip.Log4.Util;
using Ctrip.Log4.Core;
namespace Ctrip.Log4.Repository.Hierarchy
{
/// <summary>
/// Implementation of <see cref="ILogger"/> used by <see cref="Hierarchy"/>
/// </summary>
/// <remarks>
/// <para>
/// Internal class used to provide implementation of <see cref="ILogger"/>
/// interface. Applications should use <see cref="LogManager"/> to get
/// logger instances.
/// </para>
/// <para>
/// This is one of the central classes in the Ctrip implementation. One of the
/// distinctive features of Ctrip are hierarchical loggers and their
/// evaluation. The <see cref="Hierarchy"/> organizes the <see cref="Logger"/>
/// instances into a rooted tree hierarchy.
/// </para>
/// <para>
/// The <see cref="Logger"/> class is abstract. Only concrete subclasses of
/// <see cref="Logger"/> can be created. The <see cref="ILoggerFactory"/>
/// is used to create instances of this type for the <see cref="Hierarchy"/>.
/// </para>
/// </remarks>
/// <author>Nicko Cadell</author>
/// <author>Gert Driesen</author>
/// <author>Aspi Havewala</author>
/// <author>Douglas de la Torre</author>
public abstract class Logger : IAppenderAttachable, ILogger
{
#region Protected Instance Constructors
/// <summary>
/// This constructor created a new <see cref="Logger" /> instance and
/// sets its name.
/// </summary>
/// <param name="name">The name of the <see cref="Logger" />.</param>
/// <remarks>
/// <para>
/// This constructor is protected and designed to be used by
/// a subclass that is not abstract.
/// </para>
/// <para>
/// Loggers are constructed by <see cref="ILoggerFactory"/>
/// objects. See <see cref="DefaultLoggerFactory"/> for the default
/// logger creator.
/// </para>
/// </remarks>
protected Logger(string name)
{
#if NETCF
// NETCF: String.Intern causes Native Exception
m_name = name;
#else
m_name = string.Intern(name);
#endif
}
#endregion Protected Instance Constructors
#region Public Instance Properties
/// <summary>
/// Gets or sets the parent logger in the hierarchy.
/// </summary>
/// <value>
/// The parent logger in the hierarchy.
/// </value>
/// <remarks>
/// <para>
/// Part of the Composite pattern that makes the hierarchy.
/// The hierarchy is parent linked rather than child linked.
/// </para>
/// </remarks>
virtual public Logger Parent
{
get { return m_parent; }
set { m_parent = value; }
}
/// <summary>
/// Gets or sets a value indicating if child loggers inherit their parent's appenders.
/// </summary>
/// <value>
/// <c>true</c> if child loggers inherit their parent's appenders.
/// </value>
/// <remarks>
/// <para>
/// Additivity is set to <c>true</c> by default, that is children inherit
/// the appenders of their ancestors by default. If this variable is
/// set to <c>false</c> then the appenders found in the
/// ancestors of this logger are not used. However, the children
/// of this logger will inherit its appenders, unless the children
/// have their additivity flag set to <c>false</c> too. See
/// the user manual for more details.
/// </para>
/// </remarks>
virtual public bool Additivity
{
get { return m_additive; }
set { m_additive = value; }
}
/// <summary>
/// Gets the effective level for this logger.
/// </summary>
/// <returns>The nearest level in the logger hierarchy.</returns>
/// <remarks>
/// <para>
/// Starting from this logger, searches the logger hierarchy for a
/// non-null level and returns it. Otherwise, returns the level of the
/// root logger.
/// </para>
/// <para>The Logger class is designed so that this method executes as
/// quickly as possible.</para>
/// </remarks>
virtual public Level EffectiveLevel
{
get
{
for(Logger c = this; c != null; c = c.m_parent)
{
Level level = c.m_level;
// Casting level to Object for performance, otherwise the overloaded operator is called
if ((object)level != null)
{
return level;
}
}
return null; // If reached will cause an NullPointerException.
}
}
/// <summary>
/// Gets or sets the <see cref="Hierarchy"/> where this
/// <c>Logger</c> instance is attached to.
/// </summary>
/// <value>The hierarchy that this logger belongs to.</value>
/// <remarks>
/// <para>
/// This logger must be attached to a single <see cref="Hierarchy"/>.
/// </para>
/// </remarks>
virtual public Hierarchy Hierarchy
{
get { return m_hierarchy; }
set { m_hierarchy = value; }
}
/// <summary>
/// Gets or sets the assigned <see cref="Level"/>, if any, for this Logger.
/// </summary>
/// <value>
/// The <see cref="Level"/> of this logger.
/// </value>
/// <remarks>
/// <para>
/// The assigned <see cref="Level"/> can be <c>null</c>.
/// </para>
/// </remarks>
virtual public Level Level
{
get { return m_level; }
set { m_level = value; }
}
#endregion Public Instance Properties
#region Implementation of IAppenderAttachable
/// <summary>
/// Add <paramref name="newAppender"/> to the list of appenders of this
/// Logger instance.
/// </summary>
/// <param name="newAppender">An appender to add to this logger</param>
/// <remarks>
/// <para>
/// Add <paramref name="newAppender"/> to the list of appenders of this
/// Logger instance.
/// </para>
/// <para>
/// If <paramref name="newAppender"/> is already in the list of
/// appenders, then it won't be added again.
/// </para>
/// </remarks>
virtual public void AddAppender(IAppender newAppender)
{
if (newAppender == null)
{
throw new ArgumentNullException("newAppender");
}
m_appenderLock.AcquireWriterLock();
try
{
if (m_appenderAttachedImpl == null)
{
m_appenderAttachedImpl = new Ctrip.Log4.Util.AppenderAttachedImpl();
}
m_appenderAttachedImpl.AddAppender(newAppender);
}
finally
{
m_appenderLock.ReleaseWriterLock();
}
}
/// <summary>
/// Get the appenders contained in this logger as an
/// <see cref="System.Collections.ICollection"/>.
/// </summary>
/// <returns>A collection of the appenders in this logger</returns>
/// <remarks>
/// <para>
/// Get the appenders contained in this logger as an
/// <see cref="System.Collections.ICollection"/>. If no appenders
/// can be found, then a <see cref="EmptyCollection"/> is returned.
/// </para>
/// </remarks>
virtual public AppenderCollection Appenders
{
get
{
m_appenderLock.AcquireReaderLock();
try
{
if (m_appenderAttachedImpl == null)
{
return AppenderCollection.EmptyCollection;
}
else
{
return m_appenderAttachedImpl.Appenders;
}
}
finally
{
m_appenderLock.ReleaseReaderLock();
}
}
}
/// <summary>
/// Look for the appender named as <c>name</c>
/// </summary>
/// <param name="name">The name of the appender to lookup</param>
/// <returns>The appender with the name specified, or <c>null</c>.</returns>
/// <remarks>
/// <para>
/// Returns the named appender, or null if the appender is not found.
/// </para>
/// </remarks>
virtual public IAppender GetAppender(string name)
{
m_appenderLock.AcquireReaderLock();
try
{
if (m_appenderAttachedImpl == null || name == null)
{
return null;
}
return m_appenderAttachedImpl.GetAppender(name);
}
finally
{
m_appenderLock.ReleaseReaderLock();
}
}
/// <summary>
/// Remove all previously added appenders from this Logger instance.
/// </summary>
/// <remarks>
/// <para>
/// Remove all previously added appenders from this Logger instance.
/// </para>
/// <para>
/// This is useful when re-reading configuration information.
/// </para>
/// </remarks>
virtual public void RemoveAllAppenders()
{
m_appenderLock.AcquireWriterLock();
try
{
if (m_appenderAttachedImpl != null)
{
m_appenderAttachedImpl.RemoveAllAppenders();
m_appenderAttachedImpl = null;
}
}
finally
{
m_appenderLock.ReleaseWriterLock();
}
}
/// <summary>
/// Remove the appender passed as parameter form the list of appenders.
/// </summary>
/// <param name="appender">The appender to remove</param>
/// <returns>The appender removed from the list</returns>
/// <remarks>
/// <para>
/// Remove the appender passed as parameter form the list of appenders.
/// The appender removed is not closed.
/// If you are discarding the appender you must call
/// <see cref="IAppender.Close"/> on the appender removed.
/// </para>
/// </remarks>
virtual public IAppender RemoveAppender(IAppender appender)
{
m_appenderLock.AcquireWriterLock();
try
{
if (appender != null && m_appenderAttachedImpl != null)
{
return m_appenderAttachedImpl.RemoveAppender(appender);
}
}
finally
{
m_appenderLock.ReleaseWriterLock();
}
return null;
}
/// <summary>
/// Remove the appender passed as parameter form the list of appenders.
/// </summary>
/// <param name="name">The name of the appender to remove</param>
/// <returns>The appender removed from the list</returns>
/// <remarks>
/// <para>
/// Remove the named appender passed as parameter form the list of appenders.
/// The appender removed is not closed.
/// If you are discarding the appender you must call
/// <see cref="IAppender.Close"/> on the appender removed.
/// </para>
/// </remarks>
virtual public IAppender RemoveAppender(string name)
{
m_appenderLock.AcquireWriterLock();
try
{
if (name != null && m_appenderAttachedImpl != null)
{
return m_appenderAttachedImpl.RemoveAppender(name);
}
}
finally
{
m_appenderLock.ReleaseWriterLock();
}
return null;
}
#endregion
#region Implementation of ILogger
/// <summary>
/// Gets the logger name.
/// </summary>
/// <value>
/// The name of the logger.
/// </value>
/// <remarks>
/// <para>
/// The name of this logger
/// </para>
/// </remarks>
virtual public string Name
{
get { return m_name; }
}
/// <summary>
/// This generic form is intended to be used by wrappers.
/// </summary>
/// <param name="callerStackBoundaryDeclaringType">The declaring type of the method that is
/// the stack boundary into the logging system for this call.</param>
/// <param name="level">The level of the message to be logged.</param>
/// <param name="message">The message object to log.</param>
/// <param name="exception">The exception to log, including its stack trace.</param>
/// <remarks>
/// <para>
/// Generate a logging event for the specified <paramref name="level"/> using
/// the <paramref name="message"/> and <paramref name="exception"/>.
/// </para>
/// <para>
/// This method must not throw any exception to the caller.
/// </para>
/// </remarks>
virtual public void Log(Type callerStackBoundaryDeclaringType, Level level, object message, Exception exception)
{
try
{
if (IsEnabledFor(level))
{
ForcedLog((callerStackBoundaryDeclaringType != null) ? callerStackBoundaryDeclaringType : declaringType, level, message, exception);
}
}
catch (Exception ex)
{
Ctrip.Log4.Util.LogLog.Error(declaringType, "Exception while logging", ex);
}
#if !NET_2_0 && !MONO_2_0
catch
{
Ctrip.Log4.Util.LogLog.Error(declaringType, "Exception while logging");
}
#endif
}
/// <summary>
/// This is the most generic printing method that is intended to be used
/// by wrappers.
/// </summary>
/// <param name="logEvent">The event being logged.</param>
/// <remarks>
/// <para>
/// Logs the specified logging event through this logger.
/// </para>
/// <para>
/// This method must not throw any exception to the caller.
/// </para>
/// </remarks>
virtual public void Log(LoggingEvent logEvent)
{
try
{
if (logEvent != null)
{
if (IsEnabledFor(logEvent.Level))
{
ForcedLog(logEvent);
}
}
}
catch (Exception ex)
{
Ctrip.Log4.Util.LogLog.Error(declaringType, "Exception while logging", ex);
}
#if !NET_2_0 && !MONO_2_0
catch
{
Ctrip.Log4.Util.LogLog.Error(declaringType, "Exception while logging");
}
#endif
}
/// <summary>
/// Checks if this logger is enabled for a given <see cref="Level"/> passed as parameter.
/// </summary>
/// <param name="level">The level to check.</param>
/// <returns>
/// <c>true</c> if this logger is enabled for <c>level</c>, otherwise <c>false</c>.
/// </returns>
/// <remarks>
/// <para>
/// Test if this logger is going to log events of the specified <paramref name="level"/>.
/// </para>
/// <para>
/// This method must not throw any exception to the caller.
/// </para>
/// </remarks>
virtual public bool IsEnabledFor(Level level)
{
try
{
if (level != null)
{
if (m_hierarchy.IsDisabled(level))
{
return false;
}
return level >= this.EffectiveLevel;
}
}
catch (Exception ex)
{
Ctrip.Log4.Util.LogLog.Error(declaringType, "Exception while logging", ex);
}
#if !NET_2_0 && !MONO_2_0
catch
{
Ctrip.Log4.Util.LogLog.Error(declaringType, "Exception while logging");
}
#endif
return false;
}
/// <summary>
/// Gets the <see cref="ILoggerRepository"/> where this
/// <c>Logger</c> instance is attached to.
/// </summary>
/// <value>
/// The <see cref="ILoggerRepository" /> that this logger belongs to.
/// </value>
/// <remarks>
/// <para>
/// Gets the <see cref="ILoggerRepository"/> where this
/// <c>Logger</c> instance is attached to.
/// </para>
/// </remarks>
public ILoggerRepository Repository
{
get { return m_hierarchy; }
}
#endregion Implementation of ILogger
/// <summary>
/// Deliver the <see cref="LoggingEvent"/> to the attached appenders.
/// </summary>
/// <param name="loggingEvent">The event to log.</param>
/// <remarks>
/// <para>
/// Call the appenders in the hierarchy starting at
/// <c>this</c>. If no appenders could be found, emit a
/// warning.
/// </para>
/// <para>
/// This method calls all the appenders inherited from the
/// hierarchy circumventing any evaluation of whether to log or not
/// to log the particular log request.
/// </para>
/// </remarks>
virtual protected void CallAppenders(LoggingEvent loggingEvent)
{
if (loggingEvent == null)
{
throw new ArgumentNullException("loggingEvent");
}
int writes = 0;
for(Logger c=this; c != null; c=c.m_parent)
{
if (c.m_appenderAttachedImpl != null)
{
// Protected against simultaneous call to addAppender, removeAppender,...
c.m_appenderLock.AcquireReaderLock();
try
{
if (c.m_appenderAttachedImpl != null)
{
writes += c.m_appenderAttachedImpl.AppendLoopOnAppenders(loggingEvent);
}
}
finally
{
c.m_appenderLock.ReleaseReaderLock();
}
}
if (!c.m_additive)
{
break;
}
}
// No appenders in hierarchy, warn user only once.
//
// Note that by including the AppDomain values for the currently running
// thread, it becomes much easier to see which application the warning
// is from, which is especially helpful in a multi-AppDomain environment
// (like IIS with multiple VDIRS). Without this, it can be difficult
// or impossible to determine which .config file is missing appender
// definitions.
//
if (!m_hierarchy.EmittedNoAppenderWarning && writes == 0)
{
LogLog.Debug(declaringType, "No appenders could be found for logger [" + Name + "] repository [" + Repository.Name + "]");
LogLog.Debug(declaringType, "Please initialize the Ctrip system properly.");
try
{
LogLog.Debug(declaringType, " Current AppDomain context information: ");
LogLog.Debug(declaringType, " BaseDirectory : " + SystemInfo.ApplicationBaseDirectory);
#if !NETCF
LogLog.Debug(declaringType, " FriendlyName : " + AppDomain.CurrentDomain.FriendlyName);
LogLog.Debug(declaringType, " DynamicDirectory: " + AppDomain.CurrentDomain.DynamicDirectory);
#endif
}
catch(System.Security.SecurityException)
{
// Insufficient permissions to display info from the AppDomain
}
m_hierarchy.EmittedNoAppenderWarning = true;
}
}
/// <summary>
/// Closes all attached appenders implementing the <see cref="IAppenderAttachable"/> interface.
/// </summary>
/// <remarks>
/// <para>
/// Used to ensure that the appenders are correctly shutdown.
/// </para>
/// </remarks>
virtual public void CloseNestedAppenders()
{
m_appenderLock.AcquireWriterLock();
try
{
if (m_appenderAttachedImpl != null)
{
AppenderCollection appenders = m_appenderAttachedImpl.Appenders;
foreach(IAppender appender in appenders)
{
if (appender is IAppenderAttachable)
{
appender.Close();
}
}
}
}
finally
{
m_appenderLock.ReleaseWriterLock();
}
}
/// <summary>
/// This is the most generic printing method. This generic form is intended to be used by wrappers
/// </summary>
/// <param name="level">The level of the message to be logged.</param>
/// <param name="message">The message object to log.</param>
/// <param name="exception">The exception to log, including its stack trace.</param>
/// <remarks>
/// <para>
/// Generate a logging event for the specified <paramref name="level"/> using
/// the <paramref name="message"/>.
/// </para>
/// </remarks>
virtual public void Log(Level level, object message, Exception exception)
{
if (IsEnabledFor(level))
{
ForcedLog(declaringType, level, message, exception);
}
}
/// <summary>
/// Creates a new logging event and logs the event without further checks.
/// </summary>
/// <param name="callerStackBoundaryDeclaringType">The declaring type of the method that is
/// the stack boundary into the logging system for this call.</param>
/// <param name="level">The level of the message to be logged.</param>
/// <param name="message">The message object to log.</param>
/// <param name="exception">The exception to log, including its stack trace.</param>
/// <remarks>
/// <para>
/// Generates a logging event and delivers it to the attached
/// appenders.
/// </para>
/// </remarks>
virtual protected void ForcedLog(Type callerStackBoundaryDeclaringType, Level level, object message, Exception exception)
{
CallAppenders(new LoggingEvent(callerStackBoundaryDeclaringType, this.Hierarchy, this.Name, level, message, exception));
}
/// <summary>
/// Creates a new logging event and logs the event without further checks.
/// </summary>
/// <param name="logEvent">The event being logged.</param>
/// <remarks>
/// <para>
/// Delivers the logging event to the attached appenders.
/// </para>
/// </remarks>
virtual protected void ForcedLog(LoggingEvent logEvent)
{
// The logging event may not have been created by this logger
// the Repository may not be correctly set on the event. This
// is required for the appenders to correctly lookup renderers etc...
logEvent.EnsureRepository(this.Hierarchy);
CallAppenders(logEvent);
}
#region Private Static Fields
/// <summary>
/// The fully qualified type of the Logger class.
/// </summary>
private readonly static Type declaringType = typeof(Logger);
#endregion Private Static Fields
#region Private Instance Fields
/// <summary>
/// The name of this logger.
/// </summary>
private readonly string m_name;
/// <summary>
/// The assigned level of this logger.
/// </summary>
/// <remarks>
/// <para>
/// The <c>level</c> variable need not be
/// assigned a value in which case it is inherited
/// form the hierarchy.
/// </para>
/// </remarks>
private Level m_level;
/// <summary>
/// The parent of this logger.
/// </summary>
/// <remarks>
/// <para>
/// The parent of this logger.
/// All loggers have at least one ancestor which is the root logger.
/// </para>
/// </remarks>
private Logger m_parent;
/// <summary>
/// Loggers need to know what Hierarchy they are in.
/// </summary>
/// <remarks>
/// <para>
/// Loggers need to know what Hierarchy they are in.
/// The hierarchy that this logger is a member of is stored
/// here.
/// </para>
/// </remarks>
private Hierarchy m_hierarchy;
/// <summary>
/// Helper implementation of the <see cref="IAppenderAttachable"/> interface
/// </summary>
private Ctrip.Log4.Util.AppenderAttachedImpl m_appenderAttachedImpl;
/// <summary>
/// Flag indicating if child loggers inherit their parents appenders
/// </summary>
/// <remarks>
/// <para>
/// Additivity is set to true by default, that is children inherit
/// the appenders of their ancestors by default. If this variable is
/// set to <c>false</c> then the appenders found in the
/// ancestors of this logger are not used. However, the children
/// of this logger will inherit its appenders, unless the children
/// have their additivity flag set to <c>false</c> too. See
/// the user manual for more details.
/// </para>
/// </remarks>
private bool m_additive = true;
/// <summary>
/// Lock to protect AppenderAttachedImpl variable m_appenderAttachedImpl
/// </summary>
private readonly ReaderWriterLock m_appenderLock = new ReaderWriterLock();
#endregion
}
}
| |
// SF API version v50.0
// Custom fields included: False
// Relationship objects included: True
using System;
using NetCoreForce.Client.Models;
using NetCoreForce.Client.Attributes;
using Newtonsoft.Json;
namespace NetCoreForce.Models
{
///<summary>
/// Threat Detection Feedback Feed
///<para>SObject Name: ThreatDetectionFeedbackFeed</para>
///<para>Custom Object: False</para>
///</summary>
public class SfThreatDetectionFeedbackFeed : SObject
{
[JsonIgnore]
public static string SObjectTypeName
{
get { return "ThreatDetectionFeedbackFeed"; }
}
///<summary>
/// Feed Item ID
/// <para>Name: Id</para>
/// <para>SF Type: id</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "id")]
[Updateable(false), Createable(false)]
public string Id { get; set; }
///<summary>
/// Parent ID
/// <para>Name: ParentId</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "parentId")]
[Updateable(false), Createable(false)]
public string ParentId { get; set; }
///<summary>
/// ReferenceTo: ThreatDetectionFeedback
/// <para>RelationshipName: Parent</para>
///</summary>
[JsonProperty(PropertyName = "parent")]
[Updateable(false), Createable(false)]
public SfThreatDetectionFeedback Parent { get; set; }
///<summary>
/// Feed Item Type
/// <para>Name: Type</para>
/// <para>SF Type: picklist</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "type")]
[Updateable(false), Createable(false)]
public string Type { get; set; }
///<summary>
/// Created By ID
/// <para>Name: CreatedById</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "createdById")]
[Updateable(false), Createable(false)]
public string CreatedById { get; set; }
///<summary>
/// ReferenceTo: User
/// <para>RelationshipName: CreatedBy</para>
///</summary>
[JsonProperty(PropertyName = "createdBy")]
[Updateable(false), Createable(false)]
public SfUser CreatedBy { get; set; }
///<summary>
/// Created Date
/// <para>Name: CreatedDate</para>
/// <para>SF Type: datetime</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "createdDate")]
[Updateable(false), Createable(false)]
public DateTimeOffset? CreatedDate { get; set; }
///<summary>
/// Deleted
/// <para>Name: IsDeleted</para>
/// <para>SF Type: boolean</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "isDeleted")]
[Updateable(false), Createable(false)]
public bool? IsDeleted { get; set; }
///<summary>
/// Last Modified Date
/// <para>Name: LastModifiedDate</para>
/// <para>SF Type: datetime</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "lastModifiedDate")]
[Updateable(false), Createable(false)]
public DateTimeOffset? LastModifiedDate { get; set; }
///<summary>
/// System Modstamp
/// <para>Name: SystemModstamp</para>
/// <para>SF Type: datetime</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "systemModstamp")]
[Updateable(false), Createable(false)]
public DateTimeOffset? SystemModstamp { get; set; }
///<summary>
/// Comment Count
/// <para>Name: CommentCount</para>
/// <para>SF Type: int</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "commentCount")]
[Updateable(false), Createable(false)]
public int? CommentCount { get; set; }
///<summary>
/// Like Count
/// <para>Name: LikeCount</para>
/// <para>SF Type: int</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "likeCount")]
[Updateable(false), Createable(false)]
public int? LikeCount { get; set; }
///<summary>
/// Title
/// <para>Name: Title</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "title")]
[Updateable(false), Createable(false)]
public string Title { get; set; }
///<summary>
/// Body
/// <para>Name: Body</para>
/// <para>SF Type: textarea</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "body")]
[Updateable(false), Createable(false)]
public string Body { get; set; }
///<summary>
/// Link Url
/// <para>Name: LinkUrl</para>
/// <para>SF Type: url</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "linkUrl")]
[Updateable(false), Createable(false)]
public string LinkUrl { get; set; }
///<summary>
/// Is Rich Text
/// <para>Name: IsRichText</para>
/// <para>SF Type: boolean</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "isRichText")]
[Updateable(false), Createable(false)]
public bool? IsRichText { get; set; }
///<summary>
/// Related Record ID
/// <para>Name: RelatedRecordId</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "relatedRecordId")]
[Updateable(false), Createable(false)]
public string RelatedRecordId { get; set; }
///<summary>
/// InsertedBy ID
/// <para>Name: InsertedById</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "insertedById")]
[Updateable(false), Createable(false)]
public string InsertedById { get; set; }
///<summary>
/// ReferenceTo: User
/// <para>RelationshipName: InsertedBy</para>
///</summary>
[JsonProperty(PropertyName = "insertedBy")]
[Updateable(false), Createable(false)]
public SfUser InsertedBy { get; set; }
///<summary>
/// Best Comment ID
/// <para>Name: BestCommentId</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "bestCommentId")]
[Updateable(false), Createable(false)]
public string BestCommentId { get; set; }
///<summary>
/// ReferenceTo: FeedComment
/// <para>RelationshipName: BestComment</para>
///</summary>
[JsonProperty(PropertyName = "bestComment")]
[Updateable(false), Createable(false)]
public SfFeedComment BestComment { get; set; }
}
}
| |
#region License
/*---------------------------------------------------------------------------------*\
Distributed under the terms of an MIT-style license:
The MIT License
Copyright (c) 2006-2009 Stephen M. McKamey
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
\*---------------------------------------------------------------------------------*/
#endregion License
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Text;
namespace JsonFx.Json
{
/// <summary>
/// Reader for consuming JSON data
/// </summary>
public class JsonReader
{
#region Constants
internal const string LiteralFalse = "false";
internal const string LiteralTrue = "true";
internal const string LiteralNull = "null";
internal const string LiteralUndefined = "undefined";
internal const string LiteralNotANumber = "NaN";
internal const string LiteralPositiveInfinity = "Infinity";
internal const string LiteralNegativeInfinity = "-Infinity";
internal const char OperatorNegate = '-';
internal const char OperatorUnaryPlus = '+';
internal const char OperatorArrayStart = '[';
internal const char OperatorArrayEnd = ']';
internal const char OperatorObjectStart = '{';
internal const char OperatorObjectEnd = '}';
internal const char OperatorStringDelim = '"';
internal const char OperatorStringDelimAlt = '\'';
internal const char OperatorValueDelim = ',';
internal const char OperatorNameDelim = ':';
internal const char OperatorCharEscape = '\\';
private const string CommentStart = "/*";
private const string CommentEnd = "*/";
private const string CommentLine = "//";
private const string LineEndings = "\r\n";
internal const string TypeGenericIDictionary = "System.Collections.Generic.IDictionary`2";
private const string ErrorUnrecognizedToken = "Illegal JSON sequence.";
private const string ErrorUnterminatedComment = "Unterminated comment block.";
private const string ErrorUnterminatedObject = "Unterminated JSON object.";
private const string ErrorUnterminatedArray = "Unterminated JSON array.";
private const string ErrorUnterminatedString = "Unterminated JSON string.";
private const string ErrorIllegalNumber = "Illegal JSON number.";
private const string ErrorExpectedString = "Expected JSON string.";
private const string ErrorExpectedObject = "Expected JSON object.";
private const string ErrorExpectedArray = "Expected JSON array.";
private const string ErrorExpectedPropertyName = "Expected JSON object property name.";
private const string ErrorExpectedPropertyNameDelim = "Expected JSON object property name delimiter.";
private const string ErrorGenericIDictionary = "Types which implement Generic IDictionary<TKey, TValue> also need to implement IDictionary to be deserialized. ({0})";
private const string ErrorGenericIDictionaryKeys = "Types which implement Generic IDictionary<TKey, TValue> need to have string keys to be deserialized. ({0})";
#endregion Constants
#region Fields
private readonly JsonReaderSettings Settings = new JsonReaderSettings();
private readonly string Source = null;
private readonly int SourceLength = 0;
private int index;
#endregion Fields
#region Init
/// <summary>
/// Ctor
/// </summary>
/// <param name="input">TextReader containing source</param>
public JsonReader(TextReader input)
: this(input, new JsonReaderSettings())
{
}
/// <summary>
/// Ctor
/// </summary>
/// <param name="input">TextReader containing source</param>
/// <param name="settings">JsonReaderSettings</param>
public JsonReader(TextReader input, JsonReaderSettings settings)
{
this.Settings = settings;
this.Source = input.ReadToEnd();
this.SourceLength = this.Source.Length;
}
/// <summary>
/// Ctor
/// </summary>
/// <param name="input">Stream containing source</param>
public JsonReader(Stream input)
: this(input, new JsonReaderSettings())
{
}
/// <summary>
/// Ctor
/// </summary>
/// <param name="input">Stream containing source</param>
/// <param name="settings">JsonReaderSettings</param>
public JsonReader(Stream input, JsonReaderSettings settings)
{
this.Settings = settings;
using (StreamReader reader = new StreamReader(input, true))
{
this.Source = reader.ReadToEnd();
}
this.SourceLength = this.Source.Length;
}
/// <summary>
/// Ctor
/// </summary>
/// <param name="input">string containing source</param>
public JsonReader(string input)
: this(input, new JsonReaderSettings())
{
}
/// <summary>
/// Ctor
/// </summary>
/// <param name="input">string containing source</param>
/// <param name="settings">JsonReaderSettings</param>
public JsonReader(string input, JsonReaderSettings settings)
{
this.Settings = settings;
this.Source = input;
this.SourceLength = this.Source.Length;
}
/// <summary>
/// Ctor
/// </summary>
/// <param name="input">StringBuilder containing source</param>
public JsonReader(StringBuilder input)
: this(input, new JsonReaderSettings())
{
}
/// <summary>
/// Ctor
/// </summary>
/// <param name="input">StringBuilder containing source</param>
/// <param name="settings">JsonReaderSettings</param>
public JsonReader(StringBuilder input, JsonReaderSettings settings)
{
this.Settings = settings;
this.Source = input.ToString();
this.SourceLength = this.Source.Length;
}
#endregion Init
#region Properties
/// <summary>
/// Gets and sets if ValueTypes can accept values of null
/// </summary>
/// <remarks>
/// Only affects deserialization: if a ValueType is assigned the
/// value of null, it will receive the value default(TheType).
/// Setting this to false, throws an exception if null is
/// specified for a ValueType member.
/// </remarks>
[Obsolete("This has been deprecated in favor of JsonReaderSettings object")]
public bool AllowNullValueTypes
{
get { return this.Settings.AllowNullValueTypes; }
set { this.Settings.AllowNullValueTypes = value; }
}
/// <summary>
/// Gets and sets the property name used for type hinting.
/// </summary>
[Obsolete("This has been deprecated in favor of JsonReaderSettings object")]
public string TypeHintName
{
get { return this.Settings.TypeHintName; }
set { this.Settings.TypeHintName = value; }
}
#endregion Properties
#region Parsing Methods
/// <summary>
/// Convert from JSON string to Object graph
/// </summary>
/// <returns></returns>
public object Deserialize()
{
return this.Deserialize((Type)null);
}
/// <summary>
/// Convert from JSON string to Object graph
/// </summary>
/// <returns></returns>
public object Deserialize(int start)
{
this.index = start;
return this.Deserialize((Type)null);
}
/// <summary>
/// Convert from JSON string to Object graph of specific Type
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
public object Deserialize(Type type)
{
// should this run through a preliminary test here?
return this.Read(type, false);
}
/// <summary>
/// Convert from JSON string to Object graph of specific Type
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
public T Deserialize<T>()
{
// should this run through a preliminary test here?
return (T)this.Read(typeof(T), false);
}
/// <summary>
/// Convert from JSON string to Object graph of specific Type
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
public object Deserialize(int start, Type type)
{
this.index = start;
// should this run through a preliminary test here?
return this.Read(type, false);
}
/// <summary>
/// Convert from JSON string to Object graph of specific Type
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
public T Deserialize<T>(int start)
{
this.index = start;
// should this run through a preliminary test here?
return (T)this.Read(typeof(T), false);
}
private object Read(Type expectedType, bool typeIsHint)
{
if (expectedType == typeof(Object))
{
expectedType = null;
}
JsonToken token = this.Tokenize();
switch (token)
{
case JsonToken.ObjectStart:
{
return this.ReadObject(typeIsHint ? null : expectedType);
}
case JsonToken.ArrayStart:
{
return this.ReadArray(typeIsHint ? null : expectedType);
}
case JsonToken.String:
{
return this.ReadString(typeIsHint ? null : expectedType);
}
case JsonToken.Number:
{
return this.ReadNumber(typeIsHint ? null : expectedType);
}
case JsonToken.False:
{
this.index += JsonReader.LiteralFalse.Length;
return false;
}
case JsonToken.True:
{
this.index += JsonReader.LiteralTrue.Length;
return true;
}
case JsonToken.Null:
{
this.index += JsonReader.LiteralNull.Length;
return null;
}
case JsonToken.NaN:
{
this.index += JsonReader.LiteralNotANumber.Length;
return Double.NaN;
}
case JsonToken.PositiveInfinity:
{
this.index += JsonReader.LiteralPositiveInfinity.Length;
return Double.PositiveInfinity;
}
case JsonToken.NegativeInfinity:
{
this.index += JsonReader.LiteralNegativeInfinity.Length;
return Double.NegativeInfinity;
}
case JsonToken.Undefined:
{
this.index += JsonReader.LiteralUndefined.Length;
return null;
}
case JsonToken.End:
default:
{
return null;
}
}
}
private object ReadObject(Type objectType)
{
if (this.Source[this.index] != JsonReader.OperatorObjectStart)
{
throw new JsonDeserializationException(JsonReader.ErrorExpectedObject, this.index);
}
// If this is a Date, then we should be reading an EJSON Date
if (objectType != null
&& objectType == typeof(DateTime)) {
// Read an EJSON result instead
var ejsonDateResult = this.ReadObject(typeof(Meteor.EJSON.EJSONDate)) as Meteor.EJSON.EJSONDate;
var returnDate = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddTicks(ejsonDateResult.date * 10000L);
return returnDate;
}
// If this is a byte[] destination and we're reading an object, we're handling an EJSON UInt8 array
if (objectType != null
&& objectType == typeof(byte[])) {
var ejsonBinaryResult = this.ReadObject(typeof(Meteor.EJSON.EJSONUInt8Array)) as Meteor.EJSON.EJSONUInt8Array;
var returnBytes = System.Convert.FromBase64String(ejsonBinaryResult.binary);
return returnBytes;
}
Type genericDictionaryType = null;
Dictionary<string, MemberInfo> memberMap = null;
Object result;
if (objectType != null)
{
result = this.Settings.Coercion.InstantiateObject(objectType, out memberMap);
if (memberMap == null)
{
// this allows specific IDictionary<string, T> to deserialize T
Type genericDictionary = objectType.GetInterface(JsonReader.TypeGenericIDictionary);
if (genericDictionary != null)
{
Type[] genericArgs = genericDictionary.GetGenericArguments();
if (genericArgs.Length == 2)
{
if (genericArgs[0] != typeof(String))
{
throw new JsonDeserializationException(
String.Format(JsonReader.ErrorGenericIDictionaryKeys, objectType),
this.index);
}
if (genericArgs[1] != typeof(Object))
{
genericDictionaryType = genericArgs[1];
}
}
}
}
}
else
{
result = new Dictionary<String, Object>();
}
JsonToken token;
do
{
Type memberType;
MemberInfo memberInfo;
// consume opening brace or delim
this.index++;
if (this.index >= this.SourceLength)
{
throw new JsonDeserializationException(JsonReader.ErrorUnterminatedObject, this.index);
}
// get next token
token = this.Tokenize(this.Settings.AllowUnquotedObjectKeys);
if (token == JsonToken.ObjectEnd)
{
break;
}
if (token != JsonToken.String && token != JsonToken.UnquotedName)
{
throw new JsonDeserializationException(JsonReader.ErrorExpectedPropertyName, this.index);
}
// parse object member value
string memberName = (token == JsonToken.String) ?
(String)this.ReadString(null) :
this.ReadUnquotedKey();
if (genericDictionaryType == null && memberMap != null)
{
// determine the type of the property/field
memberType = TypeCoercionUtility.GetMemberInfo(memberMap, memberName, out memberInfo);
}
else
{
memberType = genericDictionaryType;
memberInfo = null;
}
// get next token
token = this.Tokenize();
if (token != JsonToken.NameDelim)
{
throw new JsonDeserializationException(JsonReader.ErrorExpectedPropertyNameDelim, this.index);
}
// consume delim
this.index++;
if (this.index >= this.SourceLength)
{
throw new JsonDeserializationException(JsonReader.ErrorUnterminatedObject, this.index);
}
object value = this.Read(memberType, false);
if (result is IDictionary)
{
if (objectType == null && this.Settings.IsTypeHintName(memberName))
{
result = this.Settings.Coercion.ProcessTypeHint((IDictionary)result, value as string, out objectType, out memberMap);
}
else
{
((IDictionary)result)[memberName] = value;
}
}
else if (objectType.GetInterface(JsonReader.TypeGenericIDictionary) != null)
{
throw new JsonDeserializationException(
String.Format(JsonReader.ErrorGenericIDictionary, objectType),
this.index);
}
else
{
this.Settings.Coercion.SetMemberValue(result, memberType, memberInfo, value);
}
// get next token
token = this.Tokenize();
} while (token == JsonToken.ValueDelim);
if (token != JsonToken.ObjectEnd)
{
throw new JsonDeserializationException(JsonReader.ErrorUnterminatedObject, this.index);
}
// consume closing brace
this.index++;
return result;
}
private IEnumerable ReadArray(Type arrayType)
{
if (this.Source[this.index] != JsonReader.OperatorArrayStart)
{
throw new JsonDeserializationException(JsonReader.ErrorExpectedArray, this.index);
}
bool isArrayItemTypeSet = (arrayType != null);
bool isArrayTypeAHint = !isArrayItemTypeSet;
Type arrayItemType = null;
if (isArrayItemTypeSet)
{
if (arrayType.HasElementType)
{
arrayItemType = arrayType.GetElementType();
}
else if (arrayType.IsGenericType)
{
Type[] generics = arrayType.GetGenericArguments();
if (generics.Length == 1)
{
// could use the first or last, but this more correct
arrayItemType = generics[0];
}
}
}
// using ArrayList since has .ToArray(Type) method
// cannot create generic list at runtime
ArrayList jsArray = new ArrayList();
JsonToken token;
do
{
// consume opening bracket or delim
this.index++;
if (this.index >= this.SourceLength)
{
throw new JsonDeserializationException(JsonReader.ErrorUnterminatedArray, this.index);
}
// get next token
token = this.Tokenize();
if (token == JsonToken.ArrayEnd)
{
break;
}
// parse array item
object value = this.Read(arrayItemType, isArrayTypeAHint);
jsArray.Add(value);
// establish if array is of common type
if (value == null)
{
if (arrayItemType != null && arrayItemType.IsValueType)
{
// use plain object to hold null
arrayItemType = null;
}
isArrayItemTypeSet = true;
}
else if (arrayItemType != null && !arrayItemType.IsAssignableFrom(value.GetType()))
{
if (value.GetType().IsAssignableFrom(arrayItemType))
{
// attempt to use the more general type
arrayItemType = value.GetType();
}
else
{
// use plain object to hold value
arrayItemType = null;
isArrayItemTypeSet = true;
}
}
else if (!isArrayItemTypeSet)
{
// try out a hint type
// if hasn't been set before
arrayItemType = value.GetType();
isArrayItemTypeSet = true;
}
// get next token
token = this.Tokenize();
} while (token == JsonToken.ValueDelim);
if (token != JsonToken.ArrayEnd)
{
throw new JsonDeserializationException(JsonReader.ErrorUnterminatedArray, this.index);
}
// consume closing bracket
this.index++;
// TODO: optimize to reduce number of conversions on lists
if (arrayItemType != null && arrayItemType != typeof(object))
{
// if all items are of same type then convert to array of that type
return jsArray.ToArray(arrayItemType);
}
// convert to an object array for consistency
return jsArray.ToArray();
}
/// <summary>
/// Reads an unquoted JSON object key
/// </summary>
/// <returns></returns>
private string ReadUnquotedKey()
{
int start = this.index;
do
{
// continue scanning until reach a valid token
this.index++;
} while (this.Tokenize(true) == JsonToken.UnquotedName);
return this.Source.Substring(start, this.index - start);
}
/// <summary>
/// Reads a JSON string
/// </summary>
/// <param name="expectedType"></param>
/// <returns>string or value which is represented as a string in JSON</returns>
private object ReadString(Type expectedType)
{
if (this.Source[this.index] != JsonReader.OperatorStringDelim &&
this.Source[this.index] != JsonReader.OperatorStringDelimAlt)
{
throw new JsonDeserializationException(JsonReader.ErrorExpectedString, this.index);
}
char startStringDelim = this.Source[this.index];
// consume opening quote
this.index++;
if (this.index >= this.SourceLength)
{
throw new JsonDeserializationException(JsonReader.ErrorUnterminatedString, this.index);
}
int start = this.index;
StringBuilder builder = new StringBuilder();
while (this.Source[this.index] != startStringDelim)
{
if (this.Source[this.index] == JsonReader.OperatorCharEscape)
{
// copy chunk before decoding
builder.Append(this.Source, start, this.index - start);
// consume escape char
this.index++;
if (this.index >= this.SourceLength)
{
throw new JsonDeserializationException(JsonReader.ErrorUnterminatedString, this.index);
}
// decode
switch (this.Source[this.index])
{
case '0':
{
// don't allow NULL char '\0'
// causes CStrings to terminate
break;
}
case 'b':
{
// backspace
builder.Append('\b');
break;
}
case 'f':
{
// formfeed
builder.Append('\f');
break;
}
case 'n':
{
// newline
builder.Append('\n');
break;
}
case 'r':
{
// carriage return
builder.Append('\r');
break;
}
case 't':
{
// tab
builder.Append('\t');
break;
}
case 'u':
{
// Unicode escape sequence
// e.g. Copyright: "\u00A9"
// unicode ordinal
int utf16;
if (this.index+4 < this.SourceLength &&
Int32.TryParse(
this.Source.Substring(this.index+1, 4),
NumberStyles.AllowHexSpecifier,
NumberFormatInfo.InvariantInfo,
out utf16))
{
builder.Append(Char.ConvertFromUtf32(utf16));
this.index += 4;
}
else
{
// using FireFox style recovery, if not a valid hex
// escape sequence then treat as single escaped 'u'
// followed by rest of string
builder.Append(this.Source[this.index]);
}
break;
}
default:
{
builder.Append(this.Source[this.index]);
break;
}
}
this.index++;
if (this.index >= this.SourceLength)
{
throw new JsonDeserializationException(JsonReader.ErrorUnterminatedString, this.index);
}
start = this.index;
}
else
{
// next char
this.index++;
if (this.index >= this.SourceLength)
{
throw new JsonDeserializationException(JsonReader.ErrorUnterminatedString, this.index);
}
}
}
// copy rest of string
builder.Append(this.Source, start, this.index-start);
// consume closing quote
this.index++;
if (expectedType != null && expectedType != typeof(String))
{
return this.Settings.Coercion.CoerceType(expectedType, builder.ToString());
}
return builder.ToString();
}
private object ReadNumber(Type expectedType)
{
bool hasDecimal = false;
bool hasExponent = false;
int start = this.index;
int precision = 0;
int exponent = 0;
// If this is a timespan do the microtime conversion
if (expectedType != null
&& expectedType == typeof(TimeSpan)) {
object number = this.ReadNumber(typeof(long));
return new TimeSpan((long)((long)((int)number) * 10000L));
}
// optional minus part
if (this.Source[this.index] == JsonReader.OperatorNegate)
{
// consume sign
this.index++;
if (this.index >= this.SourceLength || !Char.IsDigit(this.Source[this.index]))
throw new JsonDeserializationException(JsonReader.ErrorIllegalNumber, this.index);
}
// integer part
while ((this.index < this.SourceLength) && Char.IsDigit(this.Source[this.index]))
{
// consume digit
this.index++;
}
// optional decimal part
if ((this.index < this.SourceLength) && (this.Source[this.index] == '.'))
{
hasDecimal = true;
// consume decimal
this.index++;
if (this.index >= this.SourceLength || !Char.IsDigit(this.Source[this.index]))
{
throw new JsonDeserializationException(JsonReader.ErrorIllegalNumber, this.index);
}
// fraction part
while (this.index < this.SourceLength && Char.IsDigit(this.Source[this.index]))
{
// consume digit
this.index++;
}
}
// note the number of significant digits
precision = this.index-start - (hasDecimal ? 1 : 0);
// optional exponent part
if (this.index < this.SourceLength && (this.Source[this.index] == 'e' || this.Source[this.index] == 'E'))
{
hasExponent = true;
// consume 'e'
this.index++;
if (this.index >= this.SourceLength)
{
throw new JsonDeserializationException(JsonReader.ErrorIllegalNumber, this.index);
}
int expStart = this.index;
// optional minus/plus part
if (this.Source[this.index] == JsonReader.OperatorNegate || this.Source[this.index] == JsonReader.OperatorUnaryPlus)
{
// consume sign
this.index++;
if (this.index >= this.SourceLength || !Char.IsDigit(this.Source[this.index]))
{
throw new JsonDeserializationException(JsonReader.ErrorIllegalNumber, this.index);
}
}
else
{
if (!Char.IsDigit(this.Source[this.index]))
{
throw new JsonDeserializationException(JsonReader.ErrorIllegalNumber, this.index);
}
}
// exp part
while (this.index < this.SourceLength && Char.IsDigit(this.Source[this.index]))
{
// consume digit
this.index++;
}
Int32.TryParse(this.Source.Substring(expStart, this.index-expStart), NumberStyles.Integer,
NumberFormatInfo.InvariantInfo, out exponent);
}
// at this point, we have the full number string and know its characteristics
string numberString = this.Source.Substring(start, this.index - start);
if (!hasDecimal && !hasExponent && precision < 19)
{
// is Integer value
// parse as most flexible
decimal number = Decimal.Parse(
numberString,
NumberStyles.Integer,
NumberFormatInfo.InvariantInfo);
if (number >= Int32.MinValue && number <= Int32.MaxValue)
{
// use most common
return (int)number;
}
if (number >= Int64.MinValue && number <= Int64.MaxValue)
{
// use more flexible
return (long)number;
}
// use most flexible
return number;
}
else
{
// is Floating Point value
if (expectedType == typeof(Decimal))
{
// special case since Double does not convert to Decimal
return Decimal.Parse(
numberString,
NumberStyles.Float,
NumberFormatInfo.InvariantInfo);
}
// use native EcmaScript number (IEEE 754)
double number = Double.Parse(
numberString,
NumberStyles.Float,
NumberFormatInfo.InvariantInfo);
if (expectedType != null)
{
return this.Settings.Coercion.CoerceType(expectedType, number);
}
return number;
}
}
#endregion Parsing Methods
#region Static Methods
/// <summary>
/// A fast method for deserializing an object from JSON
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static object Deserialize(string value)
{
return JsonReader.Deserialize(value, 0, null);
}
/// <summary>
/// A fast method for deserializing an object from JSON
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="value"></param>
/// <returns></returns>
public static T Deserialize<T>(string value)
{
return (T)JsonReader.Deserialize(value, 0, typeof(T));
}
/// <summary>
/// A fast method for deserializing an object from JSON
/// </summary>
/// <param name="value"></param>
/// <param name="start"></param>
/// <returns></returns>
public static object Deserialize(string value, int start)
{
return JsonReader.Deserialize(value, start, null);
}
/// <summary>
/// A fast method for deserializing an object from JSON
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="value"></param>
/// <param name="start"></param>
/// <returns></returns>
public static T Deserialize<T>(string value, int start)
{
return (T)JsonReader.Deserialize(value, start, typeof(T));
}
/// <summary>
/// A fast method for deserializing an object from JSON
/// </summary>
/// <param name="value"></param>
/// <param name="type"></param>
/// <returns></returns>
public static object Deserialize(string value, Type type)
{
return JsonReader.Deserialize(value, 0, type);
}
/// <summary>
/// A fast method for deserializing an object from JSON
/// </summary>
/// <param name="value">source text</param>
/// <param name="start">starting position</param>
/// <param name="type">expected type</param>
/// <returns></returns>
public static object Deserialize(string value, int start, Type type)
{
return (new JsonReader(value)).Deserialize(start, type);
}
#endregion Static Methods
#region Tokenizing Methods
private JsonToken Tokenize()
{
// unquoted object keys are only allowed in object properties
return this.Tokenize(false);
}
private JsonToken Tokenize(bool allowUnquotedString)
{
if (this.index >= this.SourceLength)
{
return JsonToken.End;
}
// skip whitespace
while (Char.IsWhiteSpace(this.Source[this.index]))
{
this.index++;
if (this.index >= this.SourceLength)
{
return JsonToken.End;
}
}
#region Skip Comments
// skip block and line comments
if (this.Source[this.index] == JsonReader.CommentStart[0])
{
if (this.index+1 >= this.SourceLength)
{
throw new JsonDeserializationException(JsonReader.ErrorUnrecognizedToken, this.index);
}
// skip over first char of comment start
this.index++;
bool isBlockComment = false;
if (this.Source[this.index] == JsonReader.CommentStart[1])
{
isBlockComment = true;
}
else if (this.Source[this.index] != JsonReader.CommentLine[1])
{
throw new JsonDeserializationException(JsonReader.ErrorUnrecognizedToken, this.index);
}
// skip over second char of comment start
this.index++;
if (isBlockComment)
{
// store index for unterminated case
int commentStart = this.index-2;
if (this.index+1 >= this.SourceLength)
{
throw new JsonDeserializationException(JsonReader.ErrorUnterminatedComment, commentStart);
}
// skip over everything until reach block comment ending
while (this.Source[this.index] != JsonReader.CommentEnd[0] ||
this.Source[this.index+1] != JsonReader.CommentEnd[1])
{
this.index++;
if (this.index+1 >= this.SourceLength)
{
throw new JsonDeserializationException(JsonReader.ErrorUnterminatedComment, commentStart);
}
}
// skip block comment end token
this.index += 2;
if (this.index >= this.SourceLength)
{
return JsonToken.End;
}
}
else
{
// skip over everything until reach line ending
while (JsonReader.LineEndings.IndexOf(this.Source[this.index]) < 0)
{
this.index++;
if (this.index >= this.SourceLength)
{
return JsonToken.End;
}
}
}
// skip whitespace again
while (Char.IsWhiteSpace(this.Source[this.index]))
{
this.index++;
if (this.index >= this.SourceLength)
{
return JsonToken.End;
}
}
}
#endregion Skip Comments
// consume positive signing (as is extraneous)
if (this.Source[this.index] == JsonReader.OperatorUnaryPlus)
{
this.index++;
if (this.index >= this.SourceLength)
{
return JsonToken.End;
}
}
switch (this.Source[this.index])
{
case JsonReader.OperatorArrayStart:
{
return JsonToken.ArrayStart;
}
case JsonReader.OperatorArrayEnd:
{
return JsonToken.ArrayEnd;
}
case JsonReader.OperatorObjectStart:
{
return JsonToken.ObjectStart;
}
case JsonReader.OperatorObjectEnd:
{
return JsonToken.ObjectEnd;
}
case JsonReader.OperatorStringDelim:
case JsonReader.OperatorStringDelimAlt:
{
return JsonToken.String;
}
case JsonReader.OperatorValueDelim:
{
return JsonToken.ValueDelim;
}
case JsonReader.OperatorNameDelim:
{
return JsonToken.NameDelim;
}
default:
{
break;
}
}
// number
if (Char.IsDigit(this.Source[this.index]) ||
((this.Source[this.index] == JsonReader.OperatorNegate) && (this.index+1 < this.SourceLength) && Char.IsDigit(this.Source[this.index+1])))
{
return JsonToken.Number;
}
// "false" literal
if (this.MatchLiteral(JsonReader.LiteralFalse))
{
return JsonToken.False;
}
// "true" literal
if (this.MatchLiteral(JsonReader.LiteralTrue))
{
return JsonToken.True;
}
// "null" literal
if (this.MatchLiteral(JsonReader.LiteralNull))
{
return JsonToken.Null;
}
// "NaN" literal
if (this.MatchLiteral(JsonReader.LiteralNotANumber))
{
return JsonToken.NaN;
}
// "Infinity" literal
if (this.MatchLiteral(JsonReader.LiteralPositiveInfinity))
{
return JsonToken.PositiveInfinity;
}
// "-Infinity" literal
if (this.MatchLiteral(JsonReader.LiteralNegativeInfinity))
{
return JsonToken.NegativeInfinity;
}
// "undefined" literal
if (this.MatchLiteral(JsonReader.LiteralUndefined))
{
return JsonToken.Undefined;
}
if (allowUnquotedString)
{
return JsonToken.UnquotedName;
}
throw new JsonDeserializationException(JsonReader.ErrorUnrecognizedToken, this.index);
}
/// <summary>
/// Determines if the next token is the given literal
/// </summary>
/// <param name="literal"></param>
/// <returns></returns>
private bool MatchLiteral(string literal)
{
int literalLength = literal.Length;
for (int i=0, j=this.index; i<literalLength && j<this.SourceLength; i++, j++)
{
if (literal[i] != this.Source[j])
{
return false;
}
}
return true;
}
#endregion Tokenizing Methods
#region Type Methods
/// <summary>
/// Converts a value into the specified type using type inference.
/// </summary>
/// <typeparam name="T">target type</typeparam>
/// <param name="value">value to convert</param>
/// <param name="typeToMatch">example object to get the type from</param>
/// <returns></returns>
public static T CoerceType<T>(object value, T typeToMatch)
{
return (T)new TypeCoercionUtility().CoerceType(typeof(T), value);
}
/// <summary>
/// Converts a value into the specified type.
/// </summary>
/// <typeparam name="T">target type</typeparam>
/// <param name="value">value to convert</param>
/// <returns></returns>
public static T CoerceType<T>(object value)
{
return (T)new TypeCoercionUtility().CoerceType(typeof(T), value);
}
/// <summary>
/// Converts a value into the specified type.
/// </summary>
/// <param name="targetType">target type</param>
/// <param name="value">value to convert</param>
/// <returns></returns>
public static object CoerceType(Type targetType, object value)
{
return new TypeCoercionUtility().CoerceType(targetType, value);
}
#endregion Type Methods
}
}
| |
//
// Encog(tm) Core v3.2 - .Net Version
// http://www.heatonresearch.com/encog/
//
// Copyright 2008-2014 Heaton Research, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// For more information on Heaton Research copyrights, licenses
// and trademarks visit:
// http://www.heatonresearch.com/copyright
//
using System;
using System.IO;
using System.Text;
using Encog.App.Analyst.Script;
using Encog.App.Quant;
using Encog.Util.CSV;
namespace Encog.App.Analyst.CSV.Basic
{
/// <summary>
/// Many of the Encog quant CSV processors are based upon this class. This class
/// is not useful on its own. However, it does form the foundation for most Encog
/// CSV file processing.
/// </summary>
public class BasicFile : QuantTask
{
/// <summary>
/// The default report interval.
/// </summary>
private const int REPORT_INTERVAL = 10000;
/// <summary>
/// Most Encog CSV classes must analyze a CSV file before actually processing
/// it. This property specifies if the file has been analyzed yet.
/// </summary>
private bool _analyzed;
/// <summary>
/// True, if the process should stop.
/// </summary>
private bool _cancel;
/// <summary>
/// The number of columns in the input file.
/// </summary>
private int _columnCount;
/// <summary>
/// The current record.
/// </summary>
private int _currentRecord;
/// <summary>
/// True, if input headers should be expected.
/// </summary>
private bool _expectInputHeaders;
/// <summary>
/// The format of the input file.
/// </summary>
private CSVFormat _format;
/// <summary>
/// The input filename. This is the file being analyzed/processed.
/// </summary>
private FileInfo _inputFilename;
/// <summary>
/// The column headings from the input file.
/// </summary>
private String[] _inputHeadings;
/// <summary>
/// The last time status was updated.
/// </summary>
private int _lastUpdate;
/// <summary>
/// Should output headers be produced?
/// </summary>
private bool _produceOutputHeaders;
/// <summary>
/// The number of records to process. This is determined when the file is
/// analyzed.
/// </summary>
private int _recordCount;
/// <summary>
/// Allows status to be reported. Defaults to no status reported.
/// </summary>
private IStatusReportable _report;
/// <summary>
/// The number of records to process before status is updated. Defaults to
/// 10k.
/// </summary>
private int _reportInterval;
/// <summary>
/// Construct the object, and set the defaults.
/// </summary>
public BasicFile()
{
Precision = EncogFramework.DefaultPrecision;
_report = new NullStatusReportable();
_reportInterval = REPORT_INTERVAL;
_produceOutputHeaders = true;
ResetStatus();
}
/// <summary>
/// Set the column count.
/// </summary>
public int Count
{
get { return _columnCount; }
set { _columnCount = value; }
}
/// <summary>
/// Set the input filename.
/// </summary>
public FileInfo InputFilename
{
get { return _inputFilename; }
set { _inputFilename = value; }
}
/// <summary>
/// Set the format.
/// </summary>
public CSVFormat Format
{
get { return _format; }
set { _format = value; }
}
/// <summary>
/// Set the input headings.
/// </summary>
public String[] InputHeadings
{
get { return _inputHeadings; }
set { _inputHeadings = value; }
}
/// <summary>
/// Set the precision to use.
/// </summary>
public int Precision { get; set; }
/// <summary>
/// Set the record count.
/// </summary>
public int RecordCount
{
get
{
if (!_analyzed)
{
throw new QuantError("Must analyze file first.");
}
return _recordCount;
}
set { _recordCount = value; }
}
/// <summary>
/// Set the status reporting object.
/// </summary>
public IStatusReportable Report
{
get { return _report; }
set { _report = value; }
}
/// <summary>
/// Set the reporting interval.
/// </summary>
public int ReportInterval
{
get { return _reportInterval; }
set { _reportInterval = value; }
}
/// <summary>
/// Set to true, if the file has been analyzed.
/// </summary>
public bool Analyzed
{
get { return _analyzed; }
set { _analyzed = value; }
}
/// <summary>
/// Set the flag to determine if we are expecting input headers.
/// </summary>
public bool ExpectInputHeaders
{
get { return _expectInputHeaders; }
set { _expectInputHeaders = value; }
}
/// <value>the produceOutputHeaders to set</value>
public bool ProduceOutputHeaders
{
get { return _produceOutputHeaders; }
set { _produceOutputHeaders = value; }
}
/// <value>the script to set</value>
public AnalystScript Script { get; set; }
#region QuantTask Members
/// <summary>
/// Request a stop.
/// </summary>
public void RequestStop()
{
_cancel = true;
}
/// <returns>Should we stop?</returns>
public bool ShouldStop()
{
return _cancel;
}
#endregion
/// <summary>
/// Append a separator. The separator will only be appended if the line is
/// not empty. This is used to build comma(or other) separated lists.
/// </summary>
/// <param name="line">The line to append to.</param>
/// <param name="format">The format to use.</param>
public static void AppendSeparator(StringBuilder line,
CSVFormat format)
{
if ((line.Length > 0)
&& !line.ToString().EndsWith(format.Separator + ""))
{
line.Append(format.Separator);
}
}
/// <summary>
/// Perform a basic analyze of the file. This method is used mostly
/// internally.
/// </summary>
public void PerformBasicCounts()
{
ResetStatus();
int rc = 0;
var csv = new ReadCSV(_inputFilename.ToString(),
_expectInputHeaders, _format);
while (csv.Next() && !_cancel)
{
UpdateStatus(true);
rc++;
}
_recordCount = rc;
_columnCount = csv.ColumnCount;
ReadHeaders(csv);
csv.Close();
ReportDone(true);
}
/// <summary>
/// Prepare the output file, write headers if needed.
/// </summary>
/// <param name="outputFile">The name of the output file.</param>
/// <returns>The output stream for the text file.</returns>
public StreamWriter PrepareOutputFile(FileInfo outputFile)
{
try
{
outputFile.Delete();
var tw = new StreamWriter(outputFile.OpenWrite());
// write headers, if needed
if (_produceOutputHeaders)
{
var line = new StringBuilder();
if (_inputHeadings != null)
{
foreach (String str in _inputHeadings)
{
if (line.Length > 0)
{
line.Append(_format.Separator);
}
line.Append("\"");
line.Append(str);
line.Append("\"");
}
}
else
{
for (int i = 0; i < _columnCount; i++)
{
line.Append("\"field:");
line.Append(i + 1);
line.Append("\"");
}
}
tw.WriteLine(line.ToString());
}
return tw;
}
catch (IOException e)
{
throw new QuantError(e);
}
}
/// <summary>
/// Read the headers from a CSV file. Used mostly internally.
/// </summary>
/// <param name="csv">The CSV file to read from.</param>
public void ReadHeaders(ReadCSV csv)
{
if (_expectInputHeaders)
{
_inputHeadings = new String[csv.ColumnCount];
for (int i = 0; i < csv.ColumnCount; i++)
{
_inputHeadings[i] = csv.ColumnNames[i];
}
}
else
{
_inputHeadings = new String[csv.ColumnCount];
int i = 0;
if (Script != null)
{
foreach (DataField field in Script.Fields)
{
_inputHeadings[i++] = field.Name;
}
}
while (i < csv.ColumnCount)
{
_inputHeadings[i] = "field:" + i;
i++;
}
}
}
/// <summary>
/// Report that we are done. Used internally.
/// </summary>
/// <param name="isAnalyzing">True if we are analyzing.</param>
public void ReportDone(bool isAnalyzing)
{
_report.Report(_recordCount, _recordCount,
isAnalyzing ? "Done analyzing" : "Done processing");
}
/// <summary>
/// Report that we are done. Used internally.
/// </summary>
/// <param name="task">The message.</param>
public void ReportDone(String task)
{
_report.Report(_recordCount, _recordCount, task);
}
/// <summary>
/// Reset the reporting stats. Used internally.
/// </summary>
public void ResetStatus()
{
_lastUpdate = 0;
_currentRecord = 0;
}
/// <inheritdoc />
public override sealed String ToString()
{
var result = new StringBuilder("[");
result.Append(GetType().Name);
result.Append(" inputFilename=");
result.Append(_inputFilename);
result.Append(", recordCount=");
result.Append(_recordCount);
result.Append("]");
return result.ToString();
}
/// <summary>
/// Update the status. Used internally.
/// </summary>
/// <param name="isAnalyzing">True if we are in the process of analyzing.</param>
public void UpdateStatus(bool isAnalyzing)
{
UpdateStatus(isAnalyzing ? "Analyzing" : "Processing");
}
/// <summary>
/// Report the current status.
/// </summary>
/// <param name="task">The string to report.</param>
public void UpdateStatus(String task)
{
bool shouldDisplay = false;
if (_currentRecord == 0)
{
shouldDisplay = true;
}
_currentRecord++;
_lastUpdate++;
if (_lastUpdate >= _reportInterval)
{
_lastUpdate = 0;
shouldDisplay = true;
}
if (shouldDisplay)
{
_report.Report(_recordCount, _currentRecord, task);
}
}
/// <summary>
/// Validate that the file has been analyzed. Throw an error, if it has not.
/// </summary>
public void ValidateAnalyzed()
{
if (!_analyzed)
{
throw new QuantError("File must be analyzed first.");
}
}
/// <summary>
/// Write a row to the output file.
/// </summary>
/// <param name="tw">The output stream.</param>
/// <param name="row">The row to write out.</param>
public void WriteRow(StreamWriter tw, LoadedRow row)
{
var line = new StringBuilder();
foreach (string t in row.Data)
{
AppendSeparator(line, _format);
line.Append(t);
}
tw.WriteLine(line.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.
#pragma warning disable 414
using System;
public class A{
//////////////////////////////
// Instance Fields
public int FldAPubInst;
private int FldAPrivInst;
protected int FldAFamInst; //Translates to "family"
internal int FldAAsmInst; //Translates to "assembly"
protected internal int FldAFoaInst; //Translates to "famorassem"
//////////////////////////////
// Static Fields
public static int FldAPubStat;
private static int FldAPrivStat;
protected static int FldAFamStat; //family
internal static int FldAAsmStat; //assembly
protected internal static int FldAFoaStat; //famorassem
//////////////////////////////////////
// Instance fields for nested classes
public ClsA ClsAPubInst = new ClsA();
private ClsA ClsAPrivInst = new ClsA();
protected ClsA ClsAFamInst = new ClsA();
internal ClsA ClsAAsmInst = new ClsA();
protected internal ClsA ClsAFoaInst = new ClsA();
/////////////////////////////////////
// Static fields of nested classes
public static ClsA ClsAPubStat = new ClsA();
private static ClsA ClsAPrivStat = new ClsA();
//////////////////////////////
// Instance Methods
public int MethAPubInst(){
Console.WriteLine("A::MethAPubInst()");
return 100;
}
private int MethAPrivInst(){
Console.WriteLine("A::MethAPrivInst()");
return 100;
}
protected int MethAFamInst(){
Console.WriteLine("A::MethAFamInst()");
return 100;
}
internal int MethAAsmInst(){
Console.WriteLine("A::MethAAsmInst()");
return 100;
}
protected internal int MethAFoaInst(){
Console.WriteLine("A::MethAFoaInst()");
return 100;
}
//////////////////////////////
// Static Methods
public static int MethAPubStat(){
Console.WriteLine("A::MethAPubStat()");
return 100;
}
private static int MethAPrivStat(){
Console.WriteLine("A::MethAPrivStat()");
return 100;
}
protected static int MethAFamStat(){
Console.WriteLine("A::MethAFamStat()");
return 100;
}
internal static int MethAAsmStat(){
Console.WriteLine("A::MethAAsmStat()");
return 100;
}
protected internal static int MethAFoaStat(){
Console.WriteLine("A::MethAFoaStat()");
return 100;
}
//////////////////////////////
// Virtual Instance Methods
public virtual int MethAPubVirt(){
Console.WriteLine("A::MethAPubVirt()");
return 100;
}
//@csharp - Note that C# won't compile an illegal private virtual function
//So there is no negative testing MethAPrivVirt() here.
protected virtual int MethAFamVirt(){
Console.WriteLine("A::MethAFamVirt()");
return 100;
}
internal virtual int MethAAsmVirt(){
Console.WriteLine("A::MethAAsmVirt()");
return 100;
}
protected internal virtual int MethAFoaVirt(){
Console.WriteLine("A::MethAFoaVirt()");
return 100;
}
public class ClsA{
//////////////////////////////
// Instance Fields
public int NestFldAPubInst;
private int NestFldAPrivInst;
protected int NestFldAFamInst; //Translates to "family"
internal int NestFldAAsmInst; //Translates to "assembly"
protected internal int NestFldAFoaInst; //Translates to "famorassem"
//////////////////////////////
// Static Fields
public static int NestFldAPubStat;
private static int NestFldAPrivStat;
protected static int NestFldAFamStat; //family
internal static int NestFldAAsmStat; //assembly
protected internal static int NestFldAFoaStat; //famorassem
//////////////////////////////////////
// Instance fields for nested classes
public ClsA2 ClsA2PubInst = new ClsA2();
private ClsA2 ClsA2PrivInst = new ClsA2();
protected ClsA2 ClsA2FamInst = new ClsA2();
internal ClsA2 ClsA2AsmInst = new ClsA2();
protected internal ClsA2 ClsA2FoaInst = new ClsA2();
/////////////////////////////////////
// Static fields of nested classes
public static ClsA2 ClsA2PubStat = new ClsA2();
private static ClsA2 ClsA2PrivStat = new ClsA2();
//////////////////////////////
// Instance NestMethAods
public int NestMethAPubInst(){
Console.WriteLine("A::NestMethAPubInst()");
return 100;
}
private int NestMethAPrivInst(){
Console.WriteLine("A::NestMethAPrivInst()");
return 100;
}
protected int NestMethAFamInst(){
Console.WriteLine("A::NestMethAFamInst()");
return 100;
}
internal int NestMethAAsmInst(){
Console.WriteLine("A::NestMethAAsmInst()");
return 100;
}
protected internal int NestMethAFoaInst(){
Console.WriteLine("A::NestMethAFoaInst()");
return 100;
}
//////////////////////////////
// Static NestMethods
public static int NestMethAPubStat(){
Console.WriteLine("A::NestMethAPubStat()");
return 100;
}
private static int NestMethAPrivStat(){
Console.WriteLine("A::NestMethAPrivStat()");
return 100;
}
protected static int NestMethAFamStat(){
Console.WriteLine("A::NestMethAFamStat()");
return 100;
}
internal static int NestMethAAsmStat(){
Console.WriteLine("A::NestMethAAsmStat()");
return 100;
}
protected internal static int NestMethAFoaStat(){
Console.WriteLine("A::NestMethAFoaStat()");
return 100;
}
//////////////////////////////
// Virtual Instance NestMethods
public virtual int NestMethAPubVirt(){
Console.WriteLine("A::NestMethAPubVirt()");
return 100;
}
//@csharp - Note that C# won't compile an illegal private virtual function
//So there is no negative testing NestMethAPrivVirt() here.
protected virtual int NestMethAFamVirt(){
Console.WriteLine("A::NestMethAFamVirt()");
return 100;
}
internal virtual int NestMethAAsmVirt(){
Console.WriteLine("A::NestMethAAsmVirt()");
return 100;
}
protected internal virtual int NestMethAFoaVirt(){
Console.WriteLine("A::NestMethAFoaVirt()");
return 100;
}
public class ClsA2{
public int Test(){
int mi_RetCode = 100;
/////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////
// ACCESS ENCLOSING FIELDS/MEMBERS
/////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////
//@csharp - C# will not allow nested classes to access non-static members of their enclosing classes
/////////////////////////////////
// Test static field access
NestFldA2PubStat = 100;
if(NestFldA2PubStat != 100)
mi_RetCode = 0;
NestFldA2FamStat = 100;
if(NestFldA2FamStat != 100)
mi_RetCode = 0;
NestFldA2AsmStat = 100;
if(NestFldA2AsmStat != 100)
mi_RetCode = 0;
NestFldA2FoaStat = 100;
if(NestFldA2FoaStat != 100)
mi_RetCode = 0;
/////////////////////////////////
// Test static method access
if(NestMethA2PubStat() != 100)
mi_RetCode = 0;
if(NestMethA2FamStat() != 100)
mi_RetCode = 0;
if(NestMethA2AsmStat() != 100)
mi_RetCode = 0;
if(NestMethA2FoaStat() != 100)
mi_RetCode = 0;
return mi_RetCode;
}
//////////////////////////////
// Instance Fields
public int NestFldA2PubInst;
private int NestFldA2PrivInst;
protected int NestFldA2FamInst; //Translates to "family"
internal int NestFldA2AsmInst; //Translates to "assembly"
protected internal int NestFldA2FoaInst; //Translates to "famorassem"
//////////////////////////////
// Static Fields
public static int NestFldA2PubStat;
private static int NestFldA2PrivStat;
protected static int NestFldA2FamStat; //family
internal static int NestFldA2AsmStat; //assembly
protected internal static int NestFldA2FoaStat; //famorassem
//////////////////////////////
// Instance NestMethA2ods
public int NestMethA2PubInst(){
Console.WriteLine("A::NestMethA2PubInst()");
return 100;
}
private int NestMethA2PrivInst(){
Console.WriteLine("A::NestMethA2PrivInst()");
return 100;
}
protected int NestMethA2FamInst(){
Console.WriteLine("A::NestMethA2FamInst()");
return 100;
}
internal int NestMethA2AsmInst(){
Console.WriteLine("A::NestMethA2AsmInst()");
return 100;
}
protected internal int NestMethA2FoaInst(){
Console.WriteLine("A::NestMethA2FoaInst()");
return 100;
}
//////////////////////////////
// Static NestMethods
public static int NestMethA2PubStat(){
Console.WriteLine("A::NestMethA2PubStat()");
return 100;
}
private static int NestMethA2PrivStat(){
Console.WriteLine("A::NestMethA2PrivStat()");
return 100;
}
protected static int NestMethA2FamStat(){
Console.WriteLine("A::NestMethA2FamStat()");
return 100;
}
internal static int NestMethA2AsmStat(){
Console.WriteLine("A::NestMethA2AsmStat()");
return 100;
}
protected internal static int NestMethA2FoaStat(){
Console.WriteLine("A::NestMethA2FoaStat()");
return 100;
}
//////////////////////////////
// Virtual Instance NestMethods
public virtual int NestMethA2PubVirt(){
Console.WriteLine("A::NestMethA2PubVirt()");
return 100;
}
//@csharp - Note that C# won't compile an illegal private virtual function
//So there is no negative testing NestMethA2PrivVirt() here.
protected virtual int NestMethA2FamVirt(){
Console.WriteLine("A::NestMethA2FamVirt()");
return 100;
}
internal virtual int NestMethA2AsmVirt(){
Console.WriteLine("A::NestMethA2AsmVirt()");
return 100;
}
protected internal virtual int NestMethA2FoaVirt(){
Console.WriteLine("A::NestMethA2FoaVirt()");
return 100;
}
}
}
}
| |
//
// Copyright (C) DataStax Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Cassandra.IntegrationTests.TestBase;
using Cassandra.IntegrationTests.TestClusterManagement;
using Cassandra.Tests;
using NUnit.Framework;
namespace Cassandra.IntegrationTests.MetadataTests
{
[TestFixture, Category(TestCategory.Short), Category(TestCategory.RealClusterLong)]
public class TokenMapSchemaChangeMetadataSyncTests : SharedClusterTest
{
private Cluster _cluster;
private ISession _session;
public TokenMapSchemaChangeMetadataSyncTests() : base(3, false, new TestClusterOptions { UseVNodes = true })
{
}
[OneTimeSetUp]
public void SetUp()
{
base.OneTimeSetUp();
_cluster = ClusterBuilder()
.AddContactPoint(TestCluster.InitialContactPoint)
.WithMetadataSyncOptions(new MetadataSyncOptions().SetMetadataSyncEnabled(false))
.WithQueryTimeout(60000)
.Build();
_session = _cluster.Connect();
}
public override void OneTimeTearDown()
{
_cluster.Shutdown();
base.OneTimeTearDown();
}
[Test]
public void TokenMap_Should_NotUpdateExistingTokenMap_When_KeyspaceIsCreated()
{
TestUtils.WaitForSchemaAgreement(_cluster);
var keyspaceName = TestUtils.GetUniqueKeyspaceName().ToLower();
using (var newCluster = ClusterBuilder()
.AddContactPoint(TestCluster.InitialContactPoint)
.WithMetadataSyncOptions(new MetadataSyncOptions().SetMetadataSyncEnabled(false))
.WithQueryTimeout(60000)
.Build())
{
var newSession = newCluster.Connect();
var oldTokenMap = newCluster.Metadata.TokenToReplicasMap;
Assert.AreEqual(3, newCluster.Metadata.Hosts.Count);
Assert.IsNull(newCluster.Metadata.TokenToReplicasMap.GetByKeyspace(keyspaceName));
var createKeyspaceCql = $"CREATE KEYSPACE {keyspaceName} WITH replication = {{'class': 'SimpleStrategy', 'replication_factor' : 3}}";
newSession.Execute(createKeyspaceCql);
TestUtils.WaitForSchemaAgreement(newCluster);
newSession.ChangeKeyspace(keyspaceName);
Assert.IsNull(newCluster.Metadata.TokenToReplicasMap.GetByKeyspace(keyspaceName));
Assert.AreEqual(1, newCluster.Metadata.GetReplicas(keyspaceName, Encoding.UTF8.GetBytes("123")).Count);
Assert.IsTrue(object.ReferenceEquals(newCluster.Metadata.TokenToReplicasMap, oldTokenMap));
}
}
[Test]
public void TokenMap_Should_NotUpdateExistingTokenMap_When_KeyspaceIsRemoved()
{
var keyspaceName = TestUtils.GetUniqueKeyspaceName().ToLower();
var createKeyspaceCql = $"CREATE KEYSPACE {keyspaceName} WITH replication = {{'class': 'SimpleStrategy', 'replication_factor' : 3}}";
_session.Execute(createKeyspaceCql);
TestUtils.WaitForSchemaAgreement(_cluster);
using (var newCluster = ClusterBuilder()
.AddContactPoint(TestCluster.InitialContactPoint)
.WithMetadataSyncOptions(new MetadataSyncOptions().SetMetadataSyncEnabled(false))
.WithQueryTimeout(60000)
.Build())
{
var newSession = newCluster.Connect();
var removeKeyspaceCql = $"DROP KEYSPACE {keyspaceName}";
newSession.Execute(removeKeyspaceCql);
TestUtils.WaitForSchemaAgreement(newCluster);
var oldTokenMap = newCluster.Metadata.TokenToReplicasMap;
Assert.IsNull(newCluster.Metadata.TokenToReplicasMap.GetByKeyspace(keyspaceName));
Assert.AreEqual(1, newCluster.Metadata.GetReplicas(keyspaceName, Encoding.UTF8.GetBytes("123")).Count);
Assert.IsTrue(object.ReferenceEquals(newCluster.Metadata.TokenToReplicasMap, oldTokenMap));
}
}
[Test]
public void TokenMap_Should_NotUpdateExistingTokenMap_When_KeyspaceIsChanged()
{
var keyspaceName = TestUtils.GetUniqueKeyspaceName().ToLower();
var createKeyspaceCql = $"CREATE KEYSPACE {keyspaceName} WITH replication = {{'class': 'SimpleStrategy', 'replication_factor' : 3}}";
_session.Execute(createKeyspaceCql);
TestUtils.WaitForSchemaAgreement(_cluster);
using (var newCluster = ClusterBuilder()
.AddContactPoint(TestCluster.InitialContactPoint)
.WithMetadataSyncOptions(new MetadataSyncOptions().SetMetadataSyncEnabled(false))
.WithQueryTimeout(60000)
.Build())
{
var newSession = newCluster.Connect(keyspaceName);
TestHelper.RetryAssert(() =>
{
var replicas = newCluster.Metadata.TokenToReplicasMap.GetByKeyspace(keyspaceName);
Assert.IsNull(replicas);
Assert.AreEqual(1, newCluster.Metadata.GetReplicas(keyspaceName, Encoding.UTF8.GetBytes("123")).Count);
});
Assert.AreEqual(3, newCluster.Metadata.Hosts.Count(h => h.IsUp));
var oldTokenMap = newCluster.Metadata.TokenToReplicasMap;
var alterKeyspaceCql = $"ALTER KEYSPACE {keyspaceName} WITH replication = {{'class': 'SimpleStrategy', 'replication_factor' : 2}}";
newSession.Execute(alterKeyspaceCql);
TestUtils.WaitForSchemaAgreement(newCluster);
TestHelper.RetryAssert(() =>
{
var replicas = newCluster.Metadata.TokenToReplicasMap.GetByKeyspace(keyspaceName);
Assert.IsNull(replicas);
Assert.AreEqual(1, newCluster.Metadata.GetReplicas(keyspaceName, Encoding.UTF8.GetBytes("123")).Count);
});
Assert.AreEqual(3, newCluster.Metadata.Hosts.Count(h => h.IsUp));
Assert.IsTrue(object.ReferenceEquals(newCluster.Metadata.TokenToReplicasMap, oldTokenMap));
}
}
[Test]
public async Task TokenMap_Should_RefreshTokenMapForSingleKeyspace_When_RefreshSchemaWithKeyspaceIsCalled()
{
var keyspaceName = TestUtils.GetUniqueKeyspaceName().ToLower();
var createKeyspaceCql = $"CREATE KEYSPACE {keyspaceName} WITH replication = {{'class': 'SimpleStrategy', 'replication_factor' : 3}}";
_session.Execute(createKeyspaceCql);
TestUtils.WaitForSchemaAgreement(_cluster);
keyspaceName = TestUtils.GetUniqueKeyspaceName().ToLower();
createKeyspaceCql = $"CREATE KEYSPACE {keyspaceName} WITH replication = {{'class': 'SimpleStrategy', 'replication_factor' : 3}}";
_session.Execute(createKeyspaceCql);
TestUtils.WaitForSchemaAgreement(_cluster);
using (var newCluster = ClusterBuilder()
.AddContactPoint(TestCluster.InitialContactPoint)
.WithMetadataSyncOptions(new MetadataSyncOptions().SetMetadataSyncEnabled(false))
.WithQueryTimeout(60000)
.Build())
{
var newSession = newCluster.Connect(keyspaceName);
var oldTokenMap = newCluster.Metadata.TokenToReplicasMap;
var replicas = newCluster.Metadata.TokenToReplicasMap.GetByKeyspace(keyspaceName);
Assert.IsNull(replicas);
Assert.AreEqual(1, newCluster.Metadata.GetReplicas(keyspaceName, Encoding.UTF8.GetBytes("123")).Count);
Assert.AreEqual(3, newCluster.Metadata.Hosts.Count(h => h.IsUp));
Assert.AreEqual(1, newCluster.Metadata.GetReplicas(keyspaceName, Encoding.UTF8.GetBytes("123")).Count);
await newCluster.RefreshSchemaAsync(keyspaceName).ConfigureAwait(false);
Assert.AreEqual(1, newCluster.Metadata.KeyspacesSnapshot.Length);
replicas = newCluster.Metadata.TokenToReplicasMap.GetByKeyspace(keyspaceName);
Assert.AreEqual(newCluster.Metadata.Hosts.Sum(h => h.Tokens.Count()), replicas.Count);
Assert.AreEqual(3, newCluster.Metadata.GetReplicas(keyspaceName, Encoding.UTF8.GetBytes("123")).Count);
Assert.AreEqual(3, newCluster.Metadata.Hosts.Count(h => h.IsUp));
Assert.IsTrue(object.ReferenceEquals(newCluster.Metadata.TokenToReplicasMap, oldTokenMap));
}
}
[Test]
public async Task TokenMap_Should_RefreshTokenMapForAllKeyspaces_When_RefreshSchemaWithoutKeyspaceIsCalled()
{
var keyspaceName1 = TestUtils.GetUniqueKeyspaceName().ToLower();
var createKeyspaceCql = $"CREATE KEYSPACE {keyspaceName1} WITH replication = {{'class': 'SimpleStrategy', 'replication_factor' : 3}}";
_session.Execute(createKeyspaceCql);
TestUtils.WaitForSchemaAgreement(_cluster);
var keyspaceName = TestUtils.GetUniqueKeyspaceName().ToLower();
createKeyspaceCql = $"CREATE KEYSPACE {keyspaceName} WITH replication = {{'class': 'SimpleStrategy', 'replication_factor' : 3}}";
_session.Execute(createKeyspaceCql);
TestUtils.WaitForSchemaAgreement(_cluster);
using (var newCluster = ClusterBuilder()
.AddContactPoint(TestCluster.InitialContactPoint)
.WithMetadataSyncOptions(new MetadataSyncOptions().SetMetadataSyncEnabled(false))
.WithQueryTimeout(60000)
.Build())
{
var newSession = newCluster.Connect(keyspaceName);
var replicas = newCluster.Metadata.TokenToReplicasMap.GetByKeyspace(keyspaceName);
Assert.IsNull(replicas);
Assert.AreEqual(1, newCluster.Metadata.GetReplicas(keyspaceName, Encoding.UTF8.GetBytes("123")).Count);
var oldTokenMap = newCluster.Metadata.TokenToReplicasMap;
Assert.AreEqual(3, newCluster.Metadata.Hosts.Count(h => h.IsUp));
Assert.AreEqual(1, newCluster.Metadata.GetReplicas(keyspaceName, Encoding.UTF8.GetBytes("123")).Count);
await newCluster.RefreshSchemaAsync().ConfigureAwait(false);
Assert.GreaterOrEqual(newCluster.Metadata.KeyspacesSnapshot.Length, 2);
replicas = newCluster.Metadata.TokenToReplicasMap.GetByKeyspace(keyspaceName);
Assert.AreEqual(newCluster.Metadata.Hosts.Sum(h => h.Tokens.Count()), replicas.Count);
Assert.AreEqual(3, newCluster.Metadata.GetReplicas(keyspaceName, Encoding.UTF8.GetBytes("123")).Count);
replicas = newCluster.Metadata.TokenToReplicasMap.GetByKeyspace(keyspaceName1);
Assert.AreEqual(newCluster.Metadata.Hosts.Sum(h => h.Tokens.Count()), replicas.Count);
Assert.AreEqual(3, newCluster.Metadata.GetReplicas(keyspaceName, Encoding.UTF8.GetBytes("123")).Count);
Assert.AreEqual(3, newCluster.Metadata.Hosts.Count(h => h.IsUp));
Assert.IsFalse(object.ReferenceEquals(newCluster.Metadata.TokenToReplicasMap, oldTokenMap));
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Abstractions;
using Microsoft.AspNetCore.Mvc.ActionConstraints;
using Microsoft.AspNetCore.Routing;
using Microsoft.AspNetCore.Routing.Matching;
namespace Microsoft.AspNetCore.Mvc.Routing
{
// This is a bridge that allows us to execute IActionConstraint instance when
// used with Matcher.
internal class ActionConstraintMatcherPolicy : MatcherPolicy, IEndpointSelectorPolicy
{
// We need to be able to run IActionConstraints on Endpoints that aren't associated
// with an action. This is a sentinel value we use when the endpoint isn't from MVC.
internal static readonly ActionDescriptor NonAction = new ActionDescriptor();
private readonly ActionConstraintCache _actionConstraintCache;
public ActionConstraintMatcherPolicy(ActionConstraintCache actionConstraintCache)
{
_actionConstraintCache = actionConstraintCache;
}
// Run really late.
public override int Order => 100000;
public bool AppliesToEndpoints(IReadOnlyList<Endpoint> endpoints)
{
if (endpoints == null)
{
throw new ArgumentNullException(nameof(endpoints));
}
// We can skip over action constraints when they aren't any for this set
// of endpoints. This happens once on startup so it removes this component
// from the code path in most scenarios.
for (var i = 0; i < endpoints.Count; i++)
{
var endpoint = endpoints[i];
var action = endpoint.Metadata.GetMetadata<ActionDescriptor>();
if (action?.ActionConstraints is IList<IActionConstraintMetadata> { Count: > 0} constraints && HasSignificantActionConstraint(constraints))
{
// We need to check for some specific action constraint implementations.
// We've implemented consumes, and HTTP method support inside endpoint routing, so
// we don't need to run an 'action constraint phase' if those are the only constraints.
return true;
}
}
return false;
bool HasSignificantActionConstraint(IList<IActionConstraintMetadata> constraints)
{
for (var i = 0; i < constraints.Count; i++)
{
var actionConstraint = constraints[i];
if (actionConstraint.GetType() == typeof(HttpMethodActionConstraint))
{
// This one is OK, we implement this in endpoint routing.
}
else if (actionConstraint.GetType() == typeof(ConsumesAttribute))
{
// This one is OK, we implement this in endpoint routing.
}
else
{
return true;
}
}
return false;
}
}
public Task ApplyAsync(HttpContext httpContext, CandidateSet candidateSet)
{
var finalMatches = EvaluateActionConstraints(httpContext, candidateSet);
// We've computed the set of actions that still apply (and their indices)
// First, mark everything as invalid, and then mark everything in the matching
// set as valid. This is O(2n) vs O(n**2)
for (var i = 0; i < candidateSet.Count; i++)
{
candidateSet.SetValidity(i, false);
}
if (finalMatches != null)
{
for (var i = 0; i < finalMatches.Count; i++)
{
candidateSet.SetValidity(finalMatches[i].index, true);
}
}
return Task.CompletedTask;
}
// This is almost the same as the code in ActionSelector, but we can't really share the logic
// because we need to track the index of each candidate - and, each candidate has its own route
// values.
private IReadOnlyList<(int index, ActionSelectorCandidate candidate)>? EvaluateActionConstraints(
HttpContext httpContext,
CandidateSet candidateSet)
{
var items = new List<(int index, ActionSelectorCandidate candidate)>();
// We want to execute a group at a time (based on score) so keep track of the score that we've seen.
int? score = null;
// Perf: Avoid allocations
for (var i = 0; i < candidateSet.Count; i++)
{
if (candidateSet.IsValidCandidate(i))
{
ref var candidate = ref candidateSet[i];
if (score != null && score != candidate.Score)
{
// This is the end of a group.
var matches = EvaluateActionConstraintsCore(httpContext, candidateSet, items, startingOrder: null);
if (matches?.Count > 0)
{
return matches;
}
// If we didn't find matches, then reset.
items.Clear();
}
score = candidate.Score;
// If we get here, this is either the first endpoint or the we just (unsuccessfully)
// executed constraints for a group.
//
// So keep adding constraints.
var endpoint = candidate.Endpoint;
var actionDescriptor = endpoint.Metadata.GetMetadata<ActionDescriptor>();
IReadOnlyList<IActionConstraint>? constraints = Array.Empty<IActionConstraint>();
if (actionDescriptor != null)
{
constraints = _actionConstraintCache.GetActionConstraints(httpContext, actionDescriptor);
}
// Capture the index. We need this later to look up the endpoint/route values.
items.Add((i, new ActionSelectorCandidate(actionDescriptor ?? NonAction, constraints)));
}
}
// Handle residue
return EvaluateActionConstraintsCore(httpContext, candidateSet, items, startingOrder: null);
}
private IReadOnlyList<(int index, ActionSelectorCandidate candidate)>? EvaluateActionConstraintsCore(
HttpContext httpContext,
CandidateSet candidateSet,
IReadOnlyList<(int index, ActionSelectorCandidate candidate)> items,
int? startingOrder)
{
// Find the next group of constraints to process. This will be the lowest value of
// order that is higher than startingOrder.
int? order = null;
// Perf: Avoid allocations
for (var i = 0; i < items.Count; i++)
{
var item = items[i];
var constraints = item.candidate.Constraints;
if (constraints != null)
{
for (var j = 0; j < constraints.Count; j++)
{
var constraint = constraints[j];
if ((startingOrder == null || constraint.Order > startingOrder) &&
(order == null || constraint.Order < order))
{
order = constraint.Order;
}
}
}
}
// If we don't find a next then there's nothing left to do.
if (order == null)
{
return items;
}
// Since we have a constraint to process, bisect the set of endpoints into those with and without a
// constraint for the current order.
var endpointsWithConstraint = new List<(int index, ActionSelectorCandidate candidate)>();
var endpointsWithoutConstraint = new List<(int index, ActionSelectorCandidate candidate)>();
var constraintContext = new ActionConstraintContext
{
Candidates = items.Select(i => i.candidate).ToArray()
};
// Perf: Avoid allocations
for (var i = 0; i < items.Count; i++)
{
var item = items[i];
var isMatch = true;
var foundMatchingConstraint = false;
var constraints = item.candidate.Constraints;
if (constraints != null)
{
constraintContext.CurrentCandidate = item.candidate;
for (var j = 0; j < constraints.Count; j++)
{
var constraint = constraints[j];
if (constraint.Order == order)
{
foundMatchingConstraint = true;
ref var candidate = ref candidateSet[item.index];
var routeData = new RouteData(candidate.Values!);
var dataTokens = candidate.Endpoint.Metadata.GetMetadata<IDataTokensMetadata>()?.DataTokens;
if (dataTokens != null)
{
// Set the data tokens if there are any for this candidate
routeData.PushState(router: null, values: null, dataTokens: new RouteValueDictionary(dataTokens));
}
// Before we run the constraint, we need to initialize the route values.
// In endpoint routing, the route values are per-endpoint.
constraintContext.RouteContext = new RouteContext(httpContext)
{
RouteData = routeData,
};
if (!constraint.Accept(constraintContext))
{
isMatch = false;
break;
}
}
}
}
if (isMatch && foundMatchingConstraint)
{
endpointsWithConstraint.Add(item);
}
else if (isMatch)
{
endpointsWithoutConstraint.Add(item);
}
}
// If we have matches with constraints, those are better so try to keep processing those
if (endpointsWithConstraint.Count > 0)
{
var matches = EvaluateActionConstraintsCore(httpContext, candidateSet, endpointsWithConstraint, order);
if (matches?.Count > 0)
{
return matches;
}
}
// If the set of matches with constraints can't work, then process the set without constraints.
if (endpointsWithoutConstraint.Count == 0)
{
return null;
}
else
{
return EvaluateActionConstraintsCore(httpContext, candidateSet, endpointsWithoutConstraint, order);
}
}
}
}
| |
// The MIT License (MIT)
//
// Copyright (c) 2014-2017, Institute for Software & Systems Engineering
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
namespace ISSE.SafetyChecking.AnalysisModelTraverser
{
using System;
using System.Threading;
using Utilities;
/// <summary>
/// Stores the serialized states of an <see cref="AnalysisModel" />.
/// </summary>
/// <remarks>
/// We store states in a contiguous array, indexed by a continuous variable.
/// Therefore, we use state hashes like in <cref="SparseStateStorage" /> and one level of indirection.
/// The hashes are stored in a separate array, using open addressing,
/// see Laarman, "Scalable Multi-Core Model Checking", Algorithm 2.3.
/// </remarks>
internal sealed unsafe class CompactStateStorage : StateStorage
{
/// <summary>
/// The number of attempts that are made to find an empty bucket.
/// </summary>
private const int ProbeThreshold = 1000;
/// <summary>
/// The assumed size of a cache line in bytes.
/// </summary>
private const int CacheLineSize = 64;
/// <summary>
/// The number of buckets that can be stored in a cache line.
/// </summary>
private const int BucketsPerCacheLine = CacheLineSize / sizeof(int);
/// <summary>
/// The number of states that can be cached and the number of reserved states.
/// </summary>
private readonly long _totalCapacity;
/// <summary>
/// The number of states that can be cached.
/// </summary>
private long _cachedStatesCapacity;
/// <summary>
/// The number of reserved states
/// </summary>
private long _reservedStatesCapacity = 0;
/// <summary>
/// The buffer that stores the hash table information.
/// </summary>
private readonly MemoryBuffer _hashBuffer = new MemoryBuffer();
/// <summary>
/// The memory where the hash table information is stored.
/// </summary>
private readonly int* _hashMemory;
/// <summary>
/// The buffer that stores the states.
/// </summary>
private readonly MemoryBuffer _stateBuffer = new MemoryBuffer();
/// <summary>
/// The pointer to the underlying state memory.
/// </summary>
private byte* _stateMemory;
/// <summary>
/// The buffer that stores the mapping from the hashed-based state index to the compact state index.
/// </summary>
private readonly MemoryBuffer _indexMapperBuffer = new MemoryBuffer();
/// <summary>
/// The pointer to the underlying index mapper.
/// </summary>
private readonly int* _indexMapperMemory;
/// <summary>
/// The length in bytes of a state vector required for the analysis model.
/// </summary>
private readonly int _analysisModelStateVectorSize;
/// <summary>
/// Extra bytes in state vector for traversal modifiers.
/// </summary>
private int _traversalModifierStateVectorSize;
/// <summary>
/// The length in bytes of the state vector of the analysis model with the extra bytes
/// required for the traversal.
/// </summary>
private int _stateVectorSize;
/// <summary>
/// The length in bytes of the state vector of the analysis model with the extra bytes
/// required for the traversal.
/// </summary>
public override int StateVectorSize => _stateVectorSize;
/// <summary>
/// The number of saved states (internal variable)
/// </summary>
private int _savedStates = 0;
/// <summary>
/// The number of saved states
/// </summary>
public int SavedStates => _savedStates;
/// <summary>
/// Initializes a new instance.
/// </summary>
/// <param name="analysisModelStateVectorSize">The size of the state vector required for the analysis model in bytes.</param>
/// <param name="capacity">The capacity of the cache, i.e., the number of states that can be stored in the cache.</param>
public CompactStateStorage(int analysisModelStateVectorSize, long capacity)
{
Requires.InRange(capacity, nameof(capacity), 1024, Int32.MaxValue);
_analysisModelStateVectorSize = analysisModelStateVectorSize;
_totalCapacity = capacity;
_cachedStatesCapacity = capacity - BucketsPerCacheLine; //offset returned by this.Add may be up to BucketsPerCacheLine-1 positions bigger than _cachedStatesCapacity
ResizeStateBuffer();
_indexMapperBuffer.Resize(_totalCapacity * sizeof(int), zeroMemory: false);
_indexMapperMemory = (int*) _indexMapperBuffer.Pointer;
// We allocate enough space so that we can align the returned pointer such that index 0 is the start of a cache line
_hashBuffer.Resize(_totalCapacity * sizeof(int) + CacheLineSize, zeroMemory: false);
_hashMemory = (int*)_hashBuffer.Pointer;
if ((ulong)_hashMemory % CacheLineSize != 0)
_hashMemory = (int*)(_hashBuffer.Pointer + (CacheLineSize - (ulong)_hashBuffer.Pointer % CacheLineSize));
Assert.InRange((ulong)_hashMemory - (ulong)_hashBuffer.Pointer, 0ul, (ulong)CacheLineSize);
Assert.That((ulong)_hashMemory % CacheLineSize == 0, "Invalid buffer alignment.");
}
/// <summary>
/// Gets the state at the given zero-based <paramref name="index" />.
/// </summary>
/// <param name="index">The index of the state that should be returned.</param>
public override byte* this[int index]
{
get
{
Assert.InRange(index, 0, _totalCapacity);
return _stateMemory + (long)index * _stateVectorSize;
}
}
/// <summary>
/// Reserve a state index in StateStorage. Must not be called after AddState has been called.
/// </summary>
internal override int ReserveStateIndex()
{
var freshCompactIndex = InterlockedExtensions.IncrementReturnOld(ref _savedStates);
// Use the index pointing at the last possible element in the buffers and decrease the size.
_reservedStatesCapacity++;
_cachedStatesCapacity--;
// Add BucketsPerCacheLine so returnIndex does not interfere with the maximal possible index returned by AddState
// which is _cachedStatesCapacity+BucketsPerCacheLine-1.
// returnIndex is in range of capacityToReserve, so this is save.
var hashBasedIndex = _cachedStatesCapacity + BucketsPerCacheLine;
Volatile.Write(ref _indexMapperMemory[hashBasedIndex], freshCompactIndex);
Assert.InRange(hashBasedIndex,0,Int32.MaxValue);
Assert.InRange(hashBasedIndex, 0, _totalCapacity + BucketsPerCacheLine);
return (int)freshCompactIndex;
}
/// <summary>
/// Adds the <paramref name="state" /> to the cache if it is not already known. Returns <c>true</c> to indicate that the state
/// has been added. This method can be called simultaneously from multiple threads.
/// </summary>
/// <param name="state">The state that should be added.</param>
/// <param name="index">Returns the unique index of the state.</param>
public override bool AddState(byte* state, out int index)
{
// We don't have to do any out of bounds checks here
var hash = MemoryBuffer.Hash(state, _stateVectorSize, 0);
for (var i = 1; i < ProbeThreshold; ++i)
{
// We store 30 bit hash values as 32 bit integers, with the most significant bit #31 being set
// indicating the 'written' state and bit #30 indicating whether writing is not yet finished
// 'empty' is represented by 0
// We ignore two most significant bits of the original hash, which has no influence on the
// correctness of the algorithm, but might result in more state comparisons
var hashedIndex = MemoryBuffer.Hash((byte*)&hash, sizeof(int), i * 8345723) % _cachedStatesCapacity;
var memoizedHash = hashedIndex & 0x3FFFFFFF;
var cacheLineStart = (hashedIndex / BucketsPerCacheLine) * BucketsPerCacheLine;
for (var j = 0; j < BucketsPerCacheLine; ++j)
{
var offset = (int)(cacheLineStart + (hashedIndex + j) % BucketsPerCacheLine);
var currentValue = Volatile.Read(ref _hashMemory[offset]);
if (currentValue == 0 && Interlocked.CompareExchange(ref _hashMemory[offset], (int)memoizedHash | (1 << 30), 0) == 0)
{
var freshCompactIndex = InterlockedExtensions.IncrementReturnOld(ref _savedStates);
Volatile.Write(ref _indexMapperMemory[offset], freshCompactIndex);
MemoryBuffer.Copy(state, this[freshCompactIndex], _stateVectorSize);
Volatile.Write(ref _hashMemory[offset], (int)memoizedHash | (1 << 31));
index = freshCompactIndex;
return true;
}
// We have to read the hash value again as it might have been written now where it previously was not
currentValue = Volatile.Read(ref _hashMemory[offset]);
if ((currentValue & 0x3FFFFFFF) == memoizedHash)
{
while ((currentValue & 1 << 31) == 0)
currentValue = Volatile.Read(ref _hashMemory[offset]);
var compactIndex = Volatile.Read(ref _indexMapperMemory[offset]);
if (compactIndex!=-1 && MemoryBuffer.AreEqual(state, this[compactIndex], _stateVectorSize))
{
index = compactIndex;
return false;
}
}
}
}
throw new OutOfMemoryException(
"Failed to find an empty hash table slot within a reasonable amount of time. Try increasing the state capacity.");
}
internal void ResizeStateBuffer()
{
_stateVectorSize = _analysisModelStateVectorSize + _traversalModifierStateVectorSize;
_stateBuffer.Resize(_totalCapacity * _stateVectorSize, zeroMemory: false);
_stateMemory = _stateBuffer.Pointer;
}
/// <summary>
/// Clears all stored states.
/// </summary>
internal override void Clear(int traversalModifierStateVectorSize)
{
_traversalModifierStateVectorSize = traversalModifierStateVectorSize;
ResizeStateBuffer();
_hashBuffer.Clear();
MemoryBuffer.SetAllBitsMemoryWithInitblk.ClearWithMinus1(_indexMapperMemory, _totalCapacity);
}
/// <summary>
/// Disposes the object, releasing all managed and unmanaged resources.
/// </summary>
/// <param name="disposing">If true, indicates that the object is disposed; otherwise, the object is finalized.</param>
protected override void OnDisposing(bool disposing)
{
if (disposing)
_stateBuffer.SafeDispose();
}
}
}
| |
using CK.Auth;
using CK.Core;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.Extensions.Primitives;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading.Tasks;
using Microsoft.Extensions.Options;
using System.Globalization;
using System.Linq;
using Microsoft.Extensions.DependencyInjection;
using System.Text;
using System.Diagnostics.CodeAnalysis;
#nullable enable
namespace CK.AspNet.Auth
{
/// <summary>
/// Sealed implementation of the actual authentication service.
/// This implementation is registered as a singleton by <see cref="WebFrontAuthExtensions.AddWebFrontAuth(AuthenticationBuilder)" />.
/// </summary>
public sealed class WebFrontAuthService
{
/// <summary>
/// The tag used for logs emitted related to Web Front Authentication or any
/// authentication related actions.
/// </summary>
public static readonly CKTrait WebFrontAuthMonitorTag = ActivityMonitor.Tags.Register( "WebFrontAuth" );
/// <summary>
/// Name of the authentication cookie.
/// </summary>
public string AuthCookieName { get; }
/// <summary>
/// Name of the long term authentication cookie.
/// </summary>
public string UnsafeCookieName => AuthCookieName + "LT";
internal readonly IAuthenticationTypeSystem _typeSystem;
readonly IWebFrontAuthLoginService _loginService;
readonly IDataProtector _genericProtector;
readonly FrontAuthenticationInfoSecureDataFormat _tokenFormat;
readonly FrontAuthenticationInfoSecureDataFormat _cookieFormat;
readonly ExtraDataSecureDataFormat _extraDataFormat;
readonly string _cookiePath;
readonly string _bearerHeaderName;
readonly CookieSecurePolicy _cookiePolicy;
readonly IOptionsMonitor<WebFrontAuthOptions> _options;
readonly IWebFrontAuthValidateLoginService? _validateLoginService;
readonly IWebFrontAuthAutoCreateAccountService? _autoCreateAccountService;
readonly IWebFrontAuthAutoBindingAccountService? _autoBindingAccountService;
readonly IWebFrontAuthDynamicScopeProvider? _dynamicScopeProvider;
/// <summary>
/// Initializes a new <see cref="WebFrontAuthService"/>.
/// </summary>
/// <param name="typeSystem">A <see cref="IAuthenticationTypeSystem"/>.</param>
/// <param name="loginService">Login service.</param>
/// <param name="dataProtectionProvider">The data protection provider to use.</param>
/// <param name="options">Monitored options.</param>
/// <param name="validateLoginService">Optional service that validates logins.</param>
/// <param name="autoCreateAccountService">Optional service that enables account creation.</param>
/// <param name="autoBindingAccountService">Optional service that enables account binding.</param>
/// <param name="dynamicScopeProvider">Optional service to support scope augmentation.</param>
/// <param name="validateAuthenticationInfoService">Optional service that is called each time authentication information is restored.</param>
public WebFrontAuthService(
IAuthenticationTypeSystem typeSystem,
IWebFrontAuthLoginService loginService,
IDataProtectionProvider dataProtectionProvider,
IOptionsMonitor<WebFrontAuthOptions> options,
IWebFrontAuthValidateLoginService? validateLoginService = null,
IWebFrontAuthAutoCreateAccountService? autoCreateAccountService = null,
IWebFrontAuthAutoBindingAccountService? autoBindingAccountService = null,
IWebFrontAuthDynamicScopeProvider? dynamicScopeProvider = null )
{
_typeSystem = typeSystem;
_loginService = loginService;
_options = options;
_validateLoginService = validateLoginService;
_autoCreateAccountService = autoCreateAccountService;
_autoBindingAccountService = autoBindingAccountService;
_dynamicScopeProvider = dynamicScopeProvider;
WebFrontAuthOptions initialOptions = CurrentOptions;
IDataProtector dataProtector = dataProtectionProvider.CreateProtector( typeof( WebFrontAuthHandler ).FullName );
var cookieFormat = new FrontAuthenticationInfoSecureDataFormat( _typeSystem, dataProtector.CreateProtector( "Cookie", "v1" ) );
var tokenFormat = new FrontAuthenticationInfoSecureDataFormat( _typeSystem, dataProtector.CreateProtector( "Token", "v1" ) );
var extraDataFormat = new ExtraDataSecureDataFormat( dataProtector.CreateProtector( "Extra", "v1" ) );
_genericProtector = dataProtector;
_cookieFormat = cookieFormat;
_tokenFormat = tokenFormat;
_extraDataFormat = extraDataFormat;
Debug.Assert( WebFrontAuthHandler._cSegmentPath.ToString() == "/c" );
_cookiePath = initialOptions.EntryPath + "/c/";
_bearerHeaderName = initialOptions.BearerHeaderName;
CookieMode = initialOptions.CookieMode;
_cookiePolicy = initialOptions.CookieSecurePolicy;
AuthCookieName = initialOptions.AuthCookieName;
}
/// <summary>
/// Gets the cookie mode. This is not a dynamic option: this is the value
/// captured when this service has been instantiated.
/// </summary>
public AuthenticationCookieMode CookieMode { get; }
/// <summary>
/// Direct generation of an authentication token from any <see cref="IAuthenticationInfo"/>.
/// <see cref="IAuthenticationInfo.CheckExpiration(DateTime)"/> is called with <see cref="DateTime.UtcNow"/>.
/// This is to be used with caution: the authentication token should never be sent to any client and should be
/// used only for secure server to server temporary authentication.
/// </summary>
/// <param name="c">The HttpContext.</param>
/// <param name="info">The authentication info for which an authentication token must be obtained.</param>
/// <returns>The url-safe secured authentication token string.</returns>
public string UnsafeGetAuthenticationToken( HttpContext c, IAuthenticationInfo info )
{
if( c == null ) throw new ArgumentNullException( nameof( c ) );
if( info == null ) throw new ArgumentNullException( nameof( info ) );
info = info.CheckExpiration();
return ProtectAuthenticationInfo( new FrontAuthenticationInfo( info, false ) );
}
/// <summary>
/// Simple helper that calls <see cref="UnsafeGetAuthenticationToken(HttpContext, IAuthenticationInfo)"/>.
/// </summary>
/// <param name="c">The HttpContext.</param>
/// <param name="userId">The user identifier.</param>
/// <param name="userName">The user name.</param>
/// <param name="validity">The validity time span: the shorter the better.</param>
/// <returns>The url-safe secured authentication token string.</returns>
public string UnsafeGetAuthenticationToken( HttpContext c, int userId, string userName, TimeSpan validity )
{
if( userName == null ) throw new ArgumentNullException( nameof( userName ) );
var u = _typeSystem.UserInfo.Create( userId, userName );
var info = _typeSystem.AuthenticationInfo.Create( u, DateTime.UtcNow.Add( validity ) );
return UnsafeGetAuthenticationToken( c, info );
}
/// <summary>
/// Gets the current options.
/// This must be used for configurations that can be changed dynamically like <see cref="WebFrontAuthOptions.ExpireTimeSpan"/>
/// but not for non dynamic ones like <see cref="WebFrontAuthOptions.CookieMode"/>.
/// </summary>
internal WebFrontAuthOptions CurrentOptions => _options.Get( WebFrontAuthOptions.OnlyAuthenticationScheme );
/// <summary>
/// Gets the monitor from the request service.
/// Must be called once and only once per request since a new ActivityMonitor is
/// created when hostBuilder.UseMonitoring() has not been used (the IActivityMonitor is not
/// available in the context).
/// </summary>
/// <param name="c">The http context.</param>
/// <returns>An activity monitor.</returns>
IActivityMonitor GetRequestMonitor( HttpContext c )
{
return c.RequestServices.GetService<IActivityMonitor>() ?? new ActivityMonitor( "WebFrontAuthService-Request" );
}
internal string ProtectAuthenticationInfo( FrontAuthenticationInfo info )
{
Debug.Assert( info.Info != null );
return _tokenFormat.Protect( info );
}
internal FrontAuthenticationInfo UnprotectAuthenticationInfo( string data )
{
Debug.Assert( data != null );
return _tokenFormat.Unprotect( data );
}
internal string ProtectExtraData( IEnumerable<KeyValuePair<string, StringValues>> info )
{
Debug.Assert( info != null );
return _extraDataFormat.Protect( info );
}
internal List<KeyValuePair<string, StringValues>> UnprotectExtraData( string data )
{
Debug.Assert( data != null );
return (List<KeyValuePair<string, StringValues>>)_extraDataFormat.Unprotect( data );
}
internal void SetWFAData( AuthenticationProperties p,
FrontAuthenticationInfo fAuth,
string? initialScheme,
string? callerOrigin,
string? returnUrl,
IDictionary<string, StringValues> userData )
{
p.Items.Add( "WFA2C", ProtectAuthenticationInfo( fAuth ) );
if( !String.IsNullOrWhiteSpace( initialScheme ) )
{
p.Items.Add( "WFA2S", initialScheme );
}
if( !String.IsNullOrWhiteSpace( callerOrigin ) )
{
p.Items.Add( "WFA2O", callerOrigin );
}
if( returnUrl != null )
{
p.Items.Add( "WFA2R", returnUrl );
}
if( userData.Count != 0 )
{
p.Items.Add( "WFA2D", ProtectExtraData( userData ) );
}
}
internal void GetWFAData( HttpContext h,
AuthenticationProperties properties,
out FrontAuthenticationInfo fAuth,
out string? initialScheme,
out string? callerOrigin,
out string? returnUrl,
out List<KeyValuePair<string, StringValues>> userData )
{
fAuth = GetFrontAuthenticationInfo( h, properties );
properties.Items.TryGetValue( "WFA2S", out initialScheme );
properties.Items.TryGetValue( "WFA2O", out callerOrigin );
properties.Items.TryGetValue( "WFA2R", out returnUrl );
if( properties.Items.TryGetValue( "WFA2D", out var sUData ) )
{
userData = UnprotectExtraData( sUData );
}
else
{
userData = new List<KeyValuePair<string, StringValues>>();
}
}
internal FrontAuthenticationInfo GetFrontAuthenticationInfo( HttpContext h, AuthenticationProperties properties )
{
if( !h.Items.TryGetValue( typeof( RemoteAuthenticationEventsContextExtensions ), out var fAuth ) )
{
if( properties.Items.TryGetValue( "WFA2C", out var currentAuth ) )
{
fAuth = UnprotectAuthenticationInfo( currentAuth );
}
else
{
// There should always be the WFA2C key in Authentication properties.
// However if it's not here, we return the AuthenticationType.None that has an empty DeviceId.
fAuth = _typeSystem.AuthenticationInfo.None;
}
h.Items.Add( typeof( RemoteAuthenticationEventsContextExtensions ), fAuth );
}
return (FrontAuthenticationInfo)fAuth;
}
/// <summary>
/// Handles cached authentication header or calls ReadAndCacheAuthenticationHeader.
/// Never null, can be <see cref="IAuthenticationInfoType.None"/>.
/// </summary>
/// <param name="c">The context.</param>
/// <param name="monitor">The request monitor if it's available. Will be obtained if required.</param>
/// <returns>
/// The cached or resolved authentication info.
/// </returns>
internal FrontAuthenticationInfo EnsureAuthenticationInfo( HttpContext c, [NotNullIfNotNull("monitor")]ref IActivityMonitor? monitor )
{
FrontAuthenticationInfo? authInfo;
if( c.Items.TryGetValue( typeof( FrontAuthenticationInfo ), out object? o ) )
{
authInfo = (FrontAuthenticationInfo)o;
}
else
{
authInfo = ReadAndCacheAuthenticationHeader( c, ref monitor );
}
return authInfo;
}
/// <summary>
/// Reads authentication header if possible or uses authentication Cookie (and ultimately falls back to
/// long term cookie) and caches authentication in request items.
/// </summary>
/// <param name="c">The context.</param>
/// <param name="monitor">The request monitor if it's available. Will be obtained if required.</param>
/// <returns>
/// The front authentication info.
/// </returns>
internal FrontAuthenticationInfo ReadAndCacheAuthenticationHeader( HttpContext c, ref IActivityMonitor? monitor )
{
Debug.Assert( !c.Items.ContainsKey( typeof( FrontAuthenticationInfo ) ) );
bool shouldSetCookies = false;
FrontAuthenticationInfo? fAuth = null;
// First try from the bearer: this is always the preferred way.
string authorization = c.Request.Headers[_bearerHeaderName];
bool fromBearer = !string.IsNullOrEmpty( authorization )
&& authorization.StartsWith( "Bearer ", StringComparison.OrdinalIgnoreCase );
if( fromBearer )
{
try
{
Debug.Assert( "Bearer ".Length == 7 );
string token = authorization.Substring( 7 ).Trim();
fAuth = UnprotectAuthenticationInfo( token );
}
catch( Exception ex )
{
monitor ??= GetRequestMonitor( c );
monitor.Error( "While reading bearer.", ex );
}
}
if( fAuth == null )
{
// Best case is when we have the authentication cookie, otherwise use the long term cookie.
if( CookieMode != AuthenticationCookieMode.None && c.Request.Cookies.TryGetValue( AuthCookieName, out string cookie ) )
{
try
{
fAuth = _cookieFormat.Unprotect( cookie );
}
catch( Exception ex )
{
monitor ??= GetRequestMonitor( c );
monitor.Error( "While reading Cookie.", ex );
}
}
if( fAuth == null )
{
if( CurrentOptions.UseLongTermCookie && c.Request.Cookies.TryGetValue( UnsafeCookieName, out cookie ) )
{
try
{
var o = JObject.Parse( cookie );
// The long term cookie contains a deviceId field.
string? deviceId = (string?)o[StdAuthenticationTypeSystem.DeviceIdKeyType];
// We may have a "deviceId only" cookie.
IUserInfo? info = null;
if( o.ContainsKey( StdAuthenticationTypeSystem.UserIdKeyType ) )
{
info = _typeSystem.UserInfo.FromJObject( o );
}
var auth = _typeSystem.AuthenticationInfo.Create( info, deviceId: deviceId );
Debug.Assert( auth.Level < AuthLevel.Normal, "No expiration is an Unsafe authentication." );
// If there is a long term cookie with the user information, then we are "remembering"!
// (Checking UserId != 0 here is just to be safe since the anonymous must not "remember").
fAuth = new FrontAuthenticationInfo( auth, rememberMe: info != null && info.UserId != 0 );
}
catch( Exception ex )
{
monitor ??= GetRequestMonitor( c );
monitor.Error( "While reading Long Term Cookie.", ex );
}
}
if( fAuth == null )
{
// We have nothing or only errors:
// - If we could have something (either because CookieMode is AuthenticationCookieMode.RootPath or the request
// is inside the /.webfront/c), then we create a new unauthenticated info with a new device identifier.
// - If we are outside of the cookie context, we do nothing (otherwise we'll reset the current authentication).
if( CookieMode == AuthenticationCookieMode.RootPath
|| (CookieMode == AuthenticationCookieMode.WebFrontPath
&& c.Request.Path.Value.StartsWith( _cookiePath, StringComparison.OrdinalIgnoreCase )) )
{
var deviceId = CreateNewDeviceId();
var auth = _typeSystem.AuthenticationInfo.Create( null, deviceId: deviceId );
fAuth = new FrontAuthenticationInfo( auth, rememberMe: false );
Debug.Assert( auth.Level < AuthLevel.Normal, "No expiration is an Unsafe authentication." );
// We set the long lived cookie if possible. The device identifier will be de facto persisted.
shouldSetCookies = true;
}
else
{
fAuth = new FrontAuthenticationInfo( _typeSystem.AuthenticationInfo.None, rememberMe: false );
}
}
}
}
// Upon each (non anonymous) authentication, when rooted Cookies are used and the SlidingExpiration is on, handles it.
if( fAuth.Info.Level >= AuthLevel.Normal && CookieMode == AuthenticationCookieMode.RootPath )
{
var info = fAuth.Info;
TimeSpan slidingExpirationTime = CurrentOptions.SlidingExpirationTime;
TimeSpan halfSlidingExpirationTime = new TimeSpan( slidingExpirationTime.Ticks / 2 );
if( info.Level >= AuthLevel.Normal
&& CookieMode == AuthenticationCookieMode.RootPath
&& halfSlidingExpirationTime > TimeSpan.Zero )
{
Debug.Assert( info.Expires.HasValue, "Since info.Level >= AuthLevel.Normal." );
if( info.Expires.Value <= DateTime.UtcNow + halfSlidingExpirationTime )
{
fAuth = fAuth.SetInfo( info.SetExpires( DateTime.UtcNow + slidingExpirationTime ) );
shouldSetCookies = true;
}
}
}
if( shouldSetCookies ) SetCookies( c, fAuth );
c.Items.Add( typeof( FrontAuthenticationInfo ), fAuth );
return fAuth;
}
#region Cookie management
internal void Logout( HttpContext ctx )
{
ClearCookie( ctx, AuthCookieName );
ClearCookie( ctx, UnsafeCookieName );
}
internal void SetCookies( HttpContext ctx, FrontAuthenticationInfo fAuth )
{
JObject? longTermCookie = CurrentOptions.UseLongTermCookie ? CreateLongTermCookiePayload( fAuth ) : null;
if( longTermCookie != null )
{
string value = longTermCookie.ToString( Formatting.None );
ctx.Response.Cookies.Append( UnsafeCookieName, value, CreateUnsafeCookieOptions( DateTime.UtcNow + CurrentOptions.UnsafeExpireTimeSpan ) );
}
else ClearCookie( ctx, UnsafeCookieName );
if( CookieMode != AuthenticationCookieMode.None && fAuth.Info.Level >= AuthLevel.Normal )
{
Debug.Assert( fAuth.Info.Expires.HasValue );
string value = _cookieFormat.Protect( fAuth );
// If we don't remember, we create a session cookie (no expiration).
ctx.Response.Cookies.Append( AuthCookieName, value, CreateAuthCookieOptions( ctx, fAuth.RememberMe ? fAuth.Info.Expires : null ) );
}
else ClearCookie( ctx, AuthCookieName );
}
JObject? CreateLongTermCookiePayload( FrontAuthenticationInfo fAuth )
{
bool hasDeviceId = fAuth.Info.DeviceId.Length > 0;
JObject o;
if( fAuth.RememberMe && fAuth.Info.UnsafeActualUser.UserId != 0 )
{
// The long term cookie stores the unsafe actual user: we are "remembering" so we don't need to store the RememberMe flag.
o = _typeSystem.UserInfo.ToJObject( fAuth.Info.UnsafeActualUser );
}
else if( hasDeviceId )
{
// We have no user identifier to remember or have no right to do so, but
// a device identifier exists: since we are allowed to UseLongTermCookie, then, use it!
o = new JObject();
}
else
{
return null;
}
if( hasDeviceId )
{
o.Add( StdAuthenticationTypeSystem.DeviceIdKeyType, fAuth.Info.DeviceId );
}
return o;
}
CookieOptions CreateAuthCookieOptions( HttpContext ctx, DateTimeOffset? expires = null )
{
return new CookieOptions()
{
Path = CookieMode == AuthenticationCookieMode.WebFrontPath
? _cookiePath
: "/",
Expires = expires,
HttpOnly = true,
IsEssential = true,
Secure = _cookiePolicy == CookieSecurePolicy.SameAsRequest
? ctx.Request.IsHttps
: _cookiePolicy == CookieSecurePolicy.Always
};
}
CookieOptions CreateUnsafeCookieOptions( DateTimeOffset? expires = null )
{
return new CookieOptions()
{
Path = CookieMode == AuthenticationCookieMode.WebFrontPath
? _cookiePath
: "/",
Secure = false,
Expires = expires,
HttpOnly = true
};
}
void ClearCookie( HttpContext ctx, string cookieName )
{
ctx.Response.Cookies.Delete( cookieName, cookieName == AuthCookieName
? CreateAuthCookieOptions( ctx )
: CreateUnsafeCookieOptions() );
}
#endregion
internal readonly struct LoginResult
{
/// <summary>
/// Standard JSON response.
/// It is mutable: properties can be appended.
/// </summary>
public readonly JObject Response;
/// <summary>
/// Can be a None level.
/// </summary>
public readonly IAuthenticationInfo Info;
public LoginResult( JObject r, IAuthenticationInfo a )
{
Response = r;
Info = a;
}
}
/// <summary>
/// Creates the authentication info, the standard JSON response and sets the cookies.
/// Note that the <see cref="FrontAuthenticationInfo"/> is updated in the <see cref="HttpContext.Items"/>.
/// </summary>
/// <param name="c">The current Http context.</param>
/// <param name="u">The user info to login.</param>
/// <param name="callingScheme">
/// The calling scheme is used to set a critical expires depending on <see cref="WebFrontAuthOptions.SchemesCriticalTimeSpan"/>.
/// </param>
/// <param name="initial">The <see cref="WebFrontAuthLoginContext.InitialAuthentication"/>.</param>
/// <returns>A login result with the JSON response and authentication info.</returns>
internal LoginResult HandleLogin( HttpContext c, UserLoginResult u, string callingScheme, IAuthenticationInfo initial, bool rememberMe )
{
string deviceId = initial.DeviceId;
if( deviceId.Length == 0 ) deviceId = CreateNewDeviceId();
IAuthenticationInfo authInfo;
if( u.IsSuccess )
{
DateTime expires = DateTime.UtcNow + CurrentOptions.ExpireTimeSpan;
DateTime? criticalExpires = null;
// Handling Critical level configured for this scheme.
IDictionary<string, TimeSpan>? scts = CurrentOptions.SchemesCriticalTimeSpan;
if( scts != null
&& scts.TryGetValue( callingScheme, out var criticalTimeSpan )
&& criticalTimeSpan > TimeSpan.Zero )
{
criticalExpires = DateTime.UtcNow + criticalTimeSpan;
if( expires < criticalExpires ) expires = criticalExpires.Value;
}
authInfo = _typeSystem.AuthenticationInfo.Create( u.UserInfo,
expires,
criticalExpires,
deviceId );
}
else
{
// With the introduction of the device identifier, authentication info should preserve its
// device identifier.
// On authentication failure, we could have kept the current authentication... But this could be misleading
// for clients: a failed login should fall back to the "anonymous".
// So we just create a new anonymous authentication (with the same deviceId).
authInfo = _typeSystem.AuthenticationInfo.Create( null, deviceId : deviceId );
}
var fAuth = new FrontAuthenticationInfo( authInfo, rememberMe );
c.Items[typeof( FrontAuthenticationInfo )] = fAuth;
JObject response = CreateAuthResponse( c, refreshable: authInfo.Level >= AuthLevel.Normal && CurrentOptions.SlidingExpirationTime > TimeSpan.Zero,
fAuth,
onLogin: u );
SetCookies( c, fAuth );
return new LoginResult( response, authInfo );
}
/// <summary>
/// Creates a new device identifier.
/// If this must be changed, either the IWebFrontAuthLoginService or a new service or
/// may be the Options may do the job.
/// </summary>
/// <returns>The new device identifier.</returns>
static string CreateNewDeviceId()
{
// Uses only url compliant characters and removes the = padding if it exists.
// Similar to base64url. See https://en.wikipedia.org/wiki/Base64 and https://tools.ietf.org/html/rfc4648.
return Convert.ToBase64String( Guid.NewGuid().ToByteArray() ).Replace( '+', '-' ).Replace( '/', '_' ).TrimEnd( '=' );
}
/// <summary>
/// Centralized way to return an error: a redirect or a close of the window is emitted.
/// </summary>
internal Task SendRemoteAuthenticationErrorAsync( HttpContext c,
FrontAuthenticationInfo fAuth,
string? returnUrl,
string? callerOrigin,
string errorId,
string errorText,
string? initialScheme = null,
string? callingScheme = null,
IEnumerable<KeyValuePair<string, StringValues>>? userData = null,
UserLoginResult? failedLogin = null )
{
if( returnUrl != null )
{
Debug.Assert( callerOrigin != null, "Since returnUrl is not null: /c/startLogin has been used." );
int idxQuery = returnUrl.IndexOf( '?' );
var path = idxQuery > 0
? returnUrl.Substring( 0, idxQuery )
: string.Empty;
var parameters = idxQuery > 0
? new QueryString( returnUrl.Substring( idxQuery ) )
: new QueryString();
parameters = parameters.Add( "errorId", errorId );
if( !String.IsNullOrWhiteSpace( errorText ) && errorText != errorId )
{
parameters = parameters.Add( "errorText", errorText );
}
// UnsafeActualUser must be removed.
// A ActualLevel must be added.
// => SetLevel(): if !impersonated => both changed.
// if impersonated => Level is set at most to the ActualLevel.
// => SetActualLevel(): if !impersonated => both changed.
// if impersonated => Sets the actual level.
// Level is clamped to be at most the ActualLevel.
//
//
// if( fAuth.Info.ActualLevel <= AuthLevel.Unsafe ) ??
// {
// // Need a /c/downgradeLevel entry point ? (but we have it: Logout is downgrade to None + forget deviceId...)
// // "forget deviceId" on None should be in the WebFrontAuthOption...
//
// parameters = parameters.Add( "wfaAuthLevel", fAuth.Info.ActualLevel );
// }
int loginFailureCode = failedLogin?.LoginFailureCode ?? 0;
if( loginFailureCode != 0 ) parameters = parameters.Add( "loginFailureCode", loginFailureCode.ToString( CultureInfo.InvariantCulture ) );
if( initialScheme != null ) parameters = parameters.Add( "initialScheme", initialScheme );
if( callingScheme != null ) parameters = parameters.Add( "callingScheme", callingScheme );
var caller = new Uri( callerOrigin );
var target = new Uri( caller, path + parameters.ToString() );
c.Response.Redirect( target.ToString() );
return Task.CompletedTask;
}
JObject errObj = CreateErrorAuthResponse( c, fAuth, errorId, errorText, initialScheme, callingScheme, userData, failedLogin );
return c.Response.WriteWindowPostMessageAsync( errObj, callerOrigin );
}
/// <summary>
/// Creates a JSON response error object.
/// </summary>
/// <param name="c">The context.</param>
/// <param name="fAuth">
/// The current authentication info or a TypeSystem.AuthenticationInfo.None
/// info (with a device identifier if possible).
/// </param>
/// <param name="errorId">The error identifier.</param>
/// <param name="errorText">The error text. This can be null (<paramref name="errorId"/> is the key).</param>
/// <param name="initialScheme">The initial scheme.</param>
/// <param name="callingScheme">The calling scheme.</param>
/// <param name="userData">Optional user data (can be null).</param>
/// <param name="failedLogin">Optional failed login (can be null).</param>
/// <returns>A {info,token,refreshable} object with error fields inside.</returns>
internal JObject CreateErrorAuthResponse( HttpContext c,
FrontAuthenticationInfo fAuth,
string errorId,
string? errorText,
string? initialScheme,
string? callingScheme,
IEnumerable<KeyValuePair<string, StringValues>>? userData,
UserLoginResult? failedLogin )
{
var response = CreateAuthResponse( c, false, fAuth, failedLogin );
response.Add( new JProperty( "errorId", errorId ) );
if( !String.IsNullOrWhiteSpace( errorText ) && errorText != errorId )
{
response.Add( new JProperty( "errorText", errorText ) );
}
if( initialScheme != null ) response.Add( new JProperty( "initialScheme", initialScheme ) );
if( callingScheme != null ) response.Add( new JProperty( "callingScheme", callingScheme ) );
if( userData != null ) response.Add( userData.ToJProperty() );
return response;
}
/// <summary>
/// Creates a JSON response object.
/// </summary>
/// <param name="c">The context.</param>
/// <param name="refreshable">Whether the info is refreshable or not.</param>
/// <param name="fAuth">
/// The authentication info.
/// It is never null, even on error: it must be the current authentication info or a TypeSystem.AuthenticationInfo.None
/// info (with a device identifier if possible).
/// </param>
/// <param name="onLogin">Not null when this response is the result of an actual login (and not a refresh).</param>
/// <returns>A {info,token,refreshable} object.</returns>
internal JObject CreateAuthResponse( HttpContext c, bool refreshable, FrontAuthenticationInfo fAuth, UserLoginResult? onLogin = null )
{
var j = new JObject(
new JProperty( "info", _typeSystem.AuthenticationInfo.ToJObject( fAuth.Info ) ),
new JProperty( "token", ProtectAuthenticationInfo( fAuth ) ),
new JProperty( "refreshable", refreshable ),
new JProperty( "rememberMe", fAuth.RememberMe ) );
if( onLogin != null && !onLogin.IsSuccess )
{
j.Add( new JProperty( "loginFailureCode", onLogin.LoginFailureCode ) );
j.Add( new JProperty( "loginFailureReason", onLogin.LoginFailureReason ) );
}
return j;
}
internal async Task OnHandlerStartLoginAsync( IActivityMonitor m, WebFrontAuthStartLoginContext startContext )
{
try
{
if( _dynamicScopeProvider != null )
{
startContext.DynamicScopes = await _dynamicScopeProvider.GetScopesAsync( m, startContext );
}
}
catch( Exception ex )
{
startContext.SetError( ex.GetType().FullName!, ex.Message ?? "Exception has null message!" );
}
}
/// <summary>
/// This method fully handles the request.
/// </summary>
/// <typeparam name="T">Type of a payload object that is scheme dependent.</typeparam>
/// <param name="context">The remote authentication ticket.</param>
/// <param name="payloadConfigurator">
/// Configurator for the payload object: this action typically populates properties
/// from the <see cref="TicketReceivedContext"/> principal claims.
/// </param>
/// <returns>The awaitable.</returns>
public Task HandleRemoteAuthenticationAsync<T>( TicketReceivedContext context, Action<T> payloadConfigurator )
{
if( context == null ) throw new ArgumentNullException( nameof( context ) );
if( payloadConfigurator == null ) throw new ArgumentNullException( nameof( payloadConfigurator ) );
var monitor = GetRequestMonitor( context.HttpContext );
GetWFAData( context.HttpContext, context.Properties, out var fAuth, out var initialScheme, out var callerOrigin, out var returnUrl, out var userData );
string callingScheme = context.Scheme.Name;
object payload = _loginService.CreatePayload( context.HttpContext, monitor, callingScheme );
payloadConfigurator( (T)payload );
// When Authentication Challenge has been called directly (LoginMode is WebFrontAuthLoginMode.None), we don't have
// any scheme: we steal the context.RedirectUri as being the final redirect url.
if( initialScheme == null )
{
returnUrl = context.ReturnUri;
}
var wfaSC = new WebFrontAuthLoginContext(
context.HttpContext,
this,
_typeSystem,
initialScheme != null
? WebFrontAuthLoginMode.StartLogin
: WebFrontAuthLoginMode.None,
callingScheme,
payload,
context.Properties,
initialScheme,
fAuth,
returnUrl,
callerOrigin ?? $"{context.HttpContext.Request.Scheme}://{context.HttpContext.Request.Host}",
userData );
// We always handle the response (we skip the final standard SignIn process).
context.HandleResponse();
return UnifiedLoginAsync( monitor, wfaSC, actualLogin =>
{
return _loginService.LoginAsync( context.HttpContext, monitor, callingScheme, payload, actualLogin );
} );
}
internal async Task UnifiedLoginAsync( IActivityMonitor monitor, WebFrontAuthLoginContext ctx, Func<bool,Task<UserLoginResult>> logger )
{
if( ctx.InitialAuthentication.IsImpersonated )
{
ctx.SetError( "LoginWhileImpersonation", "Login is not allowed while impersonation is active." );
monitor.Error( $"Login is not allowed while impersonation is active: {ctx.InitialAuthentication.ActualUser.UserId} impersonated into {ctx.InitialAuthentication.User.UserId}.", WebFrontAuthMonitorTag );
}
UserLoginResult? u = null;
if( !ctx.HasError )
{
// The logger function must kindly return an unlogged UserLoginResult if it cannot log the user in.
u = await SafeCallLoginAsync( monitor, ctx, logger, actualLogin: _validateLoginService == null );
}
if( !ctx.HasError )
{
Debug.Assert( u != null );
int currentlyLoggedIn = ctx.InitialAuthentication.User.UserId;
if( !u.IsSuccess )
{
// Login failed because user is not registered: entering the account binding or auto registration features.
if( u.IsUnregisteredUser )
{
if( currentlyLoggedIn != 0 )
{
bool raiseError = true;
if( _autoBindingAccountService != null )
{
UserLoginResult uBound = await _autoBindingAccountService.BindAccountAsync( monitor, ctx );
if( uBound != null )
{
raiseError = false;
if( !uBound.IsSuccess ) ctx.SetError( uBound );
else
{
if( u != uBound )
{
u = uBound;
monitor.Info( $"[Account.AutoBinding] {currentlyLoggedIn} now bound to '{ctx.CallingScheme}' scheme.", WebFrontAuthMonitorTag );
}
}
}
}
if( raiseError )
{
ctx.SetError( "Account.NoAutoBinding", "Automatic account binding is disabled." );
monitor.Error( $"[Account.NoAutoBinding] {currentlyLoggedIn} tried '{ctx.CallingScheme}' scheme.", WebFrontAuthMonitorTag );
}
}
else
{
bool raiseError = true;
if( _autoCreateAccountService != null )
{
UserLoginResult uAuto = await _autoCreateAccountService.CreateAccountAndLoginAsync( monitor, ctx );
if( uAuto != null )
{
raiseError = false;
if( !uAuto.IsSuccess ) ctx.SetError( uAuto );
else u = uAuto;
}
}
if( raiseError )
{
ctx.SetError( "User.NoAutoRegistration", "Automatic user registration is disabled." );
monitor.Error( $"[User.NoAutoRegistration] Automatic user registration is disabled (scheme: {ctx.CallingScheme}).", WebFrontAuthMonitorTag );
}
}
}
else
{
ctx.SetError( u );
monitor.Trace( $"[User.LoginError] ({u.LoginFailureCode}) {u.LoginFailureReason}", WebFrontAuthMonitorTag );
}
}
else
{
// If a validation service is registered, the first call above
// did not actually logged the user in (actualLogin = false).
// We trigger the real login now if the validation service validates it.
if( _validateLoginService != null )
{
Debug.Assert( u.UserInfo != null );
await _validateLoginService.ValidateLoginAsync( monitor, u.UserInfo, ctx );
if( !ctx.HasError )
{
u = await SafeCallLoginAsync( monitor, ctx, logger, actualLogin: true );
}
}
}
// Eventually...
if( !ctx.HasError )
{
Debug.Assert( u != null && u.UserInfo != null, "Login succeeds." );
if( currentlyLoggedIn != 0 && u.UserInfo.UserId != currentlyLoggedIn )
{
monitor.Warn( $"[Account.Relogin] User {currentlyLoggedIn} logged again as {u.UserInfo.UserId} via '{ctx.CallingScheme}' scheme without logout.", WebFrontAuthMonitorTag );
}
ctx.SetSuccessfulLogin( u );
monitor.Info( $"Logged in user {u.UserInfo.UserId} via '{ctx.CallingScheme}'.", WebFrontAuthMonitorTag );
}
}
await ctx.SendResponseAsync();
}
/// <summary>
/// Calls the actual logger function (that must kindly return an unlogged UserLoginResult if it cannot log the user in)
/// in a try/catch and sets an error on the context only if it throws.
/// </summary>
/// <param name="monitor">The monitor to use.</param>
/// <param name="ctx">The login context.</param>
/// <param name="logger">The actual login function.</param>
/// <param name="actualLogin">True for an actual login, false otherwise.</param>
/// <returns>A login result (that may be unsuccessful).</returns>
static async Task<UserLoginResult?> SafeCallLoginAsync( IActivityMonitor monitor, WebFrontAuthLoginContext ctx, Func<bool, Task<UserLoginResult>> logger, bool actualLogin )
{
UserLoginResult? u = null;
try
{
u = await logger( actualLogin );
if( u == null )
{
monitor.Fatal( "Login service returned a null UserLoginResult.", WebFrontAuthMonitorTag );
ctx.SetError( "InternalError", "Login service returned a null UserLoginResult." );
}
}
catch( Exception ex )
{
monitor.Error( "While calling login service.", ex, WebFrontAuthMonitorTag );
ctx.SetError( ex );
}
return u;
}
}
}
| |
/*
* Copyright (c) 2000 Microsoft Corporation. All Rights Reserved.
* Microsoft Confidential.
*/
namespace System.Drawing.Printing {
using System;
using System.Security;
using System.Security.Permissions;
using System.IO;
using System.Runtime.Serialization;
using System.Reflection;
using System.Collections;
using System.Globalization;
using System.Diagnostics.CodeAnalysis;
/// <include file='doc\PrintingPermission.uex' path='docs/doc[@for="PrintingPermission"]/*' />
/// <devdoc>
/// <para> Controls the ability to use the printer. This class cannot be inherited.</para>
/// </devdoc>
[Serializable]
public sealed class PrintingPermission : CodeAccessPermission, IUnrestrictedPermission {
private PrintingPermissionLevel printingLevel;
/// <include file='doc\PrintingPermission.uex' path='docs/doc[@for="PrintingPermission.PrintingPermission"]/*' />
/// <devdoc>
/// <para>Initializes a new instance of the PrintingPermission class with either fully restricted
/// or unrestricted access, as specified.</para>
/// </devdoc>
public PrintingPermission(PermissionState state) {
if (state == PermissionState.Unrestricted) {
printingLevel = PrintingPermissionLevel.AllPrinting;
}
else if (state == PermissionState.None) {
printingLevel = PrintingPermissionLevel.NoPrinting;
}
else {
throw new ArgumentException(SR.GetString(SR.InvalidPermissionState));
}
}
/// <include file='doc\PrintingPermission.uex' path='docs/doc[@for="PrintingPermission.PrintingPermission1"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public PrintingPermission(PrintingPermissionLevel printingLevel) {
VerifyPrintingLevel(printingLevel);
this.printingLevel = printingLevel;
}
/// <include file='doc\PrintingPermission.uex' path='docs/doc[@for="PrintingPermission.Level"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public PrintingPermissionLevel Level {
get {
return printingLevel;
}
set {
VerifyPrintingLevel(value);
printingLevel = value;
}
}
private static void VerifyPrintingLevel(PrintingPermissionLevel level) {
if (level < PrintingPermissionLevel.NoPrinting || level > PrintingPermissionLevel.AllPrinting) {
throw new ArgumentException(SR.GetString(SR.InvalidPermissionLevel));
}
}
//------------------------------------------------------
//
// CODEACCESSPERMISSION IMPLEMENTATION
//
//------------------------------------------------------
/// <include file='doc\PrintingPermission.uex' path='docs/doc[@for="PrintingPermission.IsUnrestricted"]/*' />
/// <devdoc>
/// <para> Gets a
/// value indicating whether permission is unrestricted.</para>
/// </devdoc>
public bool IsUnrestricted() {
return printingLevel == PrintingPermissionLevel.AllPrinting;
}
//------------------------------------------------------
//
// IPERMISSION IMPLEMENTATION
//
//------------------------------------------------------
/// <include file='doc\PrintingPermission.uex' path='docs/doc[@for="PrintingPermission.IsSubsetOf"]/*' />
/// <devdoc>
/// <para>Determines whether the current permission object is a subset of
/// the specified permission.</para>
/// </devdoc>
public override bool IsSubsetOf(IPermission target) {
if (target == null) {
return printingLevel == PrintingPermissionLevel.NoPrinting;
}
PrintingPermission operand = target as PrintingPermission;
if(operand == null) {
throw new ArgumentException(SR.GetString(SR.TargetNotPrintingPermission));
}
return this.printingLevel <= operand.printingLevel;
}
/// <include file='doc\PrintingPermission.uex' path='docs/doc[@for="PrintingPermission.Intersect"]/*' />
/// <devdoc>
/// <para>Creates and returns a permission that is the intersection of the current
/// permission object and a target permission object.</para>
/// </devdoc>
public override IPermission Intersect(IPermission target) {
if (target == null) {
return null;
}
PrintingPermission operand = target as PrintingPermission;
if(operand == null) {
throw new ArgumentException(SR.GetString(SR.TargetNotPrintingPermission));
}
PrintingPermissionLevel isectLevels = printingLevel < operand.printingLevel ? printingLevel : operand.printingLevel;
if (isectLevels == PrintingPermissionLevel.NoPrinting)
return null;
else
return new PrintingPermission(isectLevels);
}
/// <include file='doc\PrintingPermission.uex' path='docs/doc[@for="PrintingPermission.Union"]/*' />
/// <devdoc>
/// <para>Creates a permission that is the union of the permission object
/// and the target parameter permission object.</para>
/// </devdoc>
public override IPermission Union(IPermission target) {
if (target == null) {
return this.Copy();
}
PrintingPermission operand = target as PrintingPermission;
if(operand == null) {
throw new ArgumentException(SR.GetString(SR.TargetNotPrintingPermission));
}
PrintingPermissionLevel isectLevels = printingLevel > operand.printingLevel ? printingLevel : operand.printingLevel;
if (isectLevels == PrintingPermissionLevel.NoPrinting)
return null;
else
return new PrintingPermission(isectLevels);
}
/// <include file='doc\PrintingPermission.uex' path='docs/doc[@for="PrintingPermission.Copy"]/*' />
/// <devdoc>
/// <para>Creates and returns an identical copy of the current permission
/// object.</para>
/// </devdoc>
[SuppressMessage("Microsoft.Security", "CA2103:ReviewImperativeSecurity")]
public override IPermission Copy() {
return new PrintingPermission(this.printingLevel);
}
/// <include file='doc\PrintingPermission.uex' path='docs/doc[@for="PrintingPermission.ToXml"]/*' />
/// <devdoc>
/// <para>Creates an XML encoding of the security object and its current
/// state.</para>
/// </devdoc>
public override SecurityElement ToXml() {
SecurityElement securityElement = new SecurityElement("IPermission");
securityElement.AddAttribute("class", this.GetType().FullName + ", " + this.GetType().Module.Assembly.FullName.Replace('\"', '\''));
securityElement.AddAttribute("version", "1");
if (!IsUnrestricted()) {
securityElement.AddAttribute("Level", Enum.GetName(typeof(PrintingPermissionLevel), printingLevel));
}
else {
securityElement.AddAttribute("Unrestricted", "true");
}
return securityElement;
}
/// <include file='doc\PrintingPermission.uex' path='docs/doc[@for="PrintingPermission.FromXml"]/*' />
/// <devdoc>
/// <para>Reconstructs a security object with a specified state from an XML
/// encoding.</para>
/// </devdoc>
[SuppressMessage("Microsoft.Performance", "CA1808:AvoidCallsThatBoxValueTypes")]
public override void FromXml(SecurityElement esd) {
if (esd == null) {
throw new ArgumentNullException("esd");
}
String className = esd.Attribute("class");
if (className == null || className.IndexOf(this.GetType().FullName) == -1) {
throw new ArgumentException(SR.GetString(SR.InvalidClassName));
}
String unrestricted = esd.Attribute("Unrestricted");
if (unrestricted != null && String.Equals(unrestricted, "true", StringComparison.OrdinalIgnoreCase))
{
printingLevel = PrintingPermissionLevel.AllPrinting;
return;
}
printingLevel = PrintingPermissionLevel.NoPrinting;
String printing = esd.Attribute("Level");
if (printing != null)
{
printingLevel = (PrintingPermissionLevel)Enum.Parse(typeof(PrintingPermissionLevel), printing);
}
}
}
}
| |
// 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.Diagnostics;
using System.Globalization;
using System.Threading;
using System.Transactions.Distributed;
namespace System.Transactions
{
// InternalTransaction
//
// This class holds the state and all data common to a transaction instance
internal class InternalTransaction : IDisposable
{
// This variable manages the state of the transaction it should be one of the
// static elements of TransactionState derived from TransactionState.
protected TransactionState _transactionState;
internal TransactionState State
{
get { return _transactionState; }
set { _transactionState = value; }
}
// This variable holds the state that the transaction will promote to. By
// default it uses the straight forward TransactionStatePromoted. If the
// transaction has a promotable single phase enlistment however it must use
// a different state so that it is promoted correctly.
internal TransactionState _promoteState;
// The PromoterType for the transaction.
// This is set when a PSPE enlistment is created via Transaction.EnlistPromotableSinglePhase.
// It is also set when a transaction promotes without a PSPE enlistment.
internal Guid _promoterType = Guid.Empty;
// The promoted token for the transaction.
// This is set when the transaction is promoted. For an MSDTC transaction, it is the
// same as the DTC propagation token.
internal byte[] promotedToken;
// This is only used if the promoter type is different than TransactionInterop.PromoterTypeDtc.
// The promoter is supposed to tell us what the distributed transaction id after promoting it.
// We store the value here.
internal Guid _distributedTransactionIdentifierNonMSDTC = Guid.Empty;
#if DEBUG
// Keep a history of th transaction states
internal const int MaxStateHist = 20;
internal readonly TransactionState[] _stateHistory = new TransactionState[MaxStateHist];
internal int _currentStateHist;
#endif
// Finalized object see class definition for the use of this object
internal FinalizedObject _finalizedObject;
internal readonly int _transactionHash;
internal int TransactionHash => _transactionHash;
internal static int _nextHash;
// timeout stores a relative timeout for the transaction. absoluteTimeout stores
// the actual time in ticks.
private readonly long _absoluteTimeout;
internal long AbsoluteTimeout => _absoluteTimeout;
// record the current number of ticks active when the transaction is created.
private long _creationTime;
internal long CreationTime
{
get { return _creationTime; }
set { _creationTime = value; }
}
// The goal for the LTM is to only allocate as few heap objects as possible for a given
// transaction and all of its enlistments. To accomplish this, enlistment objects are
// held in system arrays. The transaction contains one enlistment for the single durable
// enlistment it can handle and a small array of volatile enlistments. If the number of
// enlistments for a given transaction exceeds the capacity of the current array a new
// larger array will be created and the contents of the old array will be copied into it.
// Heuristic data based on TransactionType can be created to avoid this sort of copy
// operation repeatedly for a given type of transaction. So if a transaction of a specific
// type continually causes the array size to be increased the LTM could start
// allocating a larger array initially for transactions of that type.
internal InternalEnlistment _durableEnlistment;
internal VolatileEnlistmentSet _phase0Volatiles;
internal VolatileEnlistmentSet _phase1Volatiles;
// This member stores the number of phase 0 volatiles for the last wave
internal int _phase0VolatileWaveCount;
// These members are used for promoted waves of dependent blocking clones. The Ltm
// does not register individually for each blocking clone created in phase 0. Instead
// it multiplexes a single phase 0 blocking clone only created after phase 0 has started.
internal DistributedDependentTransaction _phase0WaveDependentClone;
internal int _phase0WaveDependentCloneCount;
// These members are used for keeping track of aborting dependent clones if we promote
// BEFORE we get an aborting dependent clone or a Ph1 volatile enlistment. If we
// promote before we get either of these, then we never create a Ph1 volatile enlistment
// on the distributed TM. If we promote AFTER an aborting dependent clone or Ph1 volatile
// enlistment is created, then we create a Ph1 volatile enlistment on the distributed TM
// as part of promotion, so these won't be used. In that case, the Ph1 volatile enlistment
// on the distributed TM takes care of checking to make sure all the aborting dependent
// clones have completed as part of its Prepare processing. These are used in conjunction with
// phase1volatiles.dependentclones.
internal DistributedDependentTransaction _abortingDependentClone;
internal int _abortingDependentCloneCount;
// When the size of the volatile enlistment array grows increase it by this amount.
internal const int VolatileArrayIncrement = 8;
// Data maintained for TransactionTable participation
internal Bucket _tableBucket;
internal int _bucketIndex;
// Delegate to fire on transaction completion
internal TransactionCompletedEventHandler _transactionCompletedDelegate;
// If this transaction get's promoted keep a reference to the promoted transaction
private DistributedTransaction _promotedTransaction;
internal DistributedTransaction PromotedTransaction
{
get { return _promotedTransaction; }
set
{
Debug.Assert(_promotedTransaction == null, "A transaction can only be promoted once!");
_promotedTransaction = value;
}
}
// If there was an exception that happened during promotion save that exception so that it
// can be used as an inner exception to the transaciton aborted exception.
internal Exception _innerException = null;
// Note the number of Transaction objects supported by this object
internal int _cloneCount;
// The number of enlistments on this transaction.
internal int _enlistmentCount = 0;
// Double-checked locking pattern requires volatile for read/write synchronization
// Manual Reset event for IAsyncResult support
internal volatile ManualResetEvent _asyncResultEvent;
// Store the callback and state for the caller of BeginCommit
internal bool _asyncCommit;
internal AsyncCallback _asyncCallback;
internal object _asyncState;
// Flag to indicate if we need to be pulsed for tx completion
internal bool _needPulse;
// Store the transaction information object
internal TransactionInformation _transactionInformation;
// Store a reference to the owning Committable Transaction
internal readonly CommittableTransaction _committableTransaction;
// Store a reference to the outcome source
internal readonly Transaction _outcomeSource;
// Object for synchronizing access to the entire class( avoiding lock( typeof( ... )) )
private static object s_classSyncObject;
internal Guid DistributedTxId => State.get_Identifier(this);
private static string s_instanceIdentifier;
internal static string InstanceIdentifier =>
LazyInitializer.EnsureInitialized(ref s_instanceIdentifier, ref s_classSyncObject, () => Guid.NewGuid().ToString() + ":");
// Double-checked locking pattern requires volatile for read/write synchronization
private volatile bool _traceIdentifierInited = false;
// The trace identifier for the internal transaction.
private TransactionTraceIdentifier _traceIdentifier;
internal TransactionTraceIdentifier TransactionTraceId
{
get
{
if (!_traceIdentifierInited)
{
lock (this)
{
if (!_traceIdentifierInited)
{
TransactionTraceIdentifier temp = new TransactionTraceIdentifier(
InstanceIdentifier + Convert.ToString(_transactionHash, CultureInfo.InvariantCulture),
0);
_traceIdentifier = temp;
_traceIdentifierInited = true;
}
}
}
return _traceIdentifier;
}
}
internal ITransactionPromoter _promoter;
// This member is used to allow a PSPE enlistment to call Transaction.PSPEPromoteAndConvertToEnlistDurable when it is
// asked to promote a transaction. The value is set to true in TransactionStatePSPEOperation.PSPEPromote before the
// Promote call is made and set back to false after the call returns (or an exception is thrown). The value is
// checked for true in TransactionStatePSPEOperation.PSPEPromoteAndConvertToEnlistDurable to make sure the transaction
// is in the process of promoting via a PSPE enlistment.
internal bool _attemptingPSPEPromote = false;
// This is called from TransactionStatePromoted.EnterState. We assume we are promoting to MSDTC.
internal void SetPromoterTypeToMSDTC()
{
// The promoter type should either not yet be set or should already be TransactionInterop.PromoterTypeDtc in this case.
if ((_promoterType != Guid.Empty) && (_promoterType != TransactionInterop.PromoterTypeDtc))
{
throw new InvalidOperationException(SR.PromoterTypeInvalid);
}
_promoterType = TransactionInterop.PromoterTypeDtc;
}
// Throws a TransactionPromotionException if the promoterType is NOT
// Guid.Empty AND NOT TransactionInterop.PromoterTypeDtc.
internal void ThrowIfPromoterTypeIsNotMSDTC()
{
if ((_promoterType != Guid.Empty) && (_promoterType != TransactionInterop.PromoterTypeDtc))
{
throw new TransactionPromotionException(SR.Format(SR.PromoterTypeUnrecognized, _promoterType.ToString()), _innerException);
}
}
// Construct an internal transaction
internal InternalTransaction(TimeSpan timeout, CommittableTransaction committableTransaction)
{
// Calculate the absolute timeout for this transaction
_absoluteTimeout = TransactionManager.TransactionTable.TimeoutTicks(timeout);
// Start the transaction off as active
TransactionState.TransactionStateActive.EnterState(this);
// Until otherwise noted this transaction uses normal promotion.
_promoteState = TransactionState.TransactionStatePromoted;
// Keep a reference to the commitable transaction
_committableTransaction = committableTransaction;
_outcomeSource = committableTransaction;
// Initialize the hash
_transactionHash = TransactionManager.TransactionTable.Add(this);
}
// Construct an internal transaction
internal InternalTransaction(Transaction outcomeSource, DistributedTransaction distributedTx)
{
_promotedTransaction = distributedTx;
_absoluteTimeout = long.MaxValue;
// Store the initial creater as it will be the source of outcome events
_outcomeSource = outcomeSource;
// Initialize the hash
_transactionHash = TransactionManager.TransactionTable.Add(this);
// Start the transaction off as active
TransactionState.TransactionStateNonCommittablePromoted.EnterState(this);
// Until otherwise noted this transaction uses normal promotion.
_promoteState = TransactionState.TransactionStateNonCommittablePromoted;
}
// Construct an internal transaction
internal InternalTransaction(Transaction outcomeSource, ITransactionPromoter promoter)
{
_absoluteTimeout = long.MaxValue;
// Store the initial creater as it will be the source of outcome events
_outcomeSource = outcomeSource;
// Initialize the hash
_transactionHash = TransactionManager.TransactionTable.Add(this);
// Save the transaction promoter.
_promoter = promoter;
// This transaction starts in a special state.
TransactionState.TransactionStateSubordinateActive.EnterState(this);
// This transaction promotes through delegation
_promoteState = TransactionState.TransactionStateDelegatedSubordinate;
}
internal static void DistributedTransactionOutcome(InternalTransaction tx, TransactionStatus status)
{
FinalizedObject fo = null;
lock (tx)
{
if (null == tx._innerException)
{
tx._innerException = tx.PromotedTransaction.InnerException;
}
switch (status)
{
case TransactionStatus.Committed:
{
tx.State.ChangeStatePromotedCommitted(tx);
break;
}
case TransactionStatus.Aborted:
{
tx.State.ChangeStatePromotedAborted(tx);
break;
}
case TransactionStatus.InDoubt:
{
tx.State.InDoubtFromDtc(tx);
break;
}
default:
{
Debug.Fail("InternalTransaction.DistributedTransactionOutcome - Unexpected TransactionStatus");
TransactionException.CreateInvalidOperationException(TraceSourceType.TraceSourceLtm,
"",
null,
tx.DistributedTxId
);
break;
}
}
fo = tx._finalizedObject;
}
if (null != fo)
{
fo.Dispose();
}
}
#region Outcome Events
// Signal Waiters anyone waiting for transaction outcome.
internal void SignalAsyncCompletion()
{
if (_asyncResultEvent != null)
{
_asyncResultEvent.Set();
}
if (_asyncCallback != null)
{
Monitor.Exit(this); // Don't hold a lock calling user code.
try
{
_asyncCallback(_committableTransaction);
}
finally
{
Monitor.Enter(this);
}
}
}
// Fire completion to anyone registered for outcome
internal void FireCompletion()
{
TransactionCompletedEventHandler eventHandlers = _transactionCompletedDelegate;
if (eventHandlers != null)
{
TransactionEventArgs args = new TransactionEventArgs();
args._transaction = _outcomeSource.InternalClone();
eventHandlers(args._transaction, args);
}
}
#endregion
#region IDisposable Members
public void Dispose()
{
if (_promotedTransaction != null)
{
// If there is a promoted transaction dispose it.
_promotedTransaction.Dispose();
}
}
#endregion
}
// Finalized Object
//
// This object is created if the InternalTransaction needs some kind of finalization. An
// InternalTransaction will only need finalization if it is promoted so having a finalizer
// would only hurt performance for the unpromoted case. When the Ltm does promote it creates this
// object which is finalized and will handle the necessary cleanup.
internal sealed class FinalizedObject : IDisposable
{
// Keep the identifier separate. Since it is a struct it won't be finalized out from under
// this object.
private readonly Guid _identifier;
private readonly InternalTransaction _internalTransaction;
internal FinalizedObject(InternalTransaction internalTransaction, Guid identifier)
{
_internalTransaction = internalTransaction;
_identifier = identifier;
}
private void Dispose(bool disposing)
{
if (disposing)
{
GC.SuppressFinalize(this);
}
// We need to remove the entry for the transaction from the static
// LightweightTransactionManager.PromotedTransactionTable.
Hashtable promotedTransactionTable = TransactionManager.PromotedTransactionTable;
lock (promotedTransactionTable)
{
WeakReference weakRef = (WeakReference)promotedTransactionTable[_identifier];
if (null != weakRef)
{
if (weakRef.Target != null)
{
weakRef.Target = null;
}
}
promotedTransactionTable.Remove(_identifier);
}
}
public void Dispose()
{
Dispose(true);
}
~FinalizedObject()
{
Dispose(false);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* 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 CompareNotGreaterThanOrEqualScalarSingle()
{
var test = new SimpleBinaryOpTest__CompareNotGreaterThanOrEqualScalarSingle();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Sse.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 (Sse.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 (Sse.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 works
test.RunLclFldScenario();
// Validates passing an instance member works
test.RunFldScenario();
}
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 SimpleBinaryOpTest__CompareNotGreaterThanOrEqualScalarSingle
{
private const int VectorSize = 16;
private const int Op1ElementCount = VectorSize / sizeof(Single);
private const int Op2ElementCount = VectorSize / sizeof(Single);
private const int RetElementCount = VectorSize / sizeof(Single);
private static Single[] _data1 = new Single[Op1ElementCount];
private static Single[] _data2 = new Single[Op2ElementCount];
private static Vector128<Single> _clsVar1;
private static Vector128<Single> _clsVar2;
private Vector128<Single> _fld1;
private Vector128<Single> _fld2;
private SimpleBinaryOpTest__DataTable<Single, Single, Single> _dataTable;
static SimpleBinaryOpTest__CompareNotGreaterThanOrEqualScalarSingle()
{
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (float)(random.NextDouble()); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data1[0]), VectorSize);
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (float)(random.NextDouble()); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar2), ref Unsafe.As<Single, byte>(ref _data2[0]), VectorSize);
}
public SimpleBinaryOpTest__CompareNotGreaterThanOrEqualScalarSingle()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (float)(random.NextDouble()); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), VectorSize);
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (float)(random.NextDouble()); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), VectorSize);
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (float)(random.NextDouble()); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (float)(random.NextDouble()); }
_dataTable = new SimpleBinaryOpTest__DataTable<Single, Single, Single>(_data1, _data2, new Single[RetElementCount], VectorSize);
}
public bool IsSupported => Sse.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Sse.CompareNotGreaterThanOrEqualScalar(
Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
var result = Sse.CompareNotGreaterThanOrEqualScalar(
Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)),
Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
var result = Sse.CompareNotGreaterThanOrEqualScalar(
Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)),
Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
var result = typeof(Sse).GetMethod(nameof(Sse.CompareNotGreaterThanOrEqualScalar), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
var result = typeof(Sse).GetMethod(nameof(Sse.CompareNotGreaterThanOrEqualScalar), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) })
.Invoke(null, new object[] {
Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)),
Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
var result = typeof(Sse).GetMethod(nameof(Sse.CompareNotGreaterThanOrEqualScalar), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) })
.Invoke(null, new object[] {
Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)),
Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
var result = Sse.CompareNotGreaterThanOrEqualScalar(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
var left = Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr);
var right = Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr);
var result = Sse.CompareNotGreaterThanOrEqualScalar(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
var left = Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr));
var right = Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr));
var result = Sse.CompareNotGreaterThanOrEqualScalar(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
var left = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr));
var right = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr));
var result = Sse.CompareNotGreaterThanOrEqualScalar(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclFldScenario()
{
var test = new SimpleBinaryOpTest__CompareNotGreaterThanOrEqualScalarSingle();
var result = Sse.CompareNotGreaterThanOrEqualScalar(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunFldScenario()
{
var result = Sse.CompareNotGreaterThanOrEqualScalar(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunUnsupportedScenario()
{
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector128<Single> left, Vector128<Single> right, void* result, [CallerMemberName] string method = "")
{
Single[] inArray1 = new Single[Op1ElementCount];
Single[] inArray2 = new Single[Op2ElementCount];
Single[] outArray = new Single[RetElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left);
Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "")
{
Single[] inArray1 = new Single[Op1ElementCount];
Single[] inArray2 = new Single[Op2ElementCount];
Single[] outArray = new Single[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Single[] left, Single[] right, Single[] result, [CallerMemberName] string method = "")
{
if (BitConverter.SingleToInt32Bits(result[0]) != (!(left[0] >= right[0]) ? -1 : 0))
{
Succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (BitConverter.SingleToInt32Bits(left[i]) != BitConverter.SingleToInt32Bits(result[i]))
{
Succeeded = false;
break;
}
}
}
if (!Succeeded)
{
Console.WriteLine($"{nameof(Sse)}.{nameof(Sse.CompareNotGreaterThanOrEqualScalar)}<Single>(Vector128<Single>, Vector128<Single>): {method} failed:");
Console.WriteLine($" left: ({string.Join(", ", left)})");
Console.WriteLine($" right: ({string.Join(", ", right)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
using System;
using Newtonsoft.Json;
namespace Eb
{
[Serializable]
[JsonObject(MemberSerialization.OptIn)]
public struct EbVector3 : IEquatable<EbVector3>
{
//---------------------------------------------------------------------
[JsonProperty(PropertyName = "x")]
public float x { get; set; }// Gets or sets the X value.
[JsonProperty(PropertyName = "y")]
public float y { get; set; }// Gets or sets Y value.
[JsonProperty(PropertyName = "z")]
public float z { get; set; }// Gets or sets Z value.
public float Length { get { return (float)Math.Sqrt((x * x) + (y * y) + (z * z)); } }
public float Length2 { get { return ((x * x) + (y * y) + (z * z)); } }
//---------------------------------------------------------------------
public EbVector3(float x, float y, float z)
: this()
{
this.x = x;
this.y = y;
this.z = z;
}
//---------------------------------------------------------------------
public static EbVector3 Zero
{
get
{
EbVector3 v3 = new EbVector3();
v3.x = 0.0f;
v3.y = 0.0f;
v3.z = 0.0f;
return v3;
}
}
//---------------------------------------------------------------------
public static EbVector3 UnitX
{
get
{
EbVector3 v3 = new EbVector3();
v3.x = 1.0f;
v3.y = 0.0f;
v3.z = 0.0f;
return v3;
}
}
//---------------------------------------------------------------------
public static EbVector3 UnitY
{
get
{
EbVector3 v3 = new EbVector3();
v3.x = 0.0f;
v3.y = 1.0f;
v3.z = 0.0f;
return v3;
}
}
//---------------------------------------------------------------------
public static EbVector3 UnitZ
{
get
{
EbVector3 v3 = new EbVector3();
v3.x = 0.0f;
v3.y = 0.0f;
v3.z = 1.0f;
return v3;
}
}
//---------------------------------------------------------------------
public static EbVector3 Unit
{
get
{
EbVector3 v3 = new EbVector3();
v3.x = 1.0f;
v3.y = 1.0f;
v3.z = 1.0f;
return v3;
}
}
//---------------------------------------------------------------------
public bool Equals(EbVector3 other)
{
return this.x.Equals(other.x) && this.y.Equals(other.y) && this.z.Equals(other.z);
}
//---------------------------------------------------------------------
public override bool Equals(object obj)
{
if (obj is EbVector3)
{
var other = (EbVector3)obj;
return this.Equals(other);
}
return false;
}
//---------------------------------------------------------------------
public override int GetHashCode()
{
int result = this.x.GetHashCode();
result ^= this.y.GetHashCode();
result ^= this.z.GetHashCode();
return result;
}
//---------------------------------------------------------------------
public override string ToString()
{
return string.Format("{0}({1},{2},{3})", base.ToString(), this.x, this.y, this.z);
}
//---------------------------------------------------------------------
public static bool operator ==(EbVector3 coordinate1, EbVector3 coordinate2)
{
return coordinate1.Equals(coordinate2);
}
//---------------------------------------------------------------------
public static bool operator !=(EbVector3 coordinate1, EbVector3 coordinate2)
{
return coordinate1.Equals(coordinate2) == false;
}
//---------------------------------------------------------------------
public static EbVector3 operator +(EbVector3 a, EbVector3 b)
{
return new EbVector3 { x = a.x + b.x, y = a.y + b.y, z = a.z + b.z };
}
//---------------------------------------------------------------------
public static EbVector3 operator -(EbVector3 a, EbVector3 b)
{
return new EbVector3 { x = a.x - b.x, y = a.y - b.y, z = a.z - b.z };
}
//---------------------------------------------------------------------
public static EbVector3 operator -(EbVector3 a)
{
return new EbVector3 { x = -a.x, y = -a.y, z = -a.z };
}
//---------------------------------------------------------------------
public static EbVector3 operator *(EbVector3 a, int b)
{
return new EbVector3 { x = a.x * b, y = a.y * b, z = a.z * b };
}
//---------------------------------------------------------------------
public static EbVector3 operator *(EbVector3 a, float b)
{
return new EbVector3 { x = a.x * b, y = a.y * b, z = a.z * b };
}
//---------------------------------------------------------------------
public static EbVector3 operator /(EbVector3 a, int b)
{
return new EbVector3 { x = a.x / b, y = a.y / b, z = a.z / b };
}
//---------------------------------------------------------------------
public static EbVector3 operator /(EbVector3 a, float b)
{
return new EbVector3 { x = a.x / b, y = a.y / b, z = a.z / b };
}
//---------------------------------------------------------------------
public static EbVector3 max(EbVector3 value1, EbVector3 value2)
{
return new EbVector3 { x = Math.Max(value1.x, value2.x), y = Math.Max(value1.y, value2.y), z = Math.Max(value1.z, value2.z) };
}
//---------------------------------------------------------------------
public static EbVector3 min(EbVector3 value1, EbVector3 value2)
{
return new EbVector3 { x = Math.Min(value1.x, value2.x), y = Math.Min(value1.y, value2.y), z = Math.Min(value1.z, value2.z) };
}
//---------------------------------------------------------------------
public static EbVector3 lerp(EbVector3 from, EbVector3 to, float t)
{
EbVector3 v = from;
v += (to - from) * t;
return v;
}
//---------------------------------------------------------------------
public static float dot(EbVector3 lhs, EbVector3 rhs)
{
return (((lhs.x * rhs.x) + (lhs.y * rhs.y)) + (lhs.z * rhs.z));
}
//---------------------------------------------------------------------
public static EbVector3 cross(EbVector3 v1, EbVector3 v2)
{
EbVector3 result = new EbVector3();
result.x = (v1.y * v2.z) - (v1.z * v2.y);
result.y = (v1.z * v2.x) - (v1.x * v2.z);
result.z = (v1.x * v2.y) - (v1.y * v2.x);
return result;
}
//---------------------------------------------------------------------
public static EbVector3 project(EbVector3 vector, EbVector3 on_normal)
{
float num = dot(on_normal, on_normal);
if (num < float.Epsilon)
{
return Zero;
}
return (EbVector3)((on_normal * dot(vector, on_normal)) / num);
}
//---------------------------------------------------------------------
public float getDistance(EbVector3 vector)
{
return (float)Math.Sqrt(Math.Pow(vector.x - this.x, 2) + Math.Pow(vector.y - this.y, 2) + Math.Pow(vector.z - this.z, 2));
}
//---------------------------------------------------------------------
public static float magnitude(EbVector3 a)
{
return (float)Math.Sqrt(((a.x * a.x) + (a.y * a.y)) + (a.z * a.z));
}
//---------------------------------------------------------------------
public void normalize()
{
float num = magnitude(this);
if (num > 1E-05f)
{
this = (EbVector3)(this / num);
}
else
{
this = Zero;
}
}
//---------------------------------------------------------------------
public static EbVector3 normalize(EbVector3 value)
{
float num = magnitude(value);
if (num > 1E-05f)
{
return (EbVector3)(value / num);
}
return Zero;
}
//---------------------------------------------------------------------
public EbVector3 normalized
{
get
{
return normalize(this);
}
}
}
}
| |
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 Sogeti.Capstone.Api.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;
}
}
}
| |
/**
* FreeRDP: A Remote Desktop Protocol Implementation
* Secondary Updates
*
* Copyright 2011-2012 Marc-Andre Moreau <marcandre.moreau@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Runtime.InteropServices;
namespace FreeRDP
{
[StructLayout(LayoutKind.Sequential)]
public unsafe struct CacheBitmapOrder
{
public UInt32 cacheId;
public UInt32 bitmapBpp;
public UInt32 bitmapWidth;
public UInt32 bitmapHeight;
public UInt32 bitmapLength;
public UInt32 cacheIndex;
public fixed byte bitmapComprHdr[8];
public byte* bitmapDataStream;
}
[StructLayout(LayoutKind.Sequential)]
public unsafe struct CacheBitmapV2Order
{
public UInt32 cacheId;
public UInt32 flags;
public UInt32 key1;
public UInt32 key2;
public UInt32 bitmapBpp;
public UInt32 bitmapWidth;
public UInt32 bitmapHeight;
public UInt32 bitmapLength;
public UInt32 cacheIndex;
public int compressed;
public fixed byte bitmapComprHdr[8];
public byte* bitmapDataStream;
}
[StructLayout(LayoutKind.Sequential)]
public unsafe struct BitmapDataEx
{
public UInt32 bpp;
public UInt32 codecID;
public UInt32 width;
public UInt32 height;
public UInt32 length;
public byte* data;
}
[StructLayout(LayoutKind.Sequential)]
public unsafe struct CacheBitmapV3Order
{
public UInt32 cacheId;
public UInt32 bpp;
public UInt32 flags;
public UInt32 cacheIndex;
public UInt32 key1;
public UInt32 key2;
public BitmapDataEx* bitmapData;
}
[StructLayout(LayoutKind.Sequential)]
public unsafe struct CacheColorTableOrder
{
public UInt32 cacheIndex;
public UInt32 numberColors;
public UInt32* colorTable;
}
[StructLayout(LayoutKind.Sequential)]
public unsafe struct GlyphData
{
public UInt32 cacheIndex;
public Int32 x;
public Int32 y;
public UInt32 cx;
public UInt32 cy;
public UInt32 cb;
public byte* aj;
}
[StructLayout(LayoutKind.Sequential)]
public unsafe struct CacheGlyphOrder
{
public UInt32 cacheId;
public UInt32 cGlyphs;
//public GlyphData glyphData[255];
public byte* unicodeCharacters;
}
[StructLayout(LayoutKind.Sequential)]
public unsafe struct GlyphDataV2
{
public UInt32 cacheIndex;
public Int32 x;
public Int32 y;
public UInt32 cx;
public UInt32 cy;
public UInt32 cb;
public byte* aj;
}
[StructLayout(LayoutKind.Sequential)]
public unsafe struct CacheGlyphV2Order
{
public UInt32 cacheId;
public UInt32 flags;
public UInt32 cGlyphs;
//public GlyphDataV2 glyphData[255];
public byte* unicodeCharacters;
}
[StructLayout(LayoutKind.Sequential)]
public unsafe struct CacheBrushOrder
{
public UInt32 index;
public UInt32 bpp;
public UInt32 cx;
public UInt32 cy;
public UInt32 style;
public UInt32 length;
public byte* data;
}
[StructLayout(LayoutKind.Sequential)]
public unsafe struct rdpSecondaryUpdate
{
public rdpContext* context;
public fixed UInt32 paddingA[16-1];
public IntPtr CacheBitmap;
public IntPtr CacheBitmapV2;
public IntPtr CacheBitmapV3;
public IntPtr CacheColorTable;
public IntPtr CacheGlyph;
public IntPtr CacheGlyphV2;
public IntPtr CacheBrush;
public fixed UInt32 paddingB[32-23];
}
public unsafe interface ISecondaryUpdate
{
void CacheBitmap(rdpContext* context, CacheBitmapOrder* cacheBitmapOrder);
void CacheBitmapV2(rdpContext* context, CacheBitmapV2Order* cacheBitmapV2Order);
void CacheBitmapV3(rdpContext* context, CacheBitmapV3Order* cacheBitmapV3Order);
void CacheColorTable(rdpContext* context, CacheColorTableOrder* cacheColorTableOrder);
void CacheGlyph(rdpContext* context, CacheGlyphOrder* cacheGlyphOrder);
void CacheGlyphV2(rdpContext* context, CacheGlyphV2Order* cacheGlyphV2Order);
void CacheBrush(rdpContext* context, CacheBrushOrder* cacheBrushOrder);
}
public unsafe class SecondaryUpdate
{
private freerdp* instance;
private rdpContext* context;
private rdpUpdate* update;
private rdpSecondaryUpdate* secondary;
delegate void CacheBitmapDelegate(rdpContext* context, CacheBitmapOrder* cacheBitmapOrder);
delegate void CacheBitmapV2Delegate(rdpContext* context, CacheBitmapV2Order* cacheBitmapV2Order);
delegate void CacheBitmapV3Delegate(rdpContext* context, CacheBitmapV3Order* cacheBitmapV3Order);
delegate void CacheColorTableDelegate(rdpContext* context, CacheColorTableOrder* cacheColorTableOrder);
delegate void CacheGlyphDelegate(rdpContext* context, CacheGlyphOrder* cacheGlyphOrder);
delegate void CacheGlyphV2Delegate(rdpContext* context, CacheGlyphV2Order* cacheGlyphV2Order);
delegate void CacheBrushDelegate(rdpContext* context, CacheBrushOrder* cacheBrushOrder);
private CacheBitmapDelegate CacheBitmap;
private CacheBitmapV2Delegate CacheBitmapV2;
private CacheBitmapV3Delegate CacheBitmapV3;
private CacheColorTableDelegate CacheColorTable;
private CacheGlyphDelegate CacheGlyph;
private CacheGlyphV2Delegate CacheGlyphV2;
private CacheBrushDelegate CacheBrush;
public SecondaryUpdate(rdpContext* context)
{
this.context = context;
this.instance = context->instance;
this.update = instance->update;
this.secondary = update->secondary;
}
public void RegisterInterface(ISecondaryUpdate iSecondary)
{
CacheBitmap = new CacheBitmapDelegate(iSecondary.CacheBitmap);
CacheBitmapV2 = new CacheBitmapV2Delegate(iSecondary.CacheBitmapV2);
CacheBitmapV3 = new CacheBitmapV3Delegate(iSecondary.CacheBitmapV3);
CacheColorTable = new CacheColorTableDelegate(iSecondary.CacheColorTable);
CacheGlyph = new CacheGlyphDelegate(iSecondary.CacheGlyph);
CacheGlyphV2 = new CacheGlyphV2Delegate(iSecondary.CacheGlyphV2);
CacheBrush = new CacheBrushDelegate(iSecondary.CacheBrush);
secondary->CacheBitmap = Marshal.GetFunctionPointerForDelegate(CacheBitmap);
secondary->CacheBitmapV2 = Marshal.GetFunctionPointerForDelegate(CacheBitmapV2);
secondary->CacheBitmapV3 = Marshal.GetFunctionPointerForDelegate(CacheBitmapV3);
secondary->CacheColorTable = Marshal.GetFunctionPointerForDelegate(CacheColorTable);
secondary->CacheGlyph = Marshal.GetFunctionPointerForDelegate(CacheGlyph);
secondary->CacheGlyphV2 = Marshal.GetFunctionPointerForDelegate(CacheGlyphV2);
secondary->CacheBrush = Marshal.GetFunctionPointerForDelegate(CacheBrush);
}
}
}
| |
/* ====================================================================
*/
using System;
using System.Drawing;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows.Forms;
using System.Xml;
using System.Text;
using System.Reflection;
using Oranikle.Report.Engine;
namespace Oranikle.ReportDesigner
{
/// <summary>
/// DialogListOfStrings: puts up a dialog that lets a user enter a list of strings
/// </summary>
public class DialogExprEditor : System.Windows.Forms.Form
{
Type[] BASE_TYPES = new Type[]
{
typeof(string),
typeof(double),
typeof(Single),
typeof(decimal),
typeof(DateTime),
typeof(char),
typeof(bool),
typeof(int),
typeof(short),
typeof(long),
typeof(byte),
typeof(UInt16),
typeof(UInt32),
typeof(UInt64)
};
private DesignXmlDraw _Draw; // design draw
private bool _Color; // true if color list should be displayed
private SplitContainer splitContainer1;
private Oranikle.Studio.Controls.StyledButton bCopy;
private Label lOp;
private Oranikle.Studio.Controls.CustomTextControl tbExpr;
private Label lExpr;
private TreeView tvOp;
private Panel panel1;
private Oranikle.Studio.Controls.StyledButton bCancel;
private Oranikle.Studio.Controls.StyledButton bOK;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
internal DialogExprEditor(DesignXmlDraw dxDraw, string expr, XmlNode node) :
this(dxDraw, expr, node, false)
{
}
internal DialogExprEditor(DesignXmlDraw dxDraw, string expr, XmlNode node, bool bColor)
{
_Draw = dxDraw;
_Color = bColor;
//
// Required for Windows Form Designer support
//
InitializeComponent();
tbExpr.Text = expr;
// Fill out the fields list
string[] fields = null;
// Find the dataregion that contains the item (if any)
for (XmlNode pNode = node; pNode != null; pNode = pNode.ParentNode)
{
if (pNode.Name == "List" ||
pNode.Name == "Table" ||
pNode.Name == "Matrix" ||
pNode.Name == "Chart")
{
string dsname = _Draw.GetDataSetNameValue(pNode);
if (dsname != null) // found it
{
fields = _Draw.GetFields(dsname, true);
}
}
}
BuildTree(fields);
return;
}
void BuildTree(string[] flds)
{
// suppress redraw until tree view is complete
tvOp.BeginUpdate();
//AJM GJL Adding Missing 'User' Menu
// Handle the user
TreeNode ndRoot = new TreeNode("User");
tvOp.Nodes.Add(ndRoot);
foreach (string item in StaticLists.UserList)
{
// Add the node to the tree
TreeNode aRoot = new TreeNode(item.StartsWith("=") ? item.Substring(1) : item);
ndRoot.Nodes.Add(aRoot);
}
// Handle the globals
ndRoot = new TreeNode("Globals");
tvOp.Nodes.Add(ndRoot);
foreach (string item in StaticLists.GlobalList)
{
// Add the node to the tree
TreeNode aRoot = new TreeNode(item.StartsWith("=")? item.Substring(1): item);
ndRoot.Nodes.Add(aRoot);
}
// Fields - only when a dataset is specified
if (flds != null && flds.Length > 0)
{
ndRoot = new TreeNode("Fields");
tvOp.Nodes.Add(ndRoot);
foreach (string f in flds)
{
TreeNode aRoot = new TreeNode(f.StartsWith("=")? f.Substring(1): f);
ndRoot.Nodes.Add(aRoot);
}
}
// Report parameters
InitReportParameters();
// Handle the functions
ndRoot = new TreeNode("Functions");
tvOp.Nodes.Add(ndRoot);
InitFunctions(ndRoot);
// Aggregate functions
ndRoot = new TreeNode("Aggregate Functions");
tvOp.Nodes.Add(ndRoot);
foreach (string item in StaticLists.AggrFunctionList)
{
// Add the node to the tree
TreeNode aRoot = new TreeNode(item);
ndRoot.Nodes.Add(aRoot);
}
// Operators
ndRoot = new TreeNode("Operators");
tvOp.Nodes.Add(ndRoot);
foreach (string item in StaticLists.OperatorList)
{
// Add the node to the tree
TreeNode aRoot = new TreeNode(item);
ndRoot.Nodes.Add(aRoot);
}
// Colors (if requested)
if (_Color)
{
ndRoot = new TreeNode("Colors");
tvOp.Nodes.Add(ndRoot);
foreach (string item in StaticLists.ColorList)
{
// Add the node to the tree
TreeNode aRoot = new TreeNode(item);
ndRoot.Nodes.Add(aRoot);
}
}
tvOp.EndUpdate();
}
/// <summary>
/// Populate tree view with the report parameters (if any)
/// </summary>
void InitReportParameters()
{
string[] ps = _Draw.GetReportParameters(true);
if (ps == null || ps.Length == 0)
return;
TreeNode ndRoot = new TreeNode("Parameters");
tvOp.Nodes.Add(ndRoot);
foreach (string p in ps)
{
TreeNode aRoot = new TreeNode(p.StartsWith("=")?p.Substring(1): p);
ndRoot.Nodes.Add(aRoot);
}
return;
}
void InitFunctions(TreeNode ndRoot)
{
List<string> ar = new List<string>();
ar.AddRange(StaticLists.FunctionList);
// Build list of methods in the VBFunctions class
Oranikle.Report.Engine.FontStyleEnum fsi = FontStyleEnum.Italic; // just want a class from RdlEngine.dll assembly
Assembly a = Assembly.GetAssembly(fsi.GetType());
if (a == null)
return;
Type ft = a.GetType("Oranikle.Report.Engine.VBFunctions");
BuildMethods(ar, ft, "");
// build list of financial methods in Financial class
ft = a.GetType("Oranikle.Report.Engine.Financial");
BuildMethods(ar, ft, "Financial.");
a = Assembly.GetAssembly("".GetType());
ft = a.GetType("System.Math");
BuildMethods(ar, ft, "Math.");
ft = a.GetType("System.Convert");
BuildMethods(ar, ft, "Convert.");
ft = a.GetType("System.String");
BuildMethods(ar, ft, "String.");
ar.Sort();
string previous="";
foreach (string item in ar)
{
if (item != previous) // don't add duplicates
{
// Add the node to the tree
TreeNode aRoot = new TreeNode(item);
ndRoot.Nodes.Add(aRoot);
}
previous = item;
}
}
void BuildMethods(List<string> ar, Type ft, string prefix)
{
if (ft == null)
return;
MethodInfo[] mis = ft.GetMethods(BindingFlags.Static | BindingFlags.Public);
foreach (MethodInfo mi in mis)
{
// Add the node to the tree
string name = BuildMethodName(mi);
if (name != null)
ar.Add(prefix + name);
}
}
string BuildMethodName(MethodInfo mi)
{
StringBuilder sb = new StringBuilder(mi.Name);
sb.Append("(");
ParameterInfo[] pis = mi.GetParameters();
bool bFirst=true;
foreach (ParameterInfo pi in pis)
{
if (!IsBaseType(pi.ParameterType))
return null;
if (bFirst)
bFirst = false;
else
sb.Append(", ");
sb.Append(pi.Name);
}
sb.Append(")");
return sb.ToString();
}
// Determines if underlying type is a primitive
bool IsBaseType(Type t)
{
foreach (Type bt in BASE_TYPES)
{
if (bt == t)
return true;
}
return false;
}
public string Expression
{
get {return tbExpr.Text; }
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.panel1 = new System.Windows.Forms.Panel();
this.bCancel = new Oranikle.Studio.Controls.StyledButton();
this.bOK = new Oranikle.Studio.Controls.StyledButton();
this.splitContainer1 = new System.Windows.Forms.SplitContainer();
this.tvOp = new System.Windows.Forms.TreeView();
this.bCopy = new Oranikle.Studio.Controls.StyledButton();
this.lOp = new System.Windows.Forms.Label();
this.tbExpr = new Oranikle.Studio.Controls.CustomTextControl();
this.lExpr = new System.Windows.Forms.Label();
this.panel1.SuspendLayout();
this.splitContainer1.Panel1.SuspendLayout();
this.splitContainer1.Panel2.SuspendLayout();
this.splitContainer1.SuspendLayout();
this.SuspendLayout();
//
// panel1
//
this.panel1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.panel1.Controls.Add(this.bCancel);
this.panel1.Controls.Add(this.bOK);
this.panel1.Location = new System.Drawing.Point(0, 407);
this.panel1.Name = "panel1";
this.panel1.Size = new System.Drawing.Size(857, 40);
this.panel1.TabIndex = 15;
//
// bCancel
//
this.bCancel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.bCancel.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(245)))), ((int)(((byte)(245)))), ((int)(((byte)(245)))));
this.bCancel.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(225)))), ((int)(((byte)(225)))), ((int)(((byte)(225)))));
this.bCancel.BackFillMode = System.Drawing.Drawing2D.LinearGradientMode.ForwardDiagonal;
this.bCancel.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(200)))), ((int)(((byte)(200)))), ((int)(((byte)(200)))));
this.bCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.bCancel.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.bCancel.Font = new System.Drawing.Font("Arial", 9F);
this.bCancel.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(90)))), ((int)(((byte)(90)))), ((int)(((byte)(90)))));
this.bCancel.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.bCancel.Location = new System.Drawing.Point(768, 9);
this.bCancel.Name = "bCancel";
this.bCancel.OverriddenSize = null;
this.bCancel.Size = new System.Drawing.Size(75, 21);
this.bCancel.TabIndex = 5;
this.bCancel.Text = "Cancel";
this.bCancel.UseVisualStyleBackColor = true;
//
// bOK
//
this.bOK.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.bOK.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(245)))), ((int)(((byte)(245)))), ((int)(((byte)(245)))));
this.bOK.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(225)))), ((int)(((byte)(225)))), ((int)(((byte)(225)))));
this.bOK.BackFillMode = System.Drawing.Drawing2D.LinearGradientMode.ForwardDiagonal;
this.bOK.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(200)))), ((int)(((byte)(200)))), ((int)(((byte)(200)))));
this.bOK.DialogResult = System.Windows.Forms.DialogResult.OK;
this.bOK.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.bOK.Font = new System.Drawing.Font("Arial", 9F);
this.bOK.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(90)))), ((int)(((byte)(90)))), ((int)(((byte)(90)))));
this.bOK.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.bOK.Location = new System.Drawing.Point(687, 9);
this.bOK.Name = "bOK";
this.bOK.OverriddenSize = null;
this.bOK.Size = new System.Drawing.Size(75, 21);
this.bOK.TabIndex = 4;
this.bOK.Text = "OK";
this.bOK.UseVisualStyleBackColor = true;
//
// splitContainer1
//
this.splitContainer1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.splitContainer1.Location = new System.Drawing.Point(0, 0);
this.splitContainer1.Name = "splitContainer1";
//
// splitContainer1.Panel1
//
this.splitContainer1.Panel1.Controls.Add(this.tvOp);
this.splitContainer1.Panel1.Controls.Add(this.bCopy);
this.splitContainer1.Panel1.Controls.Add(this.lOp);
//
// splitContainer1.Panel2
//
this.splitContainer1.Panel2.Controls.Add(this.tbExpr);
this.splitContainer1.Panel2.Controls.Add(this.lExpr);
this.splitContainer1.Size = new System.Drawing.Size(857, 402);
this.splitContainer1.SplitterDistance = 285;
this.splitContainer1.TabIndex = 14;
//
// tvOp
//
this.tvOp.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.tvOp.Location = new System.Drawing.Point(0, 29);
this.tvOp.Name = "tvOp";
this.tvOp.Size = new System.Drawing.Size(282, 370);
this.tvOp.TabIndex = 1;
//
// bCopy
//
this.bCopy.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.bCopy.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(245)))), ((int)(((byte)(245)))), ((int)(((byte)(245)))));
this.bCopy.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(225)))), ((int)(((byte)(225)))), ((int)(((byte)(225)))));
this.bCopy.BackFillMode = System.Drawing.Drawing2D.LinearGradientMode.ForwardDiagonal;
this.bCopy.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(200)))), ((int)(((byte)(200)))), ((int)(((byte)(200)))));
this.bCopy.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.bCopy.Font = new System.Drawing.Font("Arial", 9F);
this.bCopy.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(90)))), ((int)(((byte)(90)))), ((int)(((byte)(90)))));
this.bCopy.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.bCopy.Location = new System.Drawing.Point(250, 4);
this.bCopy.Name = "bCopy";
this.bCopy.OverriddenSize = null;
this.bCopy.Size = new System.Drawing.Size(32, 21);
this.bCopy.TabIndex = 2;
this.bCopy.Text = ">>";
this.bCopy.UseVisualStyleBackColor = true;
this.bCopy.Click += new System.EventHandler(this.bCopy_Click);
//
// lOp
//
this.lOp.Location = new System.Drawing.Point(0, 4);
this.lOp.Name = "lOp";
this.lOp.Size = new System.Drawing.Size(106, 23);
this.lOp.TabIndex = 14;
this.lOp.Text = "Select and hit \'>>\'";
//
// tbExpr
//
this.tbExpr.AcceptsReturn = true;
this.tbExpr.AcceptsTab = true;
this.tbExpr.AddX = 0;
this.tbExpr.AddY = 0;
this.tbExpr.AllowSpace = false;
this.tbExpr.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.tbExpr.BorderColor = System.Drawing.Color.LightGray;
this.tbExpr.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.tbExpr.ChangeVisibility = false;
this.tbExpr.ChildControl = null;
this.tbExpr.ConvertEnterToTab = true;
this.tbExpr.ConvertEnterToTabForDialogs = false;
this.tbExpr.Decimals = 0;
this.tbExpr.DisplayList = new object[0];
this.tbExpr.HitText = Oranikle.Studio.Controls.HitText.String;
this.tbExpr.Location = new System.Drawing.Point(6, 32);
this.tbExpr.Multiline = true;
this.tbExpr.Name = "tbExpr";
this.tbExpr.OnDropDownCloseFocus = true;
this.tbExpr.ScrollBars = System.Windows.Forms.ScrollBars.Both;
this.tbExpr.SelectType = 0;
this.tbExpr.Size = new System.Drawing.Size(559, 367);
this.tbExpr.TabIndex = 0;
this.tbExpr.UseValueForChildsVisibilty = false;
this.tbExpr.Value = true;
this.tbExpr.WordWrap = false;
//
// lExpr
//
this.lExpr.Location = new System.Drawing.Point(3, 6);
this.lExpr.Name = "lExpr";
this.lExpr.Size = new System.Drawing.Size(134, 20);
this.lExpr.TabIndex = 13;
this.lExpr.Text = "Expressions start with \'=\'";
//
// DialogExprEditor
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(228)))), ((int)(((byte)(241)))), ((int)(((byte)(249)))));
this.CancelButton = this.bCancel;
this.ClientSize = new System.Drawing.Size(857, 447);
this.Controls.Add(this.splitContainer1);
this.Controls.Add(this.panel1);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.SizableToolWindow;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "DialogExprEditor";
this.ShowInTaskbar = false;
this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Show;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "Edit Expression";
this.panel1.ResumeLayout(false);
this.splitContainer1.Panel1.ResumeLayout(false);
this.splitContainer1.Panel2.ResumeLayout(false);
this.splitContainer1.Panel2.PerformLayout();
this.splitContainer1.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
private void bCopy_Click(object sender, System.EventArgs e)
{
if (tvOp.SelectedNode == null ||
tvOp.SelectedNode.Parent == null)
return; // this is the top level nodes (Fields, Parameters, ...)
TreeNode node = tvOp.SelectedNode;
string t = node.Text;
if (tbExpr.Text.Length == 0)
t = "=" + t;
tbExpr.SelectedText = t;
}
}
}
| |
#region License, Terms and Author(s)
//
// ELMAH - Error Logging Modules and Handlers for ASP.NET
// Copyright (c) 2004-9 Atif Aziz. All rights reserved.
//
// Author(s):
//
// Atif Aziz, http://www.raboof.com
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
[assembly: Elmah.Scc("$Id: MemoryErrorLog.cs 776 2011-01-12 21:09:24Z azizatif $")]
namespace Elmah
{
#region Imports
using System;
using ReaderWriterLock = System.Threading.ReaderWriterLock;
using Timeout = System.Threading.Timeout;
using NameObjectCollectionBase = System.Collections.Specialized.NameObjectCollectionBase;
using IDictionary = System.Collections.IDictionary;
using CultureInfo = System.Globalization.CultureInfo;
using System.Collections.Generic;
#endregion
/// <summary>
/// An <see cref="ErrorLog"/> implementation that uses memory as its
/// backing store.
/// </summary>
/// <remarks>
/// All <see cref="MemoryErrorLog"/> instances will share the same memory
/// store that is bound to the application (not an instance of this class).
/// </remarks>
public sealed class MemoryErrorLog : ErrorLog
{
//
// The collection that provides the actual storage for this log
// implementation and a lock to guarantee concurrency correctness.
//
private static EntryCollection _entries;
private readonly static ReaderWriterLock _lock = new ReaderWriterLock();
//
// IMPORTANT! The size must be the same for all instances
// for the entires collection to be intialized correctly.
//
private readonly int _size;
/// <summary>
/// The maximum number of errors that will ever be allowed to be stored
/// in memory.
/// </summary>
public static readonly int MaximumSize = 500;
/// <summary>
/// The maximum number of errors that will be held in memory by default
/// if no size is specified.
/// </summary>
public static readonly int DefaultSize = 15;
/// <summary>
/// Initializes a new instance of the <see cref="MemoryErrorLog"/> class
/// with a default size for maximum recordable entries.
/// </summary>
public MemoryErrorLog() : this(DefaultSize) {}
/// <summary>
/// Initializes a new instance of the <see cref="MemoryErrorLog"/> class
/// with a specific size for maximum recordable entries.
/// </summary>
public MemoryErrorLog(int size)
{
if (size < 0 || size > MaximumSize)
throw new ArgumentOutOfRangeException("size", size, string.Format("Size must be between 0 and {0}.", MaximumSize));
_size = size;
}
/// <summary>
/// Initializes a new instance of the <see cref="MemoryErrorLog"/> class
/// using a dictionary of configured settings.
/// </summary>
public MemoryErrorLog(IDictionary config)
{
if (config == null)
{
_size = DefaultSize;
}
else
{
var sizeString = config.Find("size", string.Empty);
if (sizeString.Length == 0)
{
_size = DefaultSize;
}
else
{
_size = Convert.ToInt32(sizeString, CultureInfo.InvariantCulture);
_size = Math.Max(0, Math.Min(MaximumSize, _size));
}
}
}
/// <summary>
/// Gets the name of this error log implementation.
/// </summary>
public override string Name
{
get { return "In-Memory Error Log"; }
}
/// <summary>
/// Logs an error to the application memory.
/// </summary>
/// <remarks>
/// If the log is full then the oldest error entry is removed.
/// </remarks>
public override string Log(Error error)
{
if (error == null)
throw new ArgumentNullException("error");
//
// Make a copy of the error to log since the source is mutable.
// Assign a new GUID and create an entry for the error.
//
error = (Error) ((ICloneable) error).Clone();
error.ApplicationName = this.ApplicationName;
Guid newId = Guid.NewGuid();
ErrorLogEntry entry = new ErrorLogEntry(this, newId.ToString(), error);
_lock.AcquireWriterLock(Timeout.Infinite);
try
{
if (_entries == null)
_entries = new EntryCollection(_size);
_entries.Add(entry);
}
finally
{
_lock.ReleaseWriterLock();
}
return newId.ToString();
}
/// <summary>
/// Returns the specified error from application memory, or null
/// if it does not exist.
/// </summary>
public override ErrorLogEntry GetError(string id)
{
_lock.AcquireReaderLock(Timeout.Infinite);
ErrorLogEntry entry;
try
{
if (_entries == null)
return null;
entry = _entries[id];
}
finally
{
_lock.ReleaseReaderLock();
}
if (entry == null)
return null;
//
// Return a copy that the caller can party on.
//
Error error = (Error) ((ICloneable) entry.Error).Clone();
return new ErrorLogEntry(this, entry.Id, error);
}
/// <summary>
/// Returns a page of errors from the application memory in
/// descending order of logged time.
/// </summary>
public override int GetErrors(int pageIndex, int pageSize, IList<ErrorLogEntry> errorEntryList)
{
if (pageIndex < 0)
throw new ArgumentOutOfRangeException("pageIndex", pageIndex, null);
if (pageSize < 0)
throw new ArgumentOutOfRangeException("pageSize", pageSize, null);
//
// To minimize the time for which we hold the lock, we'll first
// grab just references to the entries we need to return. Later,
// we'll make copies and return those to the caller. Since Error
// is mutable, we don't want to return direct references to our
// internal versions since someone could change their state.
//
ErrorLogEntry[] selectedEntries = null;
int totalCount;
_lock.AcquireReaderLock(Timeout.Infinite);
try
{
if (_entries == null)
return 0;
totalCount = _entries.Count;
int startIndex = pageIndex * pageSize;
int endIndex = Math.Min(startIndex + pageSize, totalCount);
int count = Math.Max(0, endIndex - startIndex);
if (count > 0)
{
selectedEntries = new ErrorLogEntry[count];
int sourceIndex = endIndex;
int targetIndex = 0;
while (sourceIndex > startIndex)
selectedEntries[targetIndex++] = _entries[--sourceIndex];
}
}
finally
{
_lock.ReleaseReaderLock();
}
if (errorEntryList != null && selectedEntries != null)
{
//
// Return copies of fetched entries. If the Error class would
// be immutable then this step wouldn't be necessary.
//
foreach (ErrorLogEntry entry in selectedEntries)
{
Error error = (Error)((ICloneable)entry.Error).Clone();
errorEntryList.Add(new ErrorLogEntry(this, entry.Id, error));
}
}
return totalCount;
}
private class EntryCollection : NameObjectCollectionBase
{
private readonly int _size;
public EntryCollection(int size) : base(size)
{
_size = size;
}
public ErrorLogEntry this[int index]
{
get { return (ErrorLogEntry) BaseGet(index); }
}
public ErrorLogEntry this[Guid id]
{
get { return (ErrorLogEntry) BaseGet(id.ToString()); }
}
public ErrorLogEntry this[string id]
{
get { return this[new Guid(id)]; }
}
public void Add(ErrorLogEntry entry)
{
Debug.Assert(entry != null);
Debug.AssertStringNotEmpty(entry.Id);
Debug.Assert(this.Count <= _size);
if (this.Count == _size)
BaseRemoveAt(0);
BaseAdd(entry.Id, entry);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Qwack.Core.Basic;
using Qwack.Core.Curves;
using Qwack.Core.Models;
using Qwack.Dates;
using Qwack.Transport.BasicTypes;
namespace Qwack.Core.Instruments.Funding
{
public class IrSwap : IFundingInstrument, ISaCcrEnabledIR
{
public Dictionary<string, string> MetaData { get; set; } = new Dictionary<string, string>();
public IrSwap() { }
public IrSwap(DateTime startDate, Frequency swapTenor, FloatRateIndex rateIndex, double parRate,
SwapPayReceiveType swapType, string forecastCurve, string discountCurve)
{
SwapTenor = swapTenor;
ResetFrequency = rateIndex.ResetTenor;
StartDate = startDate;
EndDate = StartDate.AddPeriod(rateIndex.RollConvention, rateIndex.HolidayCalendars, SwapTenor);
ParRate = parRate;
BasisFloat = rateIndex.DayCountBasis;
BasisFixed = rateIndex.DayCountBasisFixed;
SwapType = swapType;
RateIndex = rateIndex;
Currency = rateIndex.Currency;
FixedLeg = new GenericSwapLeg(StartDate, swapTenor, rateIndex.HolidayCalendars, rateIndex.Currency,
ResetFrequency, BasisFixed)
{
FixedRateOrMargin = (decimal)parRate,
LegType = SwapLegType.Fixed,
Nominal = 1e6M * (swapType == SwapPayReceiveType.Payer ? -1.0M : 1.0M),
AccrualDCB = rateIndex.DayCountBasisFixed
};
FloatLeg = new GenericSwapLeg(StartDate, swapTenor, rateIndex.HolidayCalendars, rateIndex.Currency,
ResetFrequency, BasisFloat)
{
FixedRateOrMargin = 0.0M,
LegType = SwapLegType.Float,
Nominal = 1e6M * (swapType == SwapPayReceiveType.Payer ? 1.0M : -1.0M),
AccrualDCB = rateIndex.DayCountBasis
};
FlowScheduleFixed = FixedLeg.GenerateSchedule();
FlowScheduleFloat = FloatLeg.GenerateSchedule();
ResetDates = FlowScheduleFloat.Flows.Select(x => x.FixingDateStart).ToArray();
ForecastCurve = forecastCurve;
DiscountCurve = discountCurve;
}
public double Notional { get; set; }
public double ParRate { get; set; }
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
public int NDates { get; set; }
public DateTime[] ResetDates { get; set; }
public Currency Currency { get; set; }
public GenericSwapLeg FixedLeg { get; set; }
public GenericSwapLeg FloatLeg { get; set; }
public CashFlowSchedule FlowScheduleFixed { get; set; }
public CashFlowSchedule FlowScheduleFloat { get; set; }
public DayCountBasis BasisFixed { get; set; }
public DayCountBasis BasisFloat { get; set; }
public Frequency ResetFrequency { get; set; }
public Frequency SwapTenor { get; set; }
public SwapPayReceiveType SwapType { get; set; }
public string ForecastCurve { get; set; }
public string DiscountCurve { get; set; }
public string SolveCurve { get; set; }
public DateTime PillarDate { get; set; }
public string TradeId { get; set; }
public string Counterparty { get; set; }
public FloatRateIndex RateIndex { get; set; }
public string PortfolioName { get; set; }
public DateTime LastSensitivityDate => EndDate;
public List<string> Dependencies(IFxMatrix matrix) => (new[] { DiscountCurve, ForecastCurve }).Distinct().Where(x => x != SolveCurve).ToList();
public double Pv(IFundingModel model, bool updateState)
{
var updateDf = updateState || (model.CurrentSolveCurve == DiscountCurve);
var updateEst = updateState || (model.CurrentSolveCurve == ForecastCurve);
var discountCurve = model.Curves[DiscountCurve];
var forecastCurve = model.Curves[ForecastCurve];
var fixedPv = FlowScheduleFixed.PV(discountCurve, forecastCurve, updateState, updateDf, updateEst, BasisFloat, null);
var floatPv = FlowScheduleFloat.PV(discountCurve, forecastCurve, updateState, updateDf, updateEst, BasisFloat, null);
return fixedPv + floatPv;
}
//assumes zero cc rates for now
public Dictionary<string, Dictionary<DateTime, double>> Sensitivities(IFundingModel model)
{
//discounting first
var discountDict = new Dictionary<DateTime, double>();
var discountCurve = model.Curves[DiscountCurve];
foreach (var flow in FlowScheduleFloat.Flows.Union(FlowScheduleFixed.Flows))
{
var t = discountCurve.Basis.CalculateYearFraction(discountCurve.BuildDate, flow.SettleDate);
if (discountDict.ContainsKey(flow.SettleDate))
discountDict[flow.SettleDate] += -t * flow.Pv;
else
discountDict.Add(flow.SettleDate, -t * flow.Pv);
}
//then forecast
var forecastDict = (ForecastCurve == DiscountCurve) ? discountDict : new Dictionary<DateTime, double>();
var forecastCurve = model.Curves[ForecastCurve];
foreach (var flow in FlowScheduleFloat.Flows)
{
var df = flow.Fv == flow.Pv ? 1.0 : flow.Pv / flow.Fv;
var RateFloat = flow.Fv / (flow.Notional * flow.YearFraction);
var ts = discountCurve.Basis.CalculateYearFraction(discountCurve.BuildDate, flow.AccrualPeriodStart);
var te = discountCurve.Basis.CalculateYearFraction(discountCurve.BuildDate, flow.AccrualPeriodEnd);
var dPVdR = df * flow.YearFraction * flow.Notional;
var dPVdS = dPVdR * (-ts * (RateFloat + 1.0 / flow.YearFraction));
var dPVdE = dPVdR * (te * (RateFloat + 1.0 / flow.YearFraction));
if (forecastDict.ContainsKey(flow.AccrualPeriodStart))
forecastDict[flow.AccrualPeriodStart] += dPVdS;
else
forecastDict.Add(flow.AccrualPeriodStart, dPVdS);
if (forecastDict.ContainsKey(flow.AccrualPeriodEnd))
forecastDict[flow.AccrualPeriodEnd] += dPVdE;
else
forecastDict.Add(flow.AccrualPeriodEnd, dPVdE);
}
if (ForecastCurve == DiscountCurve)
return new Dictionary<string, Dictionary<DateTime, double>>()
{
{DiscountCurve,discountDict },
};
else
return new Dictionary<string, Dictionary<DateTime, double>>()
{
{DiscountCurve,discountDict },
{ForecastCurve,forecastDict },
};
}
public double CalculateParRate(IFundingModel model)
{
var dFs = FlowScheduleFloat.Flows.Select(x => x.SettleDate).Select(y => model.Curves[DiscountCurve].GetDf(model.BuildDate, y));
var floatRates = FlowScheduleFloat.Flows.Select(x => x.GetFloatRate(model.Curves[ForecastCurve], BasisFloat)).ToArray();
var parRate = dFs.Select((x, ix) => x * floatRates[ix]).Sum() / dFs.Sum();
return parRate;
}
public IFundingInstrument Clone() => new IrSwap
{
BasisFixed = BasisFixed,
BasisFloat = BasisFloat,
Currency = Currency,
Counterparty = Counterparty,
DiscountCurve = DiscountCurve,
EndDate = EndDate,
FixedLeg = FixedLeg.Clone(),
FloatLeg = FloatLeg.Clone(),
FlowScheduleFixed = FlowScheduleFixed.Clone(),
FlowScheduleFloat = FlowScheduleFloat.Clone(),
ForecastCurve = ForecastCurve,
NDates = NDates,
Notional = Notional,
ParRate = ParRate,
PillarDate = PillarDate,
ResetDates = ResetDates,
ResetFrequency = ResetFrequency,
SolveCurve = SolveCurve,
StartDate = StartDate,
SwapTenor = SwapTenor,
SwapType = SwapType,
TradeId = TradeId,
RateIndex = RateIndex,
PortfolioName = PortfolioName,
HedgingSet = HedgingSet
};
public IFundingInstrument SetParRate(double parRate) => new IrSwap(StartDate, SwapTenor, RateIndex, parRate, SwapType, ForecastCurve, DiscountCurve)
{
TradeId = TradeId,
SolveCurve = SolveCurve,
PillarDate = PillarDate,
Notional = Notional,
RateIndex = RateIndex,
PortfolioName = PortfolioName,
HedgingSet = HedgingSet
};
public double TradeNotional => System.Math.Abs(Notional);
public virtual double EffectiveNotional(IAssetFxModel model, double? MPOR = null) => SupervisoryDelta(model) * AdjustedNotional(model) * MaturityFactor(model.BuildDate, MPOR);
public double AdjustedNotional(IAssetFxModel model) => TradeNotional * SupervisoryDuration(model.BuildDate);
private double tStart(DateTime today) => today.CalculateYearFraction(StartDate, DayCountBasis.Act365F);
private double tEnd(DateTime today) => today.CalculateYearFraction(EndDate, DayCountBasis.Act365F);
public double SupervisoryDuration(DateTime today) => SaCcrUtils.SupervisoryDuration(tStart(today), tEnd(today));
public virtual double SupervisoryDelta(IAssetFxModel model) => (SwapType == SwapPayReceiveType.Pay ? 1.0 : -1.0) * System.Math.Sign(Notional);
public double MaturityFactor(DateTime today, double? MPOR = null) => MPOR.HasValue ? SaCcrUtils.MfMargined(MPOR.Value) : SaCcrUtils.MfUnmargined(tEnd(today));
public string HedgingSet { get; set; }
public int MaturityBucket(DateTime today) => tEnd(today) <= 1.0 ? 1 : tEnd(today) <= 5.0 ? 2 : 3;
public List<CashFlow> ExpectedCashFlows(IAssetFxModel model)
{
Pv(model.FundingModel, true);
return FlowScheduleFixed.Flows.Concat(FlowScheduleFloat.Flows).ToList();
}
public double SuggestPillarValue(IFundingModel model) => ParRate;
}
}
| |
//
// 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.Collections;
using System.Collections.Generic;
using Mono.Cecil;
namespace Mono.Collections.Generic {
public class Collection<T> : IList<T>, IList {
internal T [] items;
internal int size;
int version;
public int Count {
get { return size; }
}
public T this [int index] {
get {
if (index >= size)
throw new ArgumentOutOfRangeException ();
return items [index];
}
set {
CheckIndex (index);
if (index == size)
throw new ArgumentOutOfRangeException ();
OnSet (value, index);
items [index] = value;
}
}
public int Capacity {
get { return items.Length; }
set {
if (value < 0 || value < size)
throw new ArgumentOutOfRangeException ();
Resize (value);
}
}
bool ICollection<T>.IsReadOnly {
get { return false; }
}
bool IList.IsFixedSize {
get { return false; }
}
bool IList.IsReadOnly {
get { return false; }
}
object IList.this [int index] {
get { return this [index]; }
set {
CheckIndex (index);
try {
this [index] = (T) value;
return;
} catch (InvalidCastException) {
} catch (NullReferenceException) {
}
throw new ArgumentException ();
}
}
int ICollection.Count {
get { return Count; }
}
bool ICollection.IsSynchronized {
get { return false; }
}
object ICollection.SyncRoot {
get { return this; }
}
public Collection ()
{
items = Empty<T>.Array;
}
public Collection (int capacity)
{
if (capacity < 0)
throw new ArgumentOutOfRangeException ();
items = capacity == 0
? Empty<T>.Array
: new T [capacity];
}
public Collection (ICollection<T> items)
{
if (items == null)
throw new ArgumentNullException ("items");
this.items = new T [items.Count];
items.CopyTo (this.items, 0);
this.size = this.items.Length;
}
public void Add (T item)
{
if (size == items.Length)
Grow (1);
OnAdd (item, size);
items [size++] = item;
version++;
}
public bool Contains (T item)
{
return IndexOf (item) != -1;
}
public int IndexOf (T item)
{
return Array.IndexOf (items, item, 0, size);
}
public void Insert (int index, T item)
{
CheckIndex (index);
if (size == items.Length)
Grow (1);
OnInsert (item, index);
Shift (index, 1);
items [index] = item;
version++;
}
public void RemoveAt (int index)
{
if (index < 0 || index >= size)
throw new ArgumentOutOfRangeException ();
var item = items [index];
OnRemove (item, index);
Shift (index, -1);
version++;
}
public bool Remove (T item)
{
var index = IndexOf (item);
if (index == -1)
return false;
OnRemove (item, index);
Shift (index, -1);
version++;
return true;
}
public void Clear ()
{
OnClear ();
Array.Clear (items, 0, size);
size = 0;
version++;
}
public void CopyTo (T [] array, int arrayIndex)
{
Array.Copy (items, 0, array, arrayIndex, size);
}
public T [] ToArray ()
{
var array = new T [size];
Array.Copy (items, 0, array, 0, size);
return array;
}
void CheckIndex (int index)
{
if (index < 0 || index > size)
throw new ArgumentOutOfRangeException ();
}
void Shift (int start, int delta)
{
if (delta < 0)
start -= delta;
if (start < size)
Array.Copy (items, start, items, start + delta, size - start);
size += delta;
if (delta < 0)
Array.Clear (items, size, -delta);
}
protected virtual void OnAdd (T item, int index)
{
}
protected virtual void OnInsert (T item, int index)
{
}
protected virtual void OnSet (T item, int index)
{
}
protected virtual void OnRemove (T item, int index)
{
}
protected virtual void OnClear ()
{
}
internal virtual void Grow (int desired)
{
int new_size = size + desired;
if (new_size <= items.Length)
return;
const int default_capacity = 4;
new_size = System.Math.Max (
System.Math.Max (items.Length * 2, default_capacity),
new_size);
Resize (new_size);
}
protected void Resize (int new_size)
{
if (new_size == size)
return;
if (new_size < size)
throw new ArgumentOutOfRangeException ();
items = items.Resize (new_size);
}
int IList.Add (object value)
{
try {
Add ((T) value);
return size - 1;
} catch (InvalidCastException) {
} catch (NullReferenceException) {
}
throw new ArgumentException ();
}
void IList.Clear ()
{
Clear ();
}
bool IList.Contains (object value)
{
return ((IList) this).IndexOf (value) > -1;
}
int IList.IndexOf (object value)
{
try {
return IndexOf ((T) value);
} catch (InvalidCastException) {
} catch (NullReferenceException) {
}
return -1;
}
void IList.Insert (int index, object value)
{
CheckIndex (index);
try {
Insert (index, (T) value);
return;
} catch (InvalidCastException) {
} catch (NullReferenceException) {
}
throw new ArgumentException ();
}
void IList.Remove (object value)
{
try {
Remove ((T) value);
} catch (InvalidCastException) {
} catch (NullReferenceException) {
}
}
void IList.RemoveAt (int index)
{
RemoveAt (index);
}
void ICollection.CopyTo (Array array, int index)
{
Array.Copy (items, 0, array, index, size);
}
public Enumerator GetEnumerator ()
{
return new Enumerator (this);
}
IEnumerator IEnumerable.GetEnumerator ()
{
return new Enumerator (this);
}
IEnumerator<T> IEnumerable<T>.GetEnumerator ()
{
return new Enumerator (this);
}
public struct Enumerator : IEnumerator<T>, IDisposable {
Collection<T> collection;
T current;
int next;
readonly int version;
public T Current {
get { return current; }
}
object IEnumerator.Current {
get {
CheckState ();
if (next <= 0)
throw new InvalidOperationException ();
return current;
}
}
internal Enumerator (Collection<T> collection)
: this ()
{
this.collection = collection;
this.version = collection.version;
}
public bool MoveNext ()
{
CheckState ();
if (next < 0)
return false;
if (next < collection.size) {
current = collection.items [next++];
return true;
}
next = -1;
return false;
}
public void Reset ()
{
CheckState ();
next = 0;
}
void CheckState ()
{
if (collection == null)
throw new ObjectDisposedException (GetType ().FullName);
if (version != collection.version)
throw new InvalidOperationException ();
}
public void Dispose ()
{
collection = null;
}
}
}
}
| |
// $ANTLR 2.7.5 (20050128): "StrictJavaScript.g" -> "JSM_Lexer.cs"$
using antlr;
// Generate header specific to lexer CSharp file
using System;
using Stream = System.IO.Stream;
using TextReader = System.IO.TextReader;
using Hashtable = System.Collections.Hashtable;
using Comparer = System.Collections.Comparer;
using TokenStreamException = antlr.TokenStreamException;
using TokenStreamIOException = antlr.TokenStreamIOException;
using TokenStreamRecognitionException = antlr.TokenStreamRecognitionException;
using CharStreamException = antlr.CharStreamException;
using CharStreamIOException = antlr.CharStreamIOException;
using ANTLRException = antlr.ANTLRException;
using CharScanner = antlr.CharScanner;
using InputBuffer = antlr.InputBuffer;
using ByteBuffer = antlr.ByteBuffer;
using CharBuffer = antlr.CharBuffer;
using Token = antlr.Token;
using IToken = antlr.IToken;
using CommonToken = antlr.CommonToken;
using SemanticException = antlr.SemanticException;
using RecognitionException = antlr.RecognitionException;
using NoViableAltForCharException = antlr.NoViableAltForCharException;
using MismatchedCharException = antlr.MismatchedCharException;
using TokenStream = antlr.TokenStream;
using LexerSharedInputState = antlr.LexerSharedInputState;
using BitSet = antlr.collections.impl.BitSet;
public class JSM_Lexer : antlr.CharScanner , TokenStream
{
public const int EOF = 1;
public const int NULL_TREE_LOOKAHEAD = 3;
public const int JS = 4;
public const int VAL_INTEGER = 5;
public const int VAL_REAL = 6;
public const int VAL_STRING = 7;
public const int VAL_STRING2 = 8;
public const int VAL_REGEX = 9;
public const int ARGS = 10;
public const int VAR = 11;
public const int LOOKUP = 12;
public const int BLOCK = 13;
public const int ASS = 14;
public const int INLINE_OBJECT = 15;
public const int INLINE_ARRAY = 16;
public const int ANONY_FUNC = 17;
public const int FUN_APP = 18;
public const int OPP = 19;
public const int CALL = 20;
public const int ACCESS = 21;
public const int FIELD = 22;
public const int METHOD = 23;
public const int PARENTHESIS = 24;
public const int NULL_NODE = 25;
public const int GOOD_INIT = 26;
public const int GOOD_COND = 27;
public const int GOOD_INCR = 28;
public const int LITERAL_null = 29;
public const int LITERAL_false = 30;
public const int LITERAL_true = 31;
public const int LITERAL_this = 32;
public const int ICON = 33;
public const int DOT = 34;
public const int HEXCON = 35;
public const int STCON = 36;
public const int STCON2 = 37;
public const int IDENT = 38;
public const int COLON = 39;
public const int LCURL = 40;
public const int COMMA = 41;
public const int RCURL = 42;
public const int LBRACKET = 43;
public const int RBRACKET = 44;
public const int LITERAL_function = 45;
public const int LITERAL_new = 46;
public const int LPAREN = 47;
public const int RPAREN = 48;
// "=" = 49
// "|=" = 50
// "&=" = 51
// "||=" = 52
// "&&=" = 53
// "+=" = 54
// "-=" = 55
// "*=" = 56
// "/=" = 57
// "%=" = 58
// "++" = 59
// "--" = 60
// "!" = 61
public const int MINUS = 62;
// "~" = 63
public const int TIMES = 64;
// "/" = 65
public const int MOD = 66;
public const int PLUS = 67;
// ">>" = 68
// "<<" = 69
// ">>>" = 70
public const int LITERAL_typeof = 71;
public const int EQ = 72;
public const int NEQ = 73;
public const int LTHAN = 74;
public const int GTHAN = 75;
public const int GEQ = 76;
public const int LEQ = 77;
// "&&" = 78
// "||" = 79
// "&" = 80
// "|" = 81
// "^" = 82
// "?" = 83
public const int LITERAL_else = 84;
public const int LITERAL_if = 85;
public const int LITERAL_while = 86;
public const int LITERAL_for = 87;
public const int SEMICOLON = 88;
public const int LITERAL_return = 89;
public const int LITERAL_throw = 90;
public const int LITERAL_delete = 91;
public const int LITERAL_var = 92;
public const int LITERAL_catch = 93;
public const int LITERAL_try = 94;
public const int WS_ = 95;
public const int ESC = 96;
public const int DIVISON_OPS = 97;
public const int PLUSPLUS = 98;
public const int MINUSMINUS = 99;
public const int AMP = 100;
public const int ASSIGN = 101;
public const int ASSIGN_PLUS = 102;
public const int ASSIGN_MINUS = 103;
public const int ASSIGN_TIMES = 104;
public const int ASSIGN_MOD = 105;
public const int POWER = 106;
public const int SHIFT_LEFT = 107;
public const int SHIFT_RIGHT = 108;
public const int LOGIC_AND = 109;
public const int BIT_OR_ASS = 110;
public const int BIT_AND_ASS = 111;
public const int LOGIC_OR = 112;
public const int BITWISE_OR = 113;
public const int BITWISE_NOT = 114;
public const int LOGIC_NOT = 115;
public const int LOGIC_QUEST = 116;
public JSM_Lexer(Stream ins) : this(new ByteBuffer(ins))
{
}
public JSM_Lexer(TextReader r) : this(new CharBuffer(r))
{
}
public JSM_Lexer(InputBuffer ib) : this(new LexerSharedInputState(ib))
{
}
public JSM_Lexer(LexerSharedInputState state) : base(state)
{
initialize();
}
private void initialize()
{
caseSensitiveLiterals = true;
setCaseSensitive(true);
literals = new Hashtable(100, (float) 0.4, null, Comparer.Default);
literals.Add(">>>", 70);
literals.Add("this", 32);
literals.Add("<<", 69);
literals.Add("for", 87);
literals.Add("/", 65);
literals.Add("false", 30);
literals.Add("true", 31);
literals.Add("try", 94);
literals.Add("~", 63);
literals.Add("typeof", 71);
literals.Add("&&=", 53);
literals.Add("/=", 57);
literals.Add("&&", 78);
literals.Add("++", 59);
literals.Add("!", 61);
literals.Add("-=", 55);
literals.Add("throw", 90);
literals.Add("+=", 54);
literals.Add("*=", 56);
literals.Add("^", 82);
literals.Add("?", 83);
literals.Add("null", 29);
literals.Add("&", 80);
literals.Add("function", 45);
literals.Add("&=", 51);
literals.Add("|", 81);
literals.Add("%=", 58);
literals.Add("||", 79);
literals.Add("while", 86);
literals.Add(">>", 68);
literals.Add("new", 46);
literals.Add("return", 89);
literals.Add("delete", 91);
literals.Add("=", 49);
literals.Add("if", 85);
literals.Add("||=", 52);
literals.Add("|=", 50);
literals.Add("else", 84);
literals.Add("var", 92);
literals.Add("catch", 93);
literals.Add("--", 60);
}
override public IToken nextToken() //throws TokenStreamException
{
IToken theRetToken = null;
tryAgain:
for (;;)
{
IToken _token = null;
int _ttype = Token.INVALID_TYPE;
resetText();
try // for char stream error handling
{
try // for lexical error handling
{
switch ( cached_LA1 )
{
case '\t': case '\n': case '\r': case ' ':
{
mWS_(true);
theRetToken = returnToken_;
break;
}
case 'A': case 'B': case 'C': case 'D':
case 'E': case 'F': case 'G': case 'H':
case 'I': case 'J': case 'K': case 'L':
case 'M': case 'N': case 'O': case 'P':
case 'Q': case 'R': case 'S': case 'T':
case 'U': case 'V': case 'W': case 'X':
case 'Y': case 'Z': case '_': case 'a':
case 'b': case 'c': case 'd': case 'e':
case 'f': case 'g': case 'h': case 'i':
case 'j': case 'k': case 'l': case 'm':
case 'n': case 'o': case 'p': case 'q':
case 'r': case 's': case 't': case 'u':
case 'v': case 'w': case 'x': case 'y':
case 'z':
{
mIDENT(true);
theRetToken = returnToken_;
break;
}
case '\\':
{
mESC(true);
theRetToken = returnToken_;
break;
}
case '/':
{
mDIVISON_OPS(true);
theRetToken = returnToken_;
break;
}
case '"':
{
mSTCON(true);
theRetToken = returnToken_;
break;
}
case '\'':
{
mSTCON2(true);
theRetToken = returnToken_;
break;
}
case ',':
{
mCOMMA(true);
theRetToken = returnToken_;
break;
}
case ';':
{
mSEMICOLON(true);
theRetToken = returnToken_;
break;
}
case ':':
{
mCOLON(true);
theRetToken = returnToken_;
break;
}
case '(':
{
mLPAREN(true);
theRetToken = returnToken_;
break;
}
case '[':
{
mLBRACKET(true);
theRetToken = returnToken_;
break;
}
case ']':
{
mRBRACKET(true);
theRetToken = returnToken_;
break;
}
case ')':
{
mRPAREN(true);
theRetToken = returnToken_;
break;
}
case '{':
{
mLCURL(true);
theRetToken = returnToken_;
break;
}
case '}':
{
mRCURL(true);
theRetToken = returnToken_;
break;
}
case '.':
{
mDOT(true);
theRetToken = returnToken_;
break;
}
case '^':
{
mPOWER(true);
theRetToken = returnToken_;
break;
}
case '~':
{
mBITWISE_NOT(true);
theRetToken = returnToken_;
break;
}
case '?':
{
mLOGIC_QUEST(true);
theRetToken = returnToken_;
break;
}
default:
if ((cached_LA1=='0') && (cached_LA2=='x'))
{
mHEXCON(true);
theRetToken = returnToken_;
}
else if ((cached_LA1=='+') && (cached_LA2=='+')) {
mPLUSPLUS(true);
theRetToken = returnToken_;
}
else if ((cached_LA1=='-') && (cached_LA2=='-')) {
mMINUSMINUS(true);
theRetToken = returnToken_;
}
else if ((cached_LA1=='+') && (cached_LA2=='=')) {
mASSIGN_PLUS(true);
theRetToken = returnToken_;
}
else if ((cached_LA1=='-') && (cached_LA2=='=')) {
mASSIGN_MINUS(true);
theRetToken = returnToken_;
}
else if ((cached_LA1=='*') && (cached_LA2=='=')) {
mASSIGN_TIMES(true);
theRetToken = returnToken_;
}
else if ((cached_LA1=='%') && (cached_LA2=='=')) {
mASSIGN_MOD(true);
theRetToken = returnToken_;
}
else if ((cached_LA1=='=') && (cached_LA2=='=')) {
mEQ(true);
theRetToken = returnToken_;
}
else if ((cached_LA1=='!') && (cached_LA2=='=')) {
mNEQ(true);
theRetToken = returnToken_;
}
else if ((cached_LA1=='<') && (cached_LA2=='=')) {
mLEQ(true);
theRetToken = returnToken_;
}
else if ((cached_LA1=='>') && (cached_LA2=='=')) {
mGEQ(true);
theRetToken = returnToken_;
}
else if ((cached_LA1=='<') && (cached_LA2=='<')) {
mSHIFT_LEFT(true);
theRetToken = returnToken_;
}
else if ((cached_LA1=='>') && (cached_LA2=='>')) {
mSHIFT_RIGHT(true);
theRetToken = returnToken_;
}
else if ((cached_LA1=='&') && (cached_LA2=='&')) {
mLOGIC_AND(true);
theRetToken = returnToken_;
}
else if ((cached_LA1=='|') && (cached_LA2=='=')) {
mBIT_OR_ASS(true);
theRetToken = returnToken_;
}
else if ((cached_LA1=='&') && (cached_LA2=='=')) {
mBIT_AND_ASS(true);
theRetToken = returnToken_;
}
else if ((cached_LA1=='|') && (cached_LA2=='|')) {
mLOGIC_OR(true);
theRetToken = returnToken_;
}
else if (((cached_LA1 >= '0' && cached_LA1 <= '9')) && (true)) {
mICON(true);
theRetToken = returnToken_;
}
else if ((cached_LA1=='+') && (true)) {
mPLUS(true);
theRetToken = returnToken_;
}
else if ((cached_LA1=='-') && (true)) {
mMINUS(true);
theRetToken = returnToken_;
}
else if ((cached_LA1=='*') && (true)) {
mTIMES(true);
theRetToken = returnToken_;
}
else if ((cached_LA1=='&') && (true)) {
mAMP(true);
theRetToken = returnToken_;
}
else if ((cached_LA1=='=') && (true)) {
mASSIGN(true);
theRetToken = returnToken_;
}
else if ((cached_LA1=='%') && (true)) {
mMOD(true);
theRetToken = returnToken_;
}
else if ((cached_LA1=='<') && (true)) {
mLTHAN(true);
theRetToken = returnToken_;
}
else if ((cached_LA1=='>') && (true)) {
mGTHAN(true);
theRetToken = returnToken_;
}
else if ((cached_LA1=='|') && (true)) {
mBITWISE_OR(true);
theRetToken = returnToken_;
}
else if ((cached_LA1=='!') && (true)) {
mLOGIC_NOT(true);
theRetToken = returnToken_;
}
else
{
if (cached_LA1==EOF_CHAR) { uponEOF(); returnToken_ = makeToken(Token.EOF_TYPE); }
else {throw new NoViableAltForCharException(cached_LA1, getFilename(), getLine(), getColumn());}
}
break; }
if ( null==returnToken_ ) goto tryAgain; // found SKIP token
_ttype = returnToken_.Type;
_ttype = testLiteralsTable(_ttype);
returnToken_.Type = _ttype;
return returnToken_;
}
catch (RecognitionException e) {
throw new TokenStreamRecognitionException(e);
}
}
catch (CharStreamException cse) {
if ( cse is CharStreamIOException ) {
throw new TokenStreamIOException(((CharStreamIOException)cse).io);
}
else {
throw new TokenStreamException(cse.Message);
}
}
}
}
public void mWS_(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException
{
int _ttype; IToken _token=null; int _begin=text.Length;
_ttype = WS_;
{
switch ( cached_LA1 )
{
case ' ':
{
match(' ');
break;
}
case '\t':
{
match('\t');
break;
}
case '\n':
{
match('\n');
if (0==inputState.guessing)
{
newline();
}
break;
}
case '\r':
{
match('\r');
break;
}
default:
{
throw new NoViableAltForCharException(cached_LA1, getFilename(), getLine(), getColumn());
}
}
}
if (0==inputState.guessing)
{
_ttype = Token.SKIP;
}
if (_createToken && (null == _token) && (_ttype != Token.SKIP))
{
_token = makeToken(_ttype);
_token.setText(text.ToString(_begin, text.Length-_begin));
}
returnToken_ = _token;
}
public void mIDENT(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException
{
int _ttype; IToken _token=null; int _begin=text.Length;
_ttype = IDENT;
{
{
switch ( cached_LA1 )
{
case 'a': case 'b': case 'c': case 'd':
case 'e': case 'f': case 'g': case 'h':
case 'i': case 'j': case 'k': case 'l':
case 'm': case 'n': case 'o': case 'p':
case 'q': case 'r': case 's': case 't':
case 'u': case 'v': case 'w': case 'x':
case 'y': case 'z':
{
matchRange('a','z');
break;
}
case 'A': case 'B': case 'C': case 'D':
case 'E': case 'F': case 'G': case 'H':
case 'I': case 'J': case 'K': case 'L':
case 'M': case 'N': case 'O': case 'P':
case 'Q': case 'R': case 'S': case 'T':
case 'U': case 'V': case 'W': case 'X':
case 'Y': case 'Z':
{
matchRange('A','Z');
break;
}
case '_':
{
match('_');
break;
}
default:
{
throw new NoViableAltForCharException(cached_LA1, getFilename(), getLine(), getColumn());
}
}
}
{ // ( ... )*
for (;;)
{
switch ( cached_LA1 )
{
case 'A': case 'B': case 'C': case 'D':
case 'E': case 'F': case 'G': case 'H':
case 'I': case 'J': case 'K': case 'L':
case 'M': case 'N': case 'O': case 'P':
case 'Q': case 'R': case 'S': case 'T':
case 'U': case 'V': case 'W': case 'X':
case 'Y': case 'Z': case '_': case 'a':
case 'b': case 'c': case 'd': case 'e':
case 'f': case 'g': case 'h': case 'i':
case 'j': case 'k': case 'l': case 'm':
case 'n': case 'o': case 'p': case 'q':
case 'r': case 's': case 't': case 'u':
case 'v': case 'w': case 'x': case 'y':
case 'z':
{
{
switch ( cached_LA1 )
{
case 'a': case 'b': case 'c': case 'd':
case 'e': case 'f': case 'g': case 'h':
case 'i': case 'j': case 'k': case 'l':
case 'm': case 'n': case 'o': case 'p':
case 'q': case 'r': case 's': case 't':
case 'u': case 'v': case 'w': case 'x':
case 'y': case 'z':
{
matchRange('a','z');
break;
}
case 'A': case 'B': case 'C': case 'D':
case 'E': case 'F': case 'G': case 'H':
case 'I': case 'J': case 'K': case 'L':
case 'M': case 'N': case 'O': case 'P':
case 'Q': case 'R': case 'S': case 'T':
case 'U': case 'V': case 'W': case 'X':
case 'Y': case 'Z':
{
matchRange('A','Z');
break;
}
case '_':
{
match('_');
break;
}
default:
{
throw new NoViableAltForCharException(cached_LA1, getFilename(), getLine(), getColumn());
}
}
}
break;
}
case '0': case '1': case '2': case '3':
case '4': case '5': case '6': case '7':
case '8': case '9':
{
{
matchRange('0','9');
}
break;
}
default:
{
goto _loop153_breakloop;
}
}
}
_loop153_breakloop: ;
} // ( ... )*
}
if (_createToken && (null == _token) && (_ttype != Token.SKIP))
{
_token = makeToken(_ttype);
_token.setText(text.ToString(_begin, text.Length-_begin));
}
returnToken_ = _token;
}
public void mICON(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException
{
int _ttype; IToken _token=null; int _begin=text.Length;
_ttype = ICON;
matchRange('0','9');
{ // ( ... )*
for (;;)
{
if (((cached_LA1 >= '0' && cached_LA1 <= '9')))
{
matchRange('0','9');
}
else
{
goto _loop156_breakloop;
}
}
_loop156_breakloop: ;
} // ( ... )*
if (_createToken && (null == _token) && (_ttype != Token.SKIP))
{
_token = makeToken(_ttype);
_token.setText(text.ToString(_begin, text.Length-_begin));
}
returnToken_ = _token;
}
public void mESC(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException
{
int _ttype; IToken _token=null; int _begin=text.Length;
_ttype = ESC;
match('\\');
{
switch ( cached_LA1 )
{
case 'n':
{
match('n');
break;
}
case 'r':
{
match('r');
break;
}
case 't':
{
match('t');
break;
}
case 'b':
{
match('b');
break;
}
case 'f':
{
match('f');
break;
}
case '\\':
{
match('\\');
break;
}
default:
{
throw new NoViableAltForCharException(cached_LA1, getFilename(), getLine(), getColumn());
}
}
}
if (_createToken && (null == _token) && (_ttype != Token.SKIP))
{
_token = makeToken(_ttype);
_token.setText(text.ToString(_begin, text.Length-_begin));
}
returnToken_ = _token;
}
public void mHEXCON(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException
{
int _ttype; IToken _token=null; int _begin=text.Length;
_ttype = HEXCON;
match('0');
match('x');
{ // ( ... )*
for (;;)
{
switch ( cached_LA1 )
{
case '0': case '1': case '2': case '3':
case '4': case '5': case '6': case '7':
case '8': case '9':
{
matchRange('0','9');
break;
}
case 'a':
{
match('a');
break;
}
case 'b':
{
match('b');
break;
}
case 'c':
{
match('c');
break;
}
case 'd':
{
match('d');
break;
}
case 'e':
{
match('e');
break;
}
case 'f':
{
match('f');
break;
}
case 'A':
{
match('A');
break;
}
case 'B':
{
match('B');
break;
}
case 'C':
{
match('C');
break;
}
case 'D':
{
match('D');
break;
}
case 'E':
{
match('E');
break;
}
case 'F':
{
match('F');
break;
}
default:
{
goto _loop161_breakloop;
}
}
}
_loop161_breakloop: ;
} // ( ... )*
if (_createToken && (null == _token) && (_ttype != Token.SKIP))
{
_token = makeToken(_ttype);
_token.setText(text.ToString(_begin, text.Length-_begin));
}
returnToken_ = _token;
}
public void mDIVISON_OPS(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException
{
int _ttype; IToken _token=null; int _begin=text.Length;
_ttype = DIVISON_OPS;
if ((cached_LA1=='/') && (cached_LA2=='='))
{
match("/=");
}
else if ((cached_LA1=='/') && (true)) {
match('/');
}
else
{
throw new NoViableAltForCharException(cached_LA1, getFilename(), getLine(), getColumn());
}
if (_createToken && (null == _token) && (_ttype != Token.SKIP))
{
_token = makeToken(_ttype);
_token.setText(text.ToString(_begin, text.Length-_begin));
}
returnToken_ = _token;
}
public void mSTCON(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException
{
int _ttype; IToken _token=null; int _begin=text.Length;
_ttype = STCON;
match('"');
{ // ( ... )*
for (;;)
{
if ((cached_LA1=='\\') && (tokenSet_0_.member(cached_LA2)))
{
mESC(false);
}
else if ((cached_LA1=='\\') && (cached_LA2=='"')) {
match('\\');
match('\"');
}
else if ((tokenSet_1_.member(cached_LA1))) {
matchNot('"');
}
else
{
goto _loop165_breakloop;
}
}
_loop165_breakloop: ;
} // ( ... )*
match('"');
if (_createToken && (null == _token) && (_ttype != Token.SKIP))
{
_token = makeToken(_ttype);
_token.setText(text.ToString(_begin, text.Length-_begin));
}
returnToken_ = _token;
}
public void mSTCON2(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException
{
int _ttype; IToken _token=null; int _begin=text.Length;
_ttype = STCON2;
match("'");
{ // ( ... )*
for (;;)
{
if ((cached_LA1=='\\') && (tokenSet_0_.member(cached_LA2)))
{
mESC(false);
}
else if ((cached_LA1=='\\') && (cached_LA2=='\'')) {
match('\\');
match('\'');
}
else if ((tokenSet_2_.member(cached_LA1))) {
matchNot('\'');
}
else
{
goto _loop168_breakloop;
}
}
_loop168_breakloop: ;
} // ( ... )*
match("'");
if (_createToken && (null == _token) && (_ttype != Token.SKIP))
{
_token = makeToken(_ttype);
_token.setText(text.ToString(_begin, text.Length-_begin));
}
returnToken_ = _token;
}
public void mCOMMA(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException
{
int _ttype; IToken _token=null; int _begin=text.Length;
_ttype = COMMA;
match(',');
if (_createToken && (null == _token) && (_ttype != Token.SKIP))
{
_token = makeToken(_ttype);
_token.setText(text.ToString(_begin, text.Length-_begin));
}
returnToken_ = _token;
}
public void mSEMICOLON(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException
{
int _ttype; IToken _token=null; int _begin=text.Length;
_ttype = SEMICOLON;
match(';');
if (_createToken && (null == _token) && (_ttype != Token.SKIP))
{
_token = makeToken(_ttype);
_token.setText(text.ToString(_begin, text.Length-_begin));
}
returnToken_ = _token;
}
public void mCOLON(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException
{
int _ttype; IToken _token=null; int _begin=text.Length;
_ttype = COLON;
match(':');
if (_createToken && (null == _token) && (_ttype != Token.SKIP))
{
_token = makeToken(_ttype);
_token.setText(text.ToString(_begin, text.Length-_begin));
}
returnToken_ = _token;
}
public void mLPAREN(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException
{
int _ttype; IToken _token=null; int _begin=text.Length;
_ttype = LPAREN;
match('(');
if (_createToken && (null == _token) && (_ttype != Token.SKIP))
{
_token = makeToken(_ttype);
_token.setText(text.ToString(_begin, text.Length-_begin));
}
returnToken_ = _token;
}
public void mLBRACKET(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException
{
int _ttype; IToken _token=null; int _begin=text.Length;
_ttype = LBRACKET;
match('[');
if (_createToken && (null == _token) && (_ttype != Token.SKIP))
{
_token = makeToken(_ttype);
_token.setText(text.ToString(_begin, text.Length-_begin));
}
returnToken_ = _token;
}
public void mRBRACKET(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException
{
int _ttype; IToken _token=null; int _begin=text.Length;
_ttype = RBRACKET;
match(']');
if (_createToken && (null == _token) && (_ttype != Token.SKIP))
{
_token = makeToken(_ttype);
_token.setText(text.ToString(_begin, text.Length-_begin));
}
returnToken_ = _token;
}
public void mRPAREN(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException
{
int _ttype; IToken _token=null; int _begin=text.Length;
_ttype = RPAREN;
match(')');
if (_createToken && (null == _token) && (_ttype != Token.SKIP))
{
_token = makeToken(_ttype);
_token.setText(text.ToString(_begin, text.Length-_begin));
}
returnToken_ = _token;
}
public void mLCURL(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException
{
int _ttype; IToken _token=null; int _begin=text.Length;
_ttype = LCURL;
match('{');
if (_createToken && (null == _token) && (_ttype != Token.SKIP))
{
_token = makeToken(_ttype);
_token.setText(text.ToString(_begin, text.Length-_begin));
}
returnToken_ = _token;
}
public void mRCURL(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException
{
int _ttype; IToken _token=null; int _begin=text.Length;
_ttype = RCURL;
match('}');
if (_createToken && (null == _token) && (_ttype != Token.SKIP))
{
_token = makeToken(_ttype);
_token.setText(text.ToString(_begin, text.Length-_begin));
}
returnToken_ = _token;
}
public void mPLUS(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException
{
int _ttype; IToken _token=null; int _begin=text.Length;
_ttype = PLUS;
match('+');
if (_createToken && (null == _token) && (_ttype != Token.SKIP))
{
_token = makeToken(_ttype);
_token.setText(text.ToString(_begin, text.Length-_begin));
}
returnToken_ = _token;
}
public void mPLUSPLUS(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException
{
int _ttype; IToken _token=null; int _begin=text.Length;
_ttype = PLUSPLUS;
match("++");
if (_createToken && (null == _token) && (_ttype != Token.SKIP))
{
_token = makeToken(_ttype);
_token.setText(text.ToString(_begin, text.Length-_begin));
}
returnToken_ = _token;
}
public void mMINUSMINUS(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException
{
int _ttype; IToken _token=null; int _begin=text.Length;
_ttype = MINUSMINUS;
match("--");
if (_createToken && (null == _token) && (_ttype != Token.SKIP))
{
_token = makeToken(_ttype);
_token.setText(text.ToString(_begin, text.Length-_begin));
}
returnToken_ = _token;
}
public void mMINUS(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException
{
int _ttype; IToken _token=null; int _begin=text.Length;
_ttype = MINUS;
match('-');
if (_createToken && (null == _token) && (_ttype != Token.SKIP))
{
_token = makeToken(_ttype);
_token.setText(text.ToString(_begin, text.Length-_begin));
}
returnToken_ = _token;
}
public void mTIMES(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException
{
int _ttype; IToken _token=null; int _begin=text.Length;
_ttype = TIMES;
match('*');
if (_createToken && (null == _token) && (_ttype != Token.SKIP))
{
_token = makeToken(_ttype);
_token.setText(text.ToString(_begin, text.Length-_begin));
}
returnToken_ = _token;
}
public void mAMP(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException
{
int _ttype; IToken _token=null; int _begin=text.Length;
_ttype = AMP;
match('&');
if (_createToken && (null == _token) && (_ttype != Token.SKIP))
{
_token = makeToken(_ttype);
_token.setText(text.ToString(_begin, text.Length-_begin));
}
returnToken_ = _token;
}
public void mDOT(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException
{
int _ttype; IToken _token=null; int _begin=text.Length;
_ttype = DOT;
match('.');
if (_createToken && (null == _token) && (_ttype != Token.SKIP))
{
_token = makeToken(_ttype);
_token.setText(text.ToString(_begin, text.Length-_begin));
}
returnToken_ = _token;
}
public void mASSIGN(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException
{
int _ttype; IToken _token=null; int _begin=text.Length;
_ttype = ASSIGN;
match('=');
if (_createToken && (null == _token) && (_ttype != Token.SKIP))
{
_token = makeToken(_ttype);
_token.setText(text.ToString(_begin, text.Length-_begin));
}
returnToken_ = _token;
}
public void mASSIGN_PLUS(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException
{
int _ttype; IToken _token=null; int _begin=text.Length;
_ttype = ASSIGN_PLUS;
match("+=");
if (_createToken && (null == _token) && (_ttype != Token.SKIP))
{
_token = makeToken(_ttype);
_token.setText(text.ToString(_begin, text.Length-_begin));
}
returnToken_ = _token;
}
public void mASSIGN_MINUS(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException
{
int _ttype; IToken _token=null; int _begin=text.Length;
_ttype = ASSIGN_MINUS;
match("-=");
if (_createToken && (null == _token) && (_ttype != Token.SKIP))
{
_token = makeToken(_ttype);
_token.setText(text.ToString(_begin, text.Length-_begin));
}
returnToken_ = _token;
}
public void mASSIGN_TIMES(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException
{
int _ttype; IToken _token=null; int _begin=text.Length;
_ttype = ASSIGN_TIMES;
match("*=");
if (_createToken && (null == _token) && (_ttype != Token.SKIP))
{
_token = makeToken(_ttype);
_token.setText(text.ToString(_begin, text.Length-_begin));
}
returnToken_ = _token;
}
public void mASSIGN_MOD(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException
{
int _ttype; IToken _token=null; int _begin=text.Length;
_ttype = ASSIGN_MOD;
match("%=");
if (_createToken && (null == _token) && (_ttype != Token.SKIP))
{
_token = makeToken(_ttype);
_token.setText(text.ToString(_begin, text.Length-_begin));
}
returnToken_ = _token;
}
public void mMOD(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException
{
int _ttype; IToken _token=null; int _begin=text.Length;
_ttype = MOD;
match('%');
if (_createToken && (null == _token) && (_ttype != Token.SKIP))
{
_token = makeToken(_ttype);
_token.setText(text.ToString(_begin, text.Length-_begin));
}
returnToken_ = _token;
}
public void mPOWER(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException
{
int _ttype; IToken _token=null; int _begin=text.Length;
_ttype = POWER;
match('^');
if (_createToken && (null == _token) && (_ttype != Token.SKIP))
{
_token = makeToken(_ttype);
_token.setText(text.ToString(_begin, text.Length-_begin));
}
returnToken_ = _token;
}
public void mEQ(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException
{
int _ttype; IToken _token=null; int _begin=text.Length;
_ttype = EQ;
bool synPredMatched194 = false;
if (((cached_LA1=='=') && (cached_LA2=='=')))
{
int _m194 = mark();
synPredMatched194 = true;
inputState.guessing++;
try {
{
match("===");
}
}
catch (RecognitionException)
{
synPredMatched194 = false;
}
rewind(_m194);
inputState.guessing--;
}
if ( synPredMatched194 )
{
match("===");
}
else if ((cached_LA1=='=') && (cached_LA2=='=')) {
match("==");
}
else
{
throw new NoViableAltForCharException(cached_LA1, getFilename(), getLine(), getColumn());
}
if (_createToken && (null == _token) && (_ttype != Token.SKIP))
{
_token = makeToken(_ttype);
_token.setText(text.ToString(_begin, text.Length-_begin));
}
returnToken_ = _token;
}
public void mNEQ(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException
{
int _ttype; IToken _token=null; int _begin=text.Length;
_ttype = NEQ;
match("!=");
if (_createToken && (null == _token) && (_ttype != Token.SKIP))
{
_token = makeToken(_ttype);
_token.setText(text.ToString(_begin, text.Length-_begin));
}
returnToken_ = _token;
}
public void mLTHAN(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException
{
int _ttype; IToken _token=null; int _begin=text.Length;
_ttype = LTHAN;
match('<');
if (_createToken && (null == _token) && (_ttype != Token.SKIP))
{
_token = makeToken(_ttype);
_token.setText(text.ToString(_begin, text.Length-_begin));
}
returnToken_ = _token;
}
public void mGTHAN(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException
{
int _ttype; IToken _token=null; int _begin=text.Length;
_ttype = GTHAN;
match('>');
if (_createToken && (null == _token) && (_ttype != Token.SKIP))
{
_token = makeToken(_ttype);
_token.setText(text.ToString(_begin, text.Length-_begin));
}
returnToken_ = _token;
}
public void mLEQ(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException
{
int _ttype; IToken _token=null; int _begin=text.Length;
_ttype = LEQ;
match("<=");
if (_createToken && (null == _token) && (_ttype != Token.SKIP))
{
_token = makeToken(_ttype);
_token.setText(text.ToString(_begin, text.Length-_begin));
}
returnToken_ = _token;
}
public void mGEQ(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException
{
int _ttype; IToken _token=null; int _begin=text.Length;
_ttype = GEQ;
match(">=");
if (_createToken && (null == _token) && (_ttype != Token.SKIP))
{
_token = makeToken(_ttype);
_token.setText(text.ToString(_begin, text.Length-_begin));
}
returnToken_ = _token;
}
public void mSHIFT_LEFT(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException
{
int _ttype; IToken _token=null; int _begin=text.Length;
_ttype = SHIFT_LEFT;
match("<<");
if (_createToken && (null == _token) && (_ttype != Token.SKIP))
{
_token = makeToken(_ttype);
_token.setText(text.ToString(_begin, text.Length-_begin));
}
returnToken_ = _token;
}
public void mSHIFT_RIGHT(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException
{
int _ttype; IToken _token=null; int _begin=text.Length;
_ttype = SHIFT_RIGHT;
bool synPredMatched203 = false;
if (((cached_LA1=='>') && (cached_LA2=='>')))
{
int _m203 = mark();
synPredMatched203 = true;
inputState.guessing++;
try {
{
match(">>>");
}
}
catch (RecognitionException)
{
synPredMatched203 = false;
}
rewind(_m203);
inputState.guessing--;
}
if ( synPredMatched203 )
{
match(">>>");
}
else if ((cached_LA1=='>') && (cached_LA2=='>')) {
match(">>");
}
else
{
throw new NoViableAltForCharException(cached_LA1, getFilename(), getLine(), getColumn());
}
if (_createToken && (null == _token) && (_ttype != Token.SKIP))
{
_token = makeToken(_ttype);
_token.setText(text.ToString(_begin, text.Length-_begin));
}
returnToken_ = _token;
}
public void mLOGIC_AND(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException
{
int _ttype; IToken _token=null; int _begin=text.Length;
_ttype = LOGIC_AND;
match("&&");
if (_createToken && (null == _token) && (_ttype != Token.SKIP))
{
_token = makeToken(_ttype);
_token.setText(text.ToString(_begin, text.Length-_begin));
}
returnToken_ = _token;
}
public void mBIT_OR_ASS(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException
{
int _ttype; IToken _token=null; int _begin=text.Length;
_ttype = BIT_OR_ASS;
match("|=");
if (_createToken && (null == _token) && (_ttype != Token.SKIP))
{
_token = makeToken(_ttype);
_token.setText(text.ToString(_begin, text.Length-_begin));
}
returnToken_ = _token;
}
public void mBIT_AND_ASS(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException
{
int _ttype; IToken _token=null; int _begin=text.Length;
_ttype = BIT_AND_ASS;
match("&=");
if (_createToken && (null == _token) && (_ttype != Token.SKIP))
{
_token = makeToken(_ttype);
_token.setText(text.ToString(_begin, text.Length-_begin));
}
returnToken_ = _token;
}
public void mLOGIC_OR(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException
{
int _ttype; IToken _token=null; int _begin=text.Length;
_ttype = LOGIC_OR;
match("||");
if (_createToken && (null == _token) && (_ttype != Token.SKIP))
{
_token = makeToken(_ttype);
_token.setText(text.ToString(_begin, text.Length-_begin));
}
returnToken_ = _token;
}
public void mBITWISE_OR(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException
{
int _ttype; IToken _token=null; int _begin=text.Length;
_ttype = BITWISE_OR;
match("|");
if (_createToken && (null == _token) && (_ttype != Token.SKIP))
{
_token = makeToken(_ttype);
_token.setText(text.ToString(_begin, text.Length-_begin));
}
returnToken_ = _token;
}
public void mBITWISE_NOT(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException
{
int _ttype; IToken _token=null; int _begin=text.Length;
_ttype = BITWISE_NOT;
match("~");
if (_createToken && (null == _token) && (_ttype != Token.SKIP))
{
_token = makeToken(_ttype);
_token.setText(text.ToString(_begin, text.Length-_begin));
}
returnToken_ = _token;
}
public void mLOGIC_NOT(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException
{
int _ttype; IToken _token=null; int _begin=text.Length;
_ttype = LOGIC_NOT;
match("!");
if (_createToken && (null == _token) && (_ttype != Token.SKIP))
{
_token = makeToken(_ttype);
_token.setText(text.ToString(_begin, text.Length-_begin));
}
returnToken_ = _token;
}
public void mLOGIC_QUEST(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException
{
int _ttype; IToken _token=null; int _begin=text.Length;
_ttype = LOGIC_QUEST;
match("?");
if (_createToken && (null == _token) && (_ttype != Token.SKIP))
{
_token = makeToken(_ttype);
_token.setText(text.ToString(_begin, text.Length-_begin));
}
returnToken_ = _token;
}
private static long[] mk_tokenSet_0_()
{
long[] data = { 0L, 5700160604602368L, 0L, 0L};
return data;
}
public static readonly BitSet tokenSet_0_ = new BitSet(mk_tokenSet_0_());
private static long[] mk_tokenSet_1_()
{
long[] data = { -17179869185L, -268435457L, 0L, 0L};
return data;
}
public static readonly BitSet tokenSet_1_ = new BitSet(mk_tokenSet_1_());
private static long[] mk_tokenSet_2_()
{
long[] data = { -549755813889L, -268435457L, 0L, 0L};
return data;
}
public static readonly BitSet tokenSet_2_ = new BitSet(mk_tokenSet_2_());
}
| |
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace System.ServiceModel.Activation
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Runtime;
using System.ServiceModel;
using System.ServiceModel.Activation.Diagnostics;
using System.ServiceModel.Channels;
class ListenerConnectionDemuxer
{
ConnectionAcceptor acceptor;
List<InitialServerConnectionReader> connectionReaders;
bool isDisposed;
ListenerConnectionModeCallback onConnectionModeKnown;
ConnectionClosedCallback onConnectionClosed;
// this is the one provided by the caller
ConnectionHandleDuplicated connectionHandleDuplicated;
// this is the onw we use internally
ViaDecodedCallback onViaDecoded;
TransportType transportType;
TimeSpan channelInitializationTimeout;
public ListenerConnectionDemuxer(IConnectionListener listener,
TransportType transportType,
int maxAccepts, int initialMaxPendingConnections,
TimeSpan channelInitializationTimeout,
ConnectionHandleDuplicated connectionHandleDuplicated)
{
this.transportType = transportType;
this.connectionReaders = new List<InitialServerConnectionReader>();
this.connectionHandleDuplicated = connectionHandleDuplicated;
this.acceptor = new ConnectionAcceptor(listener, maxAccepts, initialMaxPendingConnections, OnConnectionAvailable);
this.channelInitializationTimeout = channelInitializationTimeout;
this.onConnectionClosed = new ConnectionClosedCallback(OnConnectionClosed);
this.onViaDecoded = new ViaDecodedCallback(OnViaDecoded);
}
object ThisLock
{
get { return this; }
}
public void Dispose()
{
lock (ThisLock)
{
if (isDisposed)
return;
isDisposed = true;
}
for (int i = 0; i < connectionReaders.Count; i++)
{
connectionReaders[i].Dispose();
}
connectionReaders.Clear();
acceptor.Dispose();
}
ListenerConnectionModeReader SetupModeReader(IConnection connection)
{
if (onConnectionModeKnown == null)
{
onConnectionModeKnown = new ListenerConnectionModeCallback(OnConnectionModeKnown);
}
ListenerConnectionModeReader modeReader = new ListenerConnectionModeReader(connection, onConnectionModeKnown, onConnectionClosed);
lock (ThisLock)
{
if (isDisposed)
{
modeReader.Dispose();
return null;
}
else
{
connectionReaders.Add(modeReader);
return modeReader;
}
}
}
void OnConnectionAvailable(IConnection connection, Action connectionDequeuedCallback)
{
if (transportType == TransportType.Tcp)
{
ListenerPerfCounters.IncrementConnectionsAcceptedTcp();
}
else
{
ListenerPerfCounters.IncrementConnectionsAcceptedNamedPipe();
}
ListenerConnectionModeReader modeReader = SetupModeReader(connection);
if (modeReader != null)
{
// StartReading() will never throw non-fatal exceptions;
// it propagates all exceptions into the onConnectionModeKnown callback,
// which is where we need our robust handling
modeReader.StartReading(this.channelInitializationTimeout, connectionDequeuedCallback);
}
else
{
connectionDequeuedCallback();
}
}
void OnConnectionModeKnown(ListenerConnectionModeReader modeReader)
{
lock (ThisLock)
{
if (isDisposed)
{
return;
}
connectionReaders.Remove(modeReader);
}
try
{
FramingMode framingMode = modeReader.GetConnectionMode();
switch (framingMode)
{
case FramingMode.Duplex:
OnDuplexConnection(modeReader);
break;
case FramingMode.Singleton:
OnSingletonConnection(modeReader);
break;
default:
{
Exception inner = new InvalidDataException(SR.GetString(
SR.FramingModeNotSupported, framingMode));
Exception exception = new ProtocolException(inner.Message, inner);
FramingEncodingString.AddFaultString(exception, FramingEncodingString.UnsupportedModeFault);
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(exception);
}
}
}
catch (ProtocolException exception)
{
DiagnosticUtility.TraceHandledException(exception, TraceEventType.Information);
modeReader.Dispose();
}
catch (Exception exception)
{
if (Fx.IsFatal(exception))
{
throw;
}
DiagnosticUtility.TraceHandledException(exception, TraceEventType.Error);
// containment -- abort the errant reader
modeReader.Dispose();
}
}
void OnViaDecoded(InitialServerConnectionReader connectionReader, ListenerSessionConnection session)
{
try
{
connectionHandleDuplicated(session);
}
finally
{
session.TriggerDequeuedCallback();
}
lock (ThisLock)
{
if (isDisposed)
{
return;
}
connectionReaders.Remove(connectionReader);
}
}
void OnConnectionClosed(InitialServerConnectionReader connectionReader)
{
lock (ThisLock)
{
if (isDisposed)
{
return;
}
connectionReaders.Remove(connectionReader);
}
}
void OnSingletonConnection(ListenerConnectionModeReader modeReader)
{
ListenerSingletonConnectionReader singletonReader = new ListenerSingletonConnectionReader(
modeReader.Connection, modeReader.GetConnectionDequeuedCallback(),
transportType, modeReader.StreamPosition,
modeReader.BufferOffset, modeReader.BufferSize,
onConnectionClosed, onViaDecoded);
lock (ThisLock)
{
if (isDisposed)
{
singletonReader.Dispose();
return;
}
connectionReaders.Add(singletonReader);
}
singletonReader.StartReading(modeReader.AccruedData, modeReader.GetRemainingTimeout());
}
void OnDuplexConnection(ListenerConnectionModeReader modeReader)
{
ListenerSessionConnectionReader sessionReader = new ListenerSessionConnectionReader(
modeReader.Connection, modeReader.GetConnectionDequeuedCallback(),
transportType, modeReader.StreamPosition,
modeReader.BufferOffset, modeReader.BufferSize,
onConnectionClosed, onViaDecoded);
lock (ThisLock)
{
if (isDisposed)
{
sessionReader.Dispose();
return;
}
connectionReaders.Add(sessionReader);
}
sessionReader.StartReading(modeReader.AccruedData, modeReader.GetRemainingTimeout());
}
public void StartDemuxing()
{
acceptor.StartAccepting();
}
}
}
| |
using System;
using System.IO;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using Loon.Utils;
using Loon.Java;
namespace Loon.Core.Store
{
internal class TMPStore
{
private const int DEFAULT_ID = 1;
private const int COULD_NOT_SAVE = -1;
private const int COULD_NOT_OPEN = -2;
public static byte[] GetBytes(string resName)
{
return GetBytes(resName, DEFAULT_ID);
}
public static string GetString(string resName)
{
return BytesToString(GetBytes(resName));
}
public static byte[] GetBytes(string resName, int recordId)
{
byte[] result = new byte[0];
TMPStore rs = null;
try
{
rs = TMPStore.OpenRecordStore(resName, true);
if (rs.Count >= recordId)
{
result = rs.GetRecord(recordId);
}
}
catch(Exception ex)
{
Loon.Utils.Debugging.Log.Exception(ex.Message);
}
finally
{
CloseRecordStore(rs);
}
return result;
}
private static string BytesToString(byte[] bytes)
{
if (bytes == null)
{
return null;
}
return StringUtils.GetString(bytes);
}
private static byte[] StringToBytes(string s)
{
if (s == null)
{
return null;
}
return StringUtils.GetBytes(s);
}
public static string GetString(string resName, int recordId)
{
return BytesToString(GetBytes(resName, recordId));
}
public static void SetBytes(string resName, string data)
{
SetBytes(resName, StringToBytes(data));
}
public static void SetBytes(string resName, byte[] data)
{
SetBytes(resName, DEFAULT_ID, data);
}
public static void SetBytes(string resName, int recordId, byte[] data)
{
TMPStore rs = null;
try
{
rs = TMPStore.OpenRecordStore(resName, true);
if (rs.GetNumRecords() == 0)
{
rs.AddRecord(data, 0, data.Length);
}
else
{
rs.SetRecord(recordId, data, 0, data.Length);
}
}
catch (Exception ex)
{
Loon.Utils.Debugging.Log.Exception(ex);
}
finally
{
CloseRecordStore(rs);
}
}
public static int AddBytes(string resName, byte[] data)
{
TMPStore rs = null;
bool opened = false;
try
{
rs = TMPStore.OpenRecordStore(resName, true);
opened = true;
return rs.AddRecord(data, 0, data.Length);
}
catch (Exception ex)
{
Loon.Utils.Debugging.Log.Exception(ex);
}
finally
{
CloseRecordStore(rs);
}
return opened ? COULD_NOT_SAVE : COULD_NOT_OPEN;
}
public static bool ExistRecordStoreAll(string resName)
{
string[] recordStores = TMPStore.ListRecordStores();
if (recordStores == null)
{
return false;
}
for (int i = 0; i < recordStores.Length; i++)
{
if (recordStores[i].Equals(resName))
{
return true;
}
}
return false;
}
public static void RemoveRecord(string resName, int recordId)
{
TMPStore rs = null;
try
{
rs = TMPStore.OpenRecordStore(resName, false);
rs.DeleteRecord(recordId);
}
finally
{
CloseRecordStore(rs);
}
}
public static void RemoveRecord(string resName)
{
RemoveRecord(resName, DEFAULT_ID);
}
public static bool ExistRecordStore(string resName)
{
TMPStore rs = null;
try
{
rs = TMPStore.OpenRecordStore(resName, false);
return (rs != null);
}
catch
{
return false;
}
finally
{
CloseRecordStore(rs);
}
}
public static void CloseRecordStore(TMPStore rs)
{
if (rs != null)
{
rs.CloseRecordStore();
rs = null;
}
}
private int nextRecordId = 1;
public const string HEADER = "TMPStore:1";
public const string STORE_FILENAME_PREFIX = "lgame-record-";
public const string STORE_FILENAME_SUFFIX = ".store";
private System.IO.IsolatedStorage.IsolatedStorageFile isoStorage = System.IO.IsolatedStorage.IsolatedStorageFile.GetUserStoreForApplication();
private static Dictionary<string, TMPStore> stores = new Dictionary<string, TMPStore>(10);
private List<RecordItem> records = new List<RecordItem>();
private string name;
private int openCount = 0;
private string storeFile;
public static TMPStore OpenRecordStore(string recordStoreName, bool createIfNecessary)
{
lock (stores)
{
TMPStore store = (TMPStore)CollectionUtils.Get(stores, recordStoreName);
if (store == null)
{
store = new TMPStore(recordStoreName);
stores.Add(recordStoreName, store);
}
store.OpenRecordStore(createIfNecessary);
return store;
}
}
private TMPStore(string name)
{
this.name = name;
}
public static void Deletes()
{
System.IO.IsolatedStorage.IsolatedStorageFile.GetUserStoreForApplication().Remove();
}
[MethodImpl(MethodImplOptions.Synchronized)]
public void DeleteStores()
{
string[] stores = ListRecordStores();
if (stores == null)
{
return;
}
for (int i = 0; i < stores.Length; i++)
{
string store = stores[i];
try
{
DeleteRecordStore(store);
}
catch (Exception ex)
{
Loon.Utils.Debugging.Log.Exception(ex);
}
}
}
[MethodImpl(MethodImplOptions.Synchronized)]
public bool DeleteRecordStore(string recordStoreName)
{
try
{
List<string> list = FileUtils.GetIsolatedStorageFiles(STORE_FILENAME_SUFFIX.Substring(1));
if (list != null)
{
int size = list.Count;
string ret, name;
for (int i = 0; i < size; i++)
{
name = list[i];
ret = FileUtils.GetFileName(list[i]);
ret = StringUtils.ReplaceIgnoreCase(ret.Substring(0, ret.Length - STORE_FILENAME_SUFFIX.Length), STORE_FILENAME_PREFIX, "");
if (recordStoreName.Equals(ret))
{
stores.Remove(ret);
isoStorage.DeleteFile(list[i]);
return true;
}
}
}
else
{
return false;
}
}
catch (IOException e)
{
throw new IOException("Store " + recordStoreName + "deleteRecordStore IOException!" + e.Message);
}
catch (Exception e)
{
throw new Exception("Store " + recordStoreName + "deleteRecordStore Exception!" + e.Message);
}
return false;
}
[MethodImpl(MethodImplOptions.Synchronized)]
public static string[] ListRecordStores()
{
string[] result = null;
try
{
List<string> list = FileUtils.GetIsolatedStorageFiles(STORE_FILENAME_SUFFIX.Substring(1));
if (list != null)
{
int size = list.Count;
result = new string[size];
if (size == 0)
{
result = null;
}
else
{
string ret;
for (int i = 0; i < size; i++)
{
ret = FileUtils.GetFileName(list[i]);
result[i] = StringUtils.ReplaceIgnoreCase(ret.Substring(0, ret.Length - STORE_FILENAME_SUFFIX.Length), STORE_FILENAME_PREFIX, "");
}
}
}
}
catch (IOException e)
{
throw new Exception("Store listRecordStores IOException!" + e.StackTrace);
}
return result;
}
[MethodImpl(MethodImplOptions.Synchronized)]
public void OpenRecordStore(bool createIfNecessary)
{
if (openCount > 0)
{
openCount++;
return;
}
storeFile = STORE_FILENAME_PREFIX + name + STORE_FILENAME_SUFFIX;
bool exists = isoStorage.FileExists(storeFile);
bool readOk = false;
if (exists)
{
try
{
ReadFromDisk(isoStorage, storeFile);
readOk = true;
}
catch
{
if (!createIfNecessary)
{
throw new Exception("Store " + name + " could not read/find backing file " + storeFile);
}
}
}
if (!readOk)
{
Clear();
WriteToDisk(isoStorage, storeFile);
}
openCount = 1;
}
public class RecordItem
{
internal int id;
internal byte[] data;
internal RecordItem()
{
}
internal RecordItem(int id, byte[] data)
{
this.id = id;
this.data = data;
}
}
[MethodImpl(MethodImplOptions.Synchronized)]
private void Clear()
{
nextRecordId = 1;
records.Clear();
}
[MethodImpl(MethodImplOptions.Synchronized)]
private void ReadFromDisk(System.IO.IsolatedStorage.IsolatedStorageFile iso, string storeFile)
{
DataInputStream dis = FileUtils.ReadIsolatedStorageFileToDataInput(iso, storeFile);
try
{
string header = dis.ReadUTF();
if (!header.Equals(HEADER))
{
throw new Exception("Store file header mismatch: " + header);
}
nextRecordId = dis.ReadInt();
int size = dis.ReadInt();
records.Clear();
for (int i = 0; i < size; i++)
{
long pSize = dis.ReadLong();
int pId = dis.ReadInt();
byte[] buffer = new byte[pSize];
dis.Read(buffer);
RecordItem ri = new RecordItem(pId, buffer);
records.Add(ri);
}
}
catch (Exception e)
{
throw new Exception("ERROR reading store from disk (" + storeFile + "): " + e.StackTrace);
}
finally
{
if (dis != null)
{
dis.Close();
dis = null;
}
}
}
[MethodImpl(MethodImplOptions.Synchronized)]
private void WriteToDisk(System.IO.IsolatedStorage.IsolatedStorageFile iso, string storeFile)
{
DataOutputStream dos = FileUtils.WriteIsolatedStorageFileToDataInput(iso, storeFile);
try
{
dos.WriteUTF(HEADER);
dos.WriteInt(nextRecordId);
dos.WriteInt(records.Count);
for (int i = 0; i < records.Count; i++)
{
RecordItem ri = records[i];
long pSize = ri.data.Length;
int pId = ri.id;
dos.WriteLong(pSize);
dos.WriteInt(pId);
dos.Write(ri.data);
}
}
catch (Exception e)
{
throw new Exception("Error writing store to disk: " + e.StackTrace);
}
finally
{
if (dos != null)
dos.Close();
dos = null;
}
}
public void CheckOpen(string message)
{
if (openCount <= 0)
{
throw new Exception(message);
}
}
[MethodImpl(MethodImplOptions.Synchronized)]
public int AddRecord(byte[] data, int offset, int numBytes)
{
CheckOpen("addRecord");
byte[] buf = new byte[numBytes];
if (numBytes != 0)
{
Array.Copy(data, offset, buf, 0, numBytes);
}
RecordItem ri = new RecordItem(nextRecordId++, buf);
records.Add(ri);
WriteToDisk(isoStorage, this.storeFile);
return ri.id;
}
public int Count
{
get
{
return records.Count;
}
}
public void CloseRecordStore()
{
CheckOpen("closeRecordStore");
openCount--;
}
[MethodImpl(MethodImplOptions.Synchronized)]
public void DeleteRecord(int recordId)
{
CheckOpen("deleteRecord");
for (int i = 0; i < records.Count; i++)
{
RecordItem ri = records[i];
if (ri.id == recordId)
{
records.RemoveAt(i);
WriteToDisk(isoStorage, storeFile);
return;
}
}
throw new Exception("deleteRecord " + recordId);
}
[MethodImpl(MethodImplOptions.Synchronized)]
public RecordEnumerationImpl EnumerateRecords()
{
CheckOpen("enumerateRecords");
return new RecordEnumerationImpl(records);
}
public string GetName()
{
CheckOpen("getName");
return name;
}
public int GetNumRecords()
{
CheckOpen("getNumRecords");
return records.Count;
}
[MethodImpl(MethodImplOptions.Synchronized)]
private RecordItem GetRecordItem(int id)
{
for (IEnumerator<RecordItem> rs = records.GetEnumerator(); rs.MoveNext(); )
{
RecordItem ri = rs.Current;
if (ri.id == id)
{
return ri;
}
}
return null;
}
[MethodImpl(MethodImplOptions.Synchronized)]
public byte[] GetRecord(int recordId)
{
CheckOpen("getRecord");
RecordItem ri = GetRecordItem(recordId);
if (ri == null)
{
throw new Exception("GetRecord record " + recordId + " not found .");
}
return ri.data;
}
[MethodImpl(MethodImplOptions.Synchronized)]
public int GetRecord(int recordId, byte[] buffer, int offset)
{
CheckOpen("getRecord");
RecordItem ri = GetRecordItem(recordId);
if (ri == null)
{
throw new Exception("GetRecord record " + recordId + " not found .");
}
byte[] data = ri.data;
int recordSize = data.Length;
Array.Copy(data, 0, buffer, offset, recordSize);
return recordSize;
}
[MethodImpl(MethodImplOptions.Synchronized)]
public int GetRecordSize(int recordId)
{
CheckOpen("getRecordSize");
RecordItem ri = GetRecordItem(recordId);
if (ri == null)
{
throw new Exception("record " + recordId + " not found .");
}
byte[] data = (byte[])ri.data;
if (data == null)
{
throw new Exception();
}
return data.Length;
}
public int GetNextRecordID()
{
return nextRecordId;
}
public int GetSize()
{
try
{
return GetRecordSize(nextRecordId);
}
catch (Exception e)
{
throw new Exception(e.StackTrace);
}
}
[MethodImpl(MethodImplOptions.Synchronized)]
public void SetRecord(int recordId, byte[] newData, int offset, int numBytes)
{
CheckOpen("setRecord");
RecordItem ri = GetRecordItem(recordId);
if (ri == null)
{
throw new Exception("record " + recordId + " not found .");
}
byte[] buf = new byte[numBytes];
if (numBytes != 0)
{
Array.Copy(newData, offset, buf, 0, numBytes);
}
ri.data = buf;
WriteToDisk(isoStorage, this.storeFile);
}
internal class RecordEnumerationImpl
{
private List<RecordItem> items;
internal RecordEnumerationImpl(List<RecordItem> r)
{
this.items = r;
this.nextIndex = 0;
}
private int nextIndex;
public bool HasNextElement()
{
lock (TMPStore.stores)
{
return nextIndex < items.Count;
}
}
public int NextRecordId()
{
lock (TMPStore.stores)
{
if (nextIndex >= items.Count)
{
throw new Exception("nextRecordId at index " + nextIndex + "/" + items.Count);
}
RecordItem ri = items[nextIndex];
nextIndex++;
return ri.id;
}
}
}
}
}
| |
// Copyright (c) 2015, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Collections.Generic;
using System.Configuration;
using WebsitePanel.Providers;
using WebsitePanel.Providers.Common;
using WebsitePanel.Providers.DNS;
using WebsitePanel.ServiceProviders.DNS.Nettica;
namespace WebsitePanel.Providers.DNS
{
public class Nettica : HostingServiceProviderBase, IDnsServer
{
public const string NetticaWebServiceUrl = "NetticaWebServiceUrl";
private const int Success = 200;
private readonly NetticaProxy proxy;
public string Login
{
get { return ProviderSettings[Constants.UserName]; }
}
public string Password
{
get
{
byte[] data = System.Text.Encoding.UTF8.GetBytes(ProviderSettings[Constants.Password]);
string binPassword = Convert.ToBase64String(data);
return binPassword;
}
}
public bool ApplyDefaultTemplate
{
get
{
bool res;
bool.TryParse(ProviderSettings["ApplyDefaultTemplate"], out res);
return res;
}
}
public Nettica()
{
proxy = new NetticaProxy();
string url = ConfigurationManager.AppSettings[NetticaWebServiceUrl];
if (!string.IsNullOrEmpty(url))
proxy.Url = url;
}
private static DomainRecord ConvertToDomainRecord(DnsRecord dnsRecord, string zoneName)
{
DomainRecord domainRecord = new DomainRecord();
domainRecord.Data = dnsRecord.RecordData;
domainRecord.DomainName = zoneName;
domainRecord.Priority = dnsRecord.MxPriority;
domainRecord.RecordType = dnsRecord.RecordType.ToString();
domainRecord.HostName = dnsRecord.RecordName;
return domainRecord;
}
private static DnsRecord ConvertToDnsRecord(DomainRecord record)
{
DnsRecord dnsRecord = new DnsRecord();
dnsRecord.RecordName = record.HostName;
dnsRecord.MxPriority = record.Priority;
dnsRecord.RecordData = record.Data;
switch(record.RecordType)
{
case "A":
dnsRecord.RecordType = DnsRecordType.A;
break;
case "AAAA":
dnsRecord.RecordType = DnsRecordType.AAAA;
break;
case "MX":
dnsRecord.RecordType = DnsRecordType.MX;
break;
case "CNAME":
dnsRecord.RecordType = DnsRecordType.CNAME;
break;
case "NS":
dnsRecord.RecordType = DnsRecordType.NS;
break;
case "SOA":
dnsRecord.RecordType = DnsRecordType.SOA;
break;
case "TXT":
dnsRecord.RecordType = DnsRecordType.TXT;
break;
}
return dnsRecord;
}
#region IDnsServer Members
public bool ZoneExists(string zoneName)
{
if (string.IsNullOrEmpty(zoneName))
throw new ArgumentNullException("zoneName");
DomainResult res = proxy.ListDomain(Login, Password, zoneName);
return res.Result.Status == Success;
}
public string[] GetZones()
{
ZoneResult res = proxy.ListZones(Login, Password);
if (res.Result.Status != Success)
throw new Exception(
string.Format("Could not get zones. Error code {0}. {1}",
res.Result.Status,
res.Result.Description));
return res.Zone;
}
public void AddPrimaryZone(string zoneName, string[] secondaryServers)
{
if (string.IsNullOrEmpty(zoneName))
throw new ArgumentNullException("zoneName");
DnsResult res = proxy.CreateZone(Login, Password, zoneName, string.Empty/*no longer used*/);
if (res.Status != Success)
throw new Exception(
string.Format("Could not add primary zone with name {0}. Error code {1}. {2}",
zoneName,
res.Status,
res.Description));
if (ApplyDefaultTemplate)
{
int result = ApplydefaultTemplate(Login, Password, zoneName, String.Empty);
if (result != Success)
{
throw new Exception(
string.Format("Could not apply default domain template for primary zone with name {0}. Error code {1}. {2}",
zoneName,
res.Status,
res.Description));
}
}
}
private int ApplydefaultTemplate(string login, string password, string zonename, string group)
{
DnsResult res = proxy.ApplyTemplate(login, password, zonename, group);
return res.Status;
}
public void AddSecondaryZone(string zoneName, string[] masterServers)
{
if (string.IsNullOrEmpty(zoneName))
throw new ArgumentNullException("zoneName");
if (masterServers == null)
throw new ArgumentNullException("masterServers");
foreach (string master in masterServers)
{
DnsResult res = proxy.CreateSecondaryZone(Login, Password, zoneName, master, string.Empty);
if (res.Status != Success)
throw new Exception(
string.Format("Could not add secondary zone with name {0}. Master zone {1}. Error code {2}. {3}",
zoneName, master, res.Status, res.Description));
}
}
public void DeleteZone(string zoneName)
{
if (string.IsNullOrEmpty(zoneName))
throw new ArgumentNullException("zoneName");
DnsResult res = proxy.DeleteZone(Login, Password, zoneName);
if (res.Status != Success)
throw new Exception(
string.Format("Could not delete zone with name {0}. Error code {1}, {2}", zoneName, res.Status, res.Description));
}
public void UpdateSoaRecord(string zoneName, string host, string primaryNsServer, string primaryPerson)
{
// throw new Exception("The method or operation is not implemented.");
}
public DnsRecord[] GetZoneRecords(string zoneName)
{
if (string.IsNullOrEmpty(zoneName))
throw new ArgumentNullException("zoneName");
DomainResult res = proxy.ListDomain(Login, Password, zoneName);
if (res.Result.Status != Success)
throw new Exception(string.Format("Could not get zone records. Error code {0}. {1}", res.Result.Status, res.Result.Description));
List <DnsRecord> retRecords = new List<DnsRecord>(res.Record.Length);
foreach (DomainRecord record in res.Record)
{
DnsRecord tempRecord = ConvertToDnsRecord(record);
retRecords.Add(tempRecord);
}
return retRecords.ToArray();
}
public void AddZoneRecord(string zoneName, DnsRecord record)
{
if (string.IsNullOrEmpty(zoneName))
throw new ArgumentNullException("zoneName");
if (record == null)
throw new ArgumentNullException("record");
DomainRecord rec = ConvertToDomainRecord(record, zoneName);
DnsResult res = proxy.AddRecord(Login, Password, rec);
if (res.Status != Success)
throw new Exception(string.Format("Could not add zone record. Error code {0}. {1}", res.Status, res.Description));
}
public void AddZoneRecords(string zoneName, DnsRecord[] records)
{
if (string.IsNullOrEmpty(zoneName))
throw new ArgumentNullException("zoneName");
if (records == null)
throw new ArgumentNullException("records");
foreach (DnsRecord record in records)
{
AddZoneRecord(zoneName, record);
}
}
public void DeleteZoneRecord(string zoneName, DnsRecord record)
{
if (string.IsNullOrEmpty(zoneName))
throw new ArgumentNullException("zoneName");
if (record == null)
throw new ArgumentNullException("record");
DomainRecord domainRecord = ConvertToDomainRecord(record, zoneName);
DnsResult res = proxy.DeleteRecord(Login, Password, domainRecord);
if (res.Status != Success)
throw new Exception(string.Format("Could not delete zone record. Error code {0}. {1}", res.Status, res.Description));
}
public void DeleteZoneRecords(string zoneName, DnsRecord[] records)
{
if (string.IsNullOrEmpty(zoneName))
throw new ArgumentNullException("zoneName");
if (records == null)
throw new ArgumentNullException("records");
foreach (DnsRecord record in records)
{
DeleteZoneRecord(zoneName, record);
}
}
#endregion
public override void DeleteServiceItems(ServiceProviderItem[] items)
{
if (items == null)
throw new ArgumentNullException("items");
foreach (ServiceProviderItem item in items)
{
DeleteZone(item.Name);
}
base.DeleteServiceItems(items);
}
public override bool IsInstalled()
{
return true;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Drawing;
using System.Reflection;
using System.Runtime.InteropServices;
using System.IO;
using System.Diagnostics;
using System.Windows.Automation;
using System.Threading;
namespace UnitTests {
public class FileComparer : IComparer<string> {
public int Compare(string a, string b) {
if (a == null && b == null) return 0;
if (a == null) return -1;
if (b == null) return 1;
// The operating system may or may not have visible "file extensions" so we do an extensionless compare
return string.Compare(Path.GetFileNameWithoutExtension(a), Path.GetFileNameWithoutExtension(b), StringComparison.CurrentCultureIgnoreCase);
}
}
public class StringComparer : IComparer<string> {
public int Compare(string a, string b) {
return String.Compare(a, b, StringComparison.CurrentCultureIgnoreCase);
}
}
public class AutomationWrapper
{
AutomationElement e;
public AutomationWrapper(AutomationElement e)
{
this.e = e;
}
internal AutomationElement AutomationElement { get { return e; } }
public static AutomationWrapper AccessibleObjectForWindow(IntPtr hwnd)
{
AutomationElement e = AutomationElement.FromHandle(hwnd);
if (e == null)
{
throw new Exception("Automation element not found for this window");
}
return new AutomationWrapper(e);
}
internal static AutomationWrapper AccessibleObjectAt(Point center)
{
AutomationElement e = AutomationElement.FromPoint(new System.Windows.Point(center.X, center.Y));
if (e == null)
{
throw new Exception("Automation element not found at this location: " + center.ToString());
}
return new AutomationWrapper(e);
}
internal static AutomationWrapper AccessibleWindowObjectAt(Point center)
{
AutomationWrapper e = AccessibleObjectAt(center);
if (e == null)
{
throw new Exception("Automation element not found for this window");
}
AutomationElement ae = e.e;
while (ae != null && ae.Current.ControlType != ControlType.Window)
{
ae = TreeWalker.RawViewWalker.GetParent(ae);
if (ae == null)
{
throw new Exception("Window not found for this element");
}
}
if (ae != null)
{
return new AutomationWrapper(ae);
}
throw new Exception("Window not found at this location: " + center.ToString());
}
public string Name {
get { return e.Current.Name; }
}
public string ClassName
{
get { return e.Current.ClassName; }
}
public AutomationWrapper Parent
{
get
{
AutomationElement parent = TreeWalker.RawViewWalker.GetParent(e);
if (parent != null)
{
return new AutomationWrapper(parent);
}
throw new Exception("Element has no parent");
}
}
public string KeyboardShortcut { get { return e.Current.AcceleratorKey; } }
public string Help { get { return e.Current.HelpText; } }
public string Role { get { return e.Current.ControlType.ToString(); } }
public string Status { get { return e.Current.ItemStatus; } }
public Rectangle Bounds
{
get { return e.Current.BoundingRectangle.ToRectangle(); }
}
public int GetChildCount()
{
var children = GetChildren();
return (children == null) ? 0 : children.Length;
}
public bool IsVisible { get { return !e.Current.IsOffscreen; } }
public AutomationWrapper FindChild(string name)
{
AutomationElement child = e.FindFirst(TreeScope.Children, new PropertyCondition(AutomationElement.NameProperty, name, PropertyConditionFlags.IgnoreCase));
if (child != null)
{
return new AutomationWrapper(child);
}
throw new Exception(string.Format("Child '{0}' not found", name));
}
public void Invoke()
{
InvokePattern ip = e.GetCurrentPattern(InvokePattern.Pattern) as InvokePattern;
if (ip != null)
{
ip.Invoke();
return;
}
throw new Exception("Element '" + e.Current.Name + "' does not support InvokePattern");
}
public string Value
{
get
{
object o = null;
if (e.TryGetCurrentPattern(ValuePattern.Pattern, out o))
{
ValuePattern vp = (ValuePattern)o;
return vp.Current.Value;
}
else
{
// must not be a leaf node then, unfortunately the mapping from IAccessible to AutomationElement
// don't add ValuePattern on ListItems that have children, so we have to get the value the hard way.
Thread.Sleep(100);
SendKeys.SendWait("{ENTER}");
Thread.Sleep(300);
SendKeys.SendWait("^c");
string text = Clipboard.GetText();
Thread.Sleep(300);
SendKeys.SendWait("{ENTER}");
Thread.Sleep(300);
return text;
}
}
set
{
object o = null;
if (e.TryGetCurrentPattern(ValuePattern.Pattern, out o))
{
ValuePattern vp = (ValuePattern)o;
vp.SetValue(value);
}
else
{
// must not be a leaf node then, unfortunately the mapping from IAccessible to AutomationElement
// don't add ValuePattern on ListItems that have children, so we have to get the value the hard way.
Thread.Sleep(100);
SendKeys.SendWait("{ENTER}");
Thread.Sleep(300);
Clipboard.SetText(value);
SendKeys.SendWait("^v");
Thread.Sleep(300);
SendKeys.SendWait("{ENTER}");
Thread.Sleep(300);
}
}
}
#region Manage Children
public AutomationWrapper FirstChild
{
get
{
AutomationElement child = TreeWalker.RawViewWalker.GetFirstChild(e);
if (child != null)
{
return new AutomationWrapper(child);
}
throw new Exception("FirstChild not found");
}
}
public AutomationWrapper LastChild
{
get
{
AutomationElement child = TreeWalker.RawViewWalker.GetLastChild(e);
if (child != null)
{
return new AutomationWrapper(child);
}
throw new Exception("LastChild not found");
}
}
public AutomationWrapper NextSibling
{
get
{
AutomationElement next = TreeWalker.RawViewWalker.GetNextSibling(e);
if (next != null)
{
return new AutomationWrapper(next);
}
throw new Exception("There is no next sibling");
}
}
public AutomationWrapper PreviousSibling
{
get
{
AutomationElement next = TreeWalker.RawViewWalker.GetPreviousSibling(e);
if (next != null)
{
return new AutomationWrapper(next);
}
throw new Exception("There is no previous sibling");
}
}
public AutomationWrapper FindDescendant(string name)
{
AutomationElement child = this.e.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.NameProperty, name));
if (child != null)
{
return new AutomationWrapper(child);
}
throw new Exception(string.Format("Descendant named '{0}' not found", name));
}
public AutomationWrapper[] GetChildren()
{
List<AutomationWrapper> list = new List<AutomationWrapper>();
foreach (AutomationElement child in this.e.FindAll(TreeScope.Children, new PropertyCondition(AutomationElement.IsOffscreenProperty, false)))
{
list.Add(new AutomationWrapper(child));
}
return list.ToArray();
}
internal AutomationWrapper GetChild(int index)
{
AutomationWrapper[] children = GetChildren();
if (index >= 0 && index < children.Length)
{
return children[index];
}
throw new Exception(string.Format("Child at index {0} not found, there are only {1} children", index, children.Length));
}
internal AutomationWrapper HitTest(int x, int y)
{
return AutomationWrapper.AccessibleObjectAt(new Point(x, y));
}
#endregion
#region Selection
public void Select()
{
SelectionItemPattern vp = e.GetCurrentPattern(SelectionItemPattern.Pattern) as SelectionItemPattern;
if (vp != null)
{
vp.Select();
return;
}
throw new Exception("Element does not support SelectionItemPattern");
}
public void AddToSelection()
{
SelectionItemPattern vp = e.GetCurrentPattern(SelectionItemPattern.Pattern) as SelectionItemPattern;
if (vp != null)
{
vp.AddToSelection();
return;
}
throw new Exception("Element does not support SelectionItemPattern");
}
public void RemoveFromSelection()
{
SelectionItemPattern vp = e.GetCurrentPattern(SelectionItemPattern.Pattern) as SelectionItemPattern;
if (vp != null)
{
vp.RemoveFromSelection();
return;
}
throw new Exception("Element does not support SelectionItemPattern");
}
internal AutomationWrapper GetSelectedChild()
{
SelectionPattern sp = e.GetCurrentPattern(SelectionPattern.Pattern) as SelectionPattern;
if (sp != null){
foreach (AutomationElement selected in sp.Current.GetSelection())
{
return new AutomationWrapper(selected);
}
}
throw new Exception("No child is selected");
}
#endregion
#region Focus
public static AutomationWrapper Focus
{
get { return new AutomationWrapper(AutomationElement.FocusedElement); }
}
public void SetFocus()
{
e.SetFocus();
}
public bool IsFocused
{
get
{
return this.e.Current.HasKeyboardFocus;
}
}
#endregion
#region Toggle Items
public bool IsChecked
{
get
{
TogglePattern ep = this.e.GetCurrentPattern(TogglePattern.Pattern) as TogglePattern;
if (ep != null)
{
return ep.Current.ToggleState == ToggleState.On;
}
throw new Exception("Element does not support TogglePattern");
}
set
{
TogglePattern ep = this.e.GetCurrentPattern(TogglePattern.Pattern) as TogglePattern;
if (ep != null)
{
ToggleState target = ToggleState.Off;
if (value)
{
target = ToggleState.On;
}
var start = ep.Current.ToggleState;
while (ep.Current.ToggleState != target)
{
ep.Toggle();
if (ep.Current.ToggleState == start)
{
throw new Exception("Element is not toggling, enabled state is " + e.Current.IsEnabled);
}
}
return;
}
throw new Exception("Element does not support TogglePattern");
}
}
#endregion
#region expandible
public bool IsExpanded
{
get
{
// we cheat in the TreeView implementation and return the expanded state in the Help field.
// The reason for this is the mapping from IAccessible to AutomationElement only allows one control type.
// We want ListItem and OutlineItem, but we can't do both. We need the SelectionItemPattern of ListItem
// so we go with that, and cheat on expandable state.
string help = this.Help;
if (help == "expanded")
{
return true;
}
return false;
}
set
{
bool expanded = IsExpanded;
if (value)
{
if (!expanded)
{
Invoke();
}
}
else
{
if (expanded)
{
Invoke();
}
}
}
}
#endregion
public IntPtr Hwnd { get { return new IntPtr(this.e.Current.NativeWindowHandle); } }
public string ControlTypeName { get { return this.e.Current.ControlType.ToString(); } }
}
public static class WinFormsExtensions
{
public static Rectangle ToRectangle(this System.Windows.Rect r)
{
return new Rectangle((int)r.Left, (int)r.Top, (int)r.Width, (int)r.Height);
}
public static Point Center(this Rectangle bounds)
{
return new Point(bounds.Left + (bounds.Width / 2),
bounds.Top + (bounds.Height / 2));
}
}
public class OpenFileDialog
{
Window dialog;
public OpenFileDialog(Window window)
{
this.dialog = window;
}
public AutomationWrapper GetFileItem(string fileName)
{
AutomationWrapper items = dialog.AccessibleObject.FindDescendant("Items View");
if (items != null)
{
AutomationElement item = items.AutomationElement.FindFirst(TreeScope.Children, new PropertyCondition(AutomationElement.NameProperty, fileName, PropertyConditionFlags.IgnoreCase));
while (item == null)
{
if (ScrollList(items, ScrollAmount.LargeIncrement) >= 100)
{
break;
}
item = items.AutomationElement.FindFirst(TreeScope.Children, new PropertyCondition(AutomationElement.NameProperty, fileName, PropertyConditionFlags.IgnoreCase));
}
if (item != null)
{
return new AutomationWrapper(item);
}
}
throw new Exception("File '" + fileName + "'not found");
}
private double ScrollList(AutomationWrapper items, ScrollAmount amount)
{
ScrollPattern sp = items.AutomationElement.GetCurrentPattern(ScrollPattern.Pattern) as ScrollPattern;
if (sp.Current.VerticallyScrollable)
{
sp.ScrollVertical(amount);
}
double percent = sp.Current.VerticalScrollPercent;
return percent;
}
internal void DismissPopUp(string keyStrokes)
{
this.dialog.DismissPopUp(keyStrokes);
}
public string FileName
{
get
{
AutomationWrapper wrapper = this.dialog.FindDescendant("File name:", ControlType.Edit);
return wrapper.Value;
}
set
{
AutomationWrapper wrapper = this.dialog.FindDescendant("File name:", ControlType.Edit);
wrapper.Value = value;
}
}
}
public class FindDialog
{
Window w;
public FindDialog(Window w)
{
this.w = w;
}
public Window Window { get { return this.w; } }
public bool MatchCase
{
get
{
return GetCheckedState("checkBoxMatchCase");
}
set
{
SetCheckedState("checkBoxMatchCase", value);
}
}
public bool UseWholeWord
{
get
{
return GetCheckedState("checkBoxWholeWord");
}
set
{
SetCheckedState("checkBoxWholeWord", value);
}
}
public bool UseRegex
{
get
{
return GetCheckedState("checkBoxRegex");
}
set
{
SetCheckedState("checkBoxRegex", value);
}
}
public bool UseXPath
{
get
{
return GetCheckedState("checkBoxXPath");
}
set
{
SetCheckedState("checkBoxXPath", value);
}
}
public string FindString
{
get
{
AutomationWrapper c = w.FindDescendant("comboBoxFind");
return c.Value;
}
set
{
AutomationWrapper c = w.FindDescendant("comboBoxFind");
c.Value = value;
}
}
internal void ClearFindCheckBoxes()
{
MatchCase = false;
UseWholeWord = false;
UseRegex = false;
UseXPath = false;
}
private bool GetCheckedState(string name)
{
AutomationWrapper s = w.FindDescendant(name);
foreach (var p in s.AutomationElement.GetSupportedProperties())
{
if (p.ProgrammaticName == "TogglePatternIdentifiers.ToggleStateProperty")
{
var value = s.AutomationElement.GetCurrentPropertyValue(p);
if (value != null && value.ToString() == "On")
{
return true;
}
}
}
return false;
}
private void SetCheckedState(string name, bool state)
{
if (this.GetCheckedState(name) == state)
{
return;
}
// seems to be a bug in the AutomationElement mapping, checkbox is not supporting the TogglePattern!
AutomationWrapper s = w.FindDescendant(name);
Rectangle r = s.Bounds;
Mouse.MouseClick(r.Center(), MouseButtons.Left);
Thread.Sleep(200);
}
internal void FocusFindString()
{
AutomationWrapper findCombo = this.w.FindDescendant("comboBoxFind");
Mouse.MouseClick(findCombo.Bounds.Center(), MouseButtons.Left);
}
}
}
| |
//***************************************************
//* This file was generated by tool
//* SharpKit
//* At: 29/08/2012 03:59:40 p.m.
//***************************************************
using SharpKit.JavaScript;
namespace Ext.form.field
{
#region Date
/// <inheritdocs />
/// <summary>
/// <p>Provides a date input field with a <see cref="Ext.picker.Date">date picker</see> dropdown and automatic date
/// validation.</p>
/// <p>This field recognizes and uses the JavaScript Date object as its main <see cref="Ext.form.field.DateConfig.value">value</see> type. In addition,
/// it recognizes string values which are parsed according to the <see cref="Ext.form.field.DateConfig.format">format</see> and/or <see cref="Ext.form.field.DateConfig.altFormats">altFormats</see>
/// configs. These may be reconfigured to use date formats appropriate for the user's locale.</p>
/// <p>The field may be limited to a certain range of dates by using the <see cref="Ext.form.field.DateConfig.minValue">minValue</see>, <see cref="Ext.form.field.DateConfig.maxValue">maxValue</see>,
/// <see cref="Ext.form.field.DateConfig.disabledDays">disabledDays</see>, and <see cref="Ext.form.field.DateConfig.disabledDates">disabledDates</see> config parameters. These configurations will be used both
/// in the field's validation, and in the date picker dropdown by preventing invalid dates from being selected.</p>
/// <h1>Example usage</h1>
/// <pre><code><see cref="Ext.ExtContext.create">Ext.create</see>('<see cref="Ext.form.Panel">Ext.form.Panel</see>', {
/// renderTo: <see cref="Ext.ExtContext.getBody">Ext.getBody</see>(),
/// width: 300,
/// bodyPadding: 10,
/// title: 'Dates',
/// items: [{
/// xtype: 'datefield',
/// anchor: '100%',
/// fieldLabel: 'From',
/// name: 'from_date',
/// maxValue: new Date() // limited to the current date or prior
/// }, {
/// xtype: 'datefield',
/// anchor: '100%',
/// fieldLabel: 'To',
/// name: 'to_date',
/// value: new Date() // defaults to today
/// }]
/// });
/// </code></pre>
/// <h1>Date Formats Examples</h1>
/// <p>This example shows a couple of different date format parsing scenarios. Both use custom date format
/// configurations; the first one matches the configured <c>format</c> while the second matches the <c>altFormats</c>.</p>
/// <pre><code><see cref="Ext.ExtContext.create">Ext.create</see>('<see cref="Ext.form.Panel">Ext.form.Panel</see>', {
/// renderTo: <see cref="Ext.ExtContext.getBody">Ext.getBody</see>(),
/// width: 300,
/// bodyPadding: 10,
/// title: 'Dates',
/// items: [{
/// xtype: 'datefield',
/// anchor: '100%',
/// fieldLabel: 'Date',
/// name: 'date',
/// // The value matches the format; will be parsed and displayed using that format.
/// format: 'm d Y',
/// value: '2 4 1978'
/// }, {
/// xtype: 'datefield',
/// anchor: '100%',
/// fieldLabel: 'Date',
/// name: 'date',
/// // The value does not match the format, but does match an altFormat; will be parsed
/// // using the altFormat and displayed using the format.
/// format: 'm d Y',
/// altFormats: 'm,d,Y|m.d.Y',
/// value: '2.4.1978'
/// }]
/// });
/// </code></pre>
/// </summary>
[JsType(JsMode.Prototype, Export=false, OmitOptionalParameters=true)]
public partial class Date : Picker
{
/// <summary>
/// Multiple date formats separated by "|" to try when parsing a user input value and it does not match the defined
/// format.
/// Defaults to: <c>"m/d/Y|n/j/Y|n/j/y|m/j/y|n/d/y|m/j/Y|n/d/Y|m-d-y|m-d-Y|m/d|m-d|md|mdy|mdY|d|Y-m-d|n-j|n/j"</c>
/// </summary>
public JsString altFormats;
/// <summary>
/// An array of "dates" to disable, as strings. These strings will be used to build a dynamic regular expression so
/// they are very powerful. Some examples:
/// <code>// disable these exact dates:
/// disabledDates: ["03/08/2003", "09/16/2003"]
/// // disable these days for every year:
/// disabledDates: ["03/08", "09/16"]
/// // only match the beginning (useful if you are using short years):
/// disabledDates: ["^03/08"]
/// // disable every day in March 2006:
/// disabledDates: ["03/../2006"]
/// // disable every day in every March:
/// disabledDates: ["^03"]
/// </code>
/// Note that the format of the dates included in the array should exactly match the <see cref="Ext.form.field.DateConfig.format">format</see> config. In order
/// to support regular expressions, if you are using a <see cref="Ext.form.field.DateConfig.format">date format</see> that has "." in it, you will have
/// to escape the dot when restricting dates. For example: <c>["03\\.08\\.03"]</c>.
/// </summary>
public JsString disabledDates;
/// <summary>
/// The tooltip text to display when the date falls on a disabled date.
/// Defaults to: <c>"Disabled"</c>
/// </summary>
public JsString disabledDatesText;
/// <summary>
/// An array of days to disable, 0 based. Some examples:
/// <code>// disable Sunday and Saturday:
/// disabledDays: [0, 6]
/// // disable weekdays:
/// disabledDays: [1,2,3,4,5]
/// </code>
/// </summary>
public JsNumber disabledDays;
/// <summary>
/// The tooltip to display when the date falls on a disabled day.
/// Defaults to: <c>"Disabled"</c>
/// </summary>
public JsString disabledDaysText;
/// <summary>
/// The default date format string which can be overriden for localization support. The format must be valid
/// according to Ext.Date.parse.
/// Defaults to: <c>"m/d/Y"</c>
/// </summary>
public JsString format;
/// <summary>
/// The error text to display when the date in the cell is after maxValue.
/// Defaults to: <c>"The date in this field must be equal to or before {0}"</c>
/// </summary>
public JsString maxText;
/// <summary>
/// The maximum allowed date. Can be either a Javascript date object or a string date in a valid format.
/// </summary>
public object maxValue;
/// <summary>
/// The error text to display when the date in the cell is before minValue.
/// Defaults to: <c>"The date in this field must be equal to or after {0}"</c>
/// </summary>
public JsString minText;
/// <summary>
/// The minimum allowed date. Can be either a Javascript date object or a string date in a valid format.
/// </summary>
public object minValue;
/// <summary>
/// false to hide the footer area of the Date picker containing the Today button and disable the keyboard handler for
/// spacebar that selects the current date.
/// Defaults to: <c>true</c>
/// </summary>
public bool showToday;
/// <summary>
/// Day index at which the week should begin, 0-based.
/// Defaults to <c>0</c> (Sunday).
/// </summary>
public JsNumber startDay;
/// <summary>
/// The date format string which will be submitted to the server. The format must be valid according to
/// Ext.Date.parse.
/// Defaults to <see cref="Ext.form.field.DateConfig.format">format</see>.
/// </summary>
public JsString submitFormat;
/// <summary>
/// True to enforce strict date parsing to prevent the default Javascript "date rollover".
/// Defaults to the useStrict parameter set on Ext.Date
/// See Ext.Date.parse.
/// </summary>
public bool useStrict;
/// <summary>
/// Focuses the field when collapsing the Date picker.
/// </summary>
private void onCollapse(){}
/// <summary>
/// Sets the Date picker's value to match the current field value when expanding.
/// </summary>
private void onExpand(){}
/// <summary>
/// Parameters<li><span>value</span> : <see cref="Object">Object</see><div>
/// </div></li>
/// </summary>
/// <param name="value">
/// </param>
private void parseDate(object value){}
/// <summary>
/// Attempts to parse a given string value using a given date format.
/// </summary>
/// <param name="value"><p>The value to attempt to parse</p>
/// </param>
/// <param name="format"><p>A valid date format (see <see cref="Ext.Date.parse">Ext.Date.parse</see>)</p>
/// </param>
/// <returns>
/// <span><see cref="Date">Date</see></span><div><p>The parsed Date object, or null if the value could not be successfully parsed.</p>
/// </div>
/// </returns>
public JsDate safeParse(JsString value, JsString format){return null;}
/// <summary>
/// Replaces any existing disabled dates with new values and refreshes the Date picker.
/// </summary>
/// <param name="disabledDates"><p>An array of date strings (see the <see cref="Ext.form.field.DateConfig.disabledDates">disabledDates</see> config for details on
/// supported values) used to disable a pattern of dates.</p>
/// </param>
public void setDisabledDates(JsArray<String> disabledDates){}
/// <summary>
/// Replaces any existing disabled days (by index, 0-6) with new values and refreshes the Date picker.
/// </summary>
/// <param name="disabledDays"><p>An array of disabled day indexes. See the <see cref="Ext.form.field.DateConfig.disabledDays">disabledDays</see> config for details on
/// supported values.</p>
/// </param>
public void setDisabledDays(JsArray<Number> disabledDays){}
/// <summary>
/// Replaces any existing maxValue with the new value and refreshes the Date picker.
/// </summary>
/// <param name="value"><p>The maximum date that can be selected</p>
/// </param>
public void setMaxValue(JsDate value){}
/// <summary>
/// Replaces any existing minValue with the new value and refreshes the Date picker.
/// </summary>
/// <param name="value"><p>The minimum date that can be selected</p>
/// </param>
public void setMinValue(JsDate value){}
public Date(Ext.form.field.DateConfig config){}
public Date(){}
public Date(params object[] args){}
}
#endregion
#region DateConfig
/// <inheritdocs />
[JsType(JsMode.Json, Export=false, OmitOptionalParameters=true)]
public partial class DateConfig : PickerConfig
{
/// <summary>
/// Multiple date formats separated by "|" to try when parsing a user input value and it does not match the defined
/// format.
/// Defaults to: <c>"m/d/Y|n/j/Y|n/j/y|m/j/y|n/d/y|m/j/Y|n/d/Y|m-d-y|m-d-Y|m/d|m-d|md|mdy|mdY|d|Y-m-d|n-j|n/j"</c>
/// </summary>
public JsString altFormats;
/// <summary>
/// An array of "dates" to disable, as strings. These strings will be used to build a dynamic regular expression so
/// they are very powerful. Some examples:
/// <code>// disable these exact dates:
/// disabledDates: ["03/08/2003", "09/16/2003"]
/// // disable these days for every year:
/// disabledDates: ["03/08", "09/16"]
/// // only match the beginning (useful if you are using short years):
/// disabledDates: ["^03/08"]
/// // disable every day in March 2006:
/// disabledDates: ["03/../2006"]
/// // disable every day in every March:
/// disabledDates: ["^03"]
/// </code>
/// Note that the format of the dates included in the array should exactly match the <see cref="Ext.form.field.DateConfig.format">format</see> config. In order
/// to support regular expressions, if you are using a <see cref="Ext.form.field.DateConfig.format">date format</see> that has "." in it, you will have
/// to escape the dot when restricting dates. For example: <c>["03\\.08\\.03"]</c>.
/// </summary>
public JsString disabledDates;
/// <summary>
/// The tooltip text to display when the date falls on a disabled date.
/// Defaults to: <c>"Disabled"</c>
/// </summary>
public JsString disabledDatesText;
/// <summary>
/// An array of days to disable, 0 based. Some examples:
/// <code>// disable Sunday and Saturday:
/// disabledDays: [0, 6]
/// // disable weekdays:
/// disabledDays: [1,2,3,4,5]
/// </code>
/// </summary>
public JsNumber disabledDays;
/// <summary>
/// The tooltip to display when the date falls on a disabled day.
/// Defaults to: <c>"Disabled"</c>
/// </summary>
public JsString disabledDaysText;
/// <summary>
/// The default date format string which can be overriden for localization support. The format must be valid
/// according to Ext.Date.parse.
/// Defaults to: <c>"m/d/Y"</c>
/// </summary>
public JsString format;
/// <summary>
/// The error text to display when the date in the cell is after maxValue.
/// Defaults to: <c>"The date in this field must be equal to or before {0}"</c>
/// </summary>
public JsString maxText;
/// <summary>
/// The maximum allowed date. Can be either a Javascript date object or a string date in a valid format.
/// </summary>
public object maxValue;
/// <summary>
/// The error text to display when the date in the cell is before minValue.
/// Defaults to: <c>"The date in this field must be equal to or after {0}"</c>
/// </summary>
public JsString minText;
/// <summary>
/// The minimum allowed date. Can be either a Javascript date object or a string date in a valid format.
/// </summary>
public object minValue;
/// <summary>
/// false to hide the footer area of the Date picker containing the Today button and disable the keyboard handler for
/// spacebar that selects the current date.
/// Defaults to: <c>true</c>
/// </summary>
public bool showToday;
/// <summary>
/// Day index at which the week should begin, 0-based.
/// Defaults to <c>0</c> (Sunday).
/// </summary>
public JsNumber startDay;
/// <summary>
/// The date format string which will be submitted to the server. The format must be valid according to
/// Ext.Date.parse.
/// Defaults to <see cref="Ext.form.field.DateConfig.format">format</see>.
/// </summary>
public JsString submitFormat;
/// <summary>
/// True to enforce strict date parsing to prevent the default Javascript "date rollover".
/// Defaults to the useStrict parameter set on Ext.Date
/// See Ext.Date.parse.
/// </summary>
public bool useStrict;
public DateConfig(params object[] args){}
}
#endregion
#region DateEvents
/// <inheritdocs />
[JsType(JsMode.Json, Export=false, OmitOptionalParameters=true)]
public partial class DateEvents : PickerEvents
{
public DateEvents(params object[] args){}
}
#endregion
}
| |
using System;
using System.Data;
using System.Data.OleDb;
using System.Xml;
using System.Collections;
using System.Collections.Generic;
using Epi.Collections;
using System.IO;
using System.Text;
using Epi.Data;
using System.Globalization;
using Epi.Data.Office.Forms;
using System.Diagnostics;
namespace Epi.Data.Office
{
/// <summary>
/// Concrete Microsoft Excel database implementation
/// </summary>
public partial class ExcelWorkbook : OleDbDatabase
{
/// <summary>
/// Default Constructor
/// </summary>
public ExcelWorkbook() : base() { }
#region Database Implementation
/// <summary>
/// Set Access database file path
/// </summary>
/// <param name="filePath"></param>
public override void SetDataSourceFilePath(string filePath)
{
this.ConnectionString = filePath;
}
/// <summary>
/// Returns the full name of the data source
/// </summary>
public override string FullName // Implements Database.FullName
{
get
{
return "[MS Excel] " + Location ?? "";
}
}
protected override OleDbConnection GetNativeConnection(string connectionString)
{
OleDbConnectionStringBuilder oleDBCnnStrBuilder = new OleDbConnectionStringBuilder(ConnectionString);
oleDBCnnStrBuilder.Provider = "Microsoft.Jet.OLEDB.4.0";
oleDBCnnStrBuilder.Add("Mode","ReadWrite");
if(false == connectionString.Contains("Extended Properties"))
{
oleDBCnnStrBuilder.Add("Extended Properties", "Excel 8.0;HDR=Yes");
}
return new OleDbConnection(oleDBCnnStrBuilder.ToString());
}
/// <summary>
/// Compact the database
/// << may only apply to Access databases >>
/// </summary>
public override bool CompactDatabase()
{
bool success = true;
Type typeJRO = Type.GetTypeFromProgID("JRO.JetEngine");
if (typeJRO == null)
{
throw new InvalidOperationException("JRO.JetEngine can not be created... please check if it is installed");
}
object JRO = Activator.CreateInstance(typeJRO);
string dataSource = DataSource;
string dataSource_Temp = dataSource.Insert(dataSource.LastIndexOf('.'), "_Temp");
object[] paramObjects = new object[]
{
OleConnectionString,
"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\"" + dataSource_Temp + "\";Jet OLEDB:Engine Type=5"
};
try
{
JRO.GetType().InvokeMember
(
"CompactDatabase",
System.Reflection.BindingFlags.InvokeMethod,
null,
JRO,
paramObjects
);
}
finally
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(JRO);
JRO = null;
}
if (success)
{
System.IO.File.Delete(dataSource);
System.IO.File.Move(dataSource_Temp, dataSource);
}
return success;
}
/// <summary>
/// Creates a table with the given columns
/// </summary>
/// <param name="tableName">Table name to be created</param>
/// <param name="columns">List of columns</param>
public override void CreateTable(string tableName, List<TableColumn> columns)
{
StringBuilder sb = new StringBuilder();
sb.Append("create table ");
sb.Append(this.InsertInEscape(tableName));
sb.Append(" ( ");
foreach (TableColumn column in columns)
{
//if (column.Name.ToLowerInvariant() != "uniquekey")
//{
if (column.IsIdentity)
{
sb.Append("[");
sb.Append(column.Name);
sb.Append("]");
sb.Append(" ");
sb.Append(" COUNTER ");
}
else
{
sb.Append("[");
sb.Append(column.Name);
sb.Append("]");
sb.Append(" ");
if (GetDbSpecificColumnType(column.DataType).Equals("text") && column.Length.HasValue && column.Length.Value > 255)
{
sb.Append("memo");
}
else
{
sb.Append(GetDbSpecificColumnType(column.DataType));
}
}
//}
//else
//{
// //UniqueKey exists
// sb.Append("[");
// sb.Append(column.Name);
// sb.Append("] counter ");
//}
if (column.Length != null)
{
if (GetDbSpecificColumnType(column.DataType).Equals("text") && column.Length.HasValue && column.Length.Value <= 255 && column.Length.Value > 0)
{
sb.Append("(");
sb.Append(column.Length.Value.ToString());
sb.Append(") ");
}
}
if (!column.AllowNull)
{
sb.Append(" NOT ");
}
sb.Append(" null ");
if (column.IsPrimaryKey)
{
sb.Append(" constraint");
sb.Append(" PK_");
sb.Append(column.Name);
sb.Append("_");
sb.Append(tableName);
sb.Append(" primary key ");
}
if (!string.IsNullOrEmpty(column.ForeignKeyColumnName) && !string.IsNullOrEmpty(column.ForeignKeyTableName))
{
sb.Append(" references ");
sb.Append(column.ForeignKeyTableName);
sb.Append("([");
sb.Append(column.ForeignKeyColumnName);
sb.Append("]) ");
if (column.CascadeDelete)
{
sb.Append(" on delete cascade");
}
}
sb.Append(", ");
}
sb.Remove(sb.Length - 2, 2);
sb.Append(") ");
ExecuteNonQuery(CreateQuery(sb.ToString()));
}
#endregion
#region Private Members
/// <summary>
/// Gets the database-specific column data type.
/// </summary>
/// <param name="dataType">An extension of the System.Data.DbType that adds StringLong (Text, Memo) data type that Epi Info commonly uses.</param>
/// <returns>Database-specific column data type.</returns>
public override string GetDbSpecificColumnType(GenericDbColumnType dataType)
{
switch (dataType)
{
case GenericDbColumnType.AnsiString:
case GenericDbColumnType.AnsiStringFixedLength:
return AccessColumnType.Text;
case GenericDbColumnType.Binary:
return "binary";
case GenericDbColumnType.Boolean:
return AccessColumnType.YesNo;
case GenericDbColumnType.Byte:
return "byte";
case GenericDbColumnType.Currency:
return AccessColumnType.Currency;
case GenericDbColumnType.Date:
case GenericDbColumnType.DateTime:
case GenericDbColumnType.Time:
return "datetime";
case GenericDbColumnType.Decimal:
case GenericDbColumnType.Double:
return "double";
case GenericDbColumnType.Guid:
return "text";
case GenericDbColumnType.Int16:
case GenericDbColumnType.UInt16:
return "SHORT";
case GenericDbColumnType.Int32:
case GenericDbColumnType.UInt32:
return "integer";
case GenericDbColumnType.Int64:
case GenericDbColumnType.UInt64:
return "LONG";
case GenericDbColumnType.Object:
case GenericDbColumnType.Image:
return "LONGBINARY";
case GenericDbColumnType.SByte:
return "byte";
case GenericDbColumnType.Single:
return "single";
case GenericDbColumnType.String:
case GenericDbColumnType.StringFixedLength:
return "text";
case GenericDbColumnType.StringLong:
case GenericDbColumnType.Xml:
return "MEMO";
case GenericDbColumnType.VarNumeric:
return "double";
default:
throw new GeneralException("genericDbColumnType is unknown");
}
}
/// <summary>
/// Read only attribute of connection description
/// </summary>
public override string ConnectionDescription
{
get { return "Microsoft Excel Workbook: " + Location; }
}
private bool firstRowContainsHeaderInformation = true;
public bool FirstRowContainsHeaderInformation
{
get { return firstRowContainsHeaderInformation; }
set { firstRowContainsHeaderInformation = value; }
}
/// <summary>
/// Connection String attribute
/// </summary>
public override string ConnectionString
{
get
{
OleDbConnectionStringBuilder cnnBuilder = new OleDbConnectionStringBuilder(base.ConnectionString);
cnnBuilder.Provider = "Microsoft.Jet.OLEDB.4.0";
string connection = base.ConnectionString;
if (false == connection.Contains("Extended Properties"))
{
cnnBuilder.Add("Extended Properties", "Excel 8.0;");
}
StackFrame[] frames = new StackTrace().GetFrames();
foreach (StackFrame frame in frames)
{
string methodName = frame.GetMethod().Name;
if (methodName == "GetDataTable" || methodName == "GetDataTableReader")
{
if (cnnBuilder.ConnectionString.Contains("IMEX=1") == false)
{
cnnBuilder.ConnectionString = cnnBuilder.ConnectionString.Replace("Extended Properties=\"Excel 8.0", "Extended Properties=\"Excel 8.0;IMEX=1;");
}
break;
}
}
if (FirstRowContainsHeaderInformation)
{
cnnBuilder.ConnectionString = cnnBuilder.ConnectionString.Replace("Extended Properties=\"Excel 8.0", "Extended Properties=\"Excel 8.0;HDR=Yes");
}
return cnnBuilder.ToString();
}
set
{
string connectionString;
if (Util.IsFilePath(value))
{
connectionString = ExcelWorkbook.BuildConnectionString(value, "");
}
else
{
connectionString = value;
}
base.ConnectionString = connectionString;
}
}
#endregion
public static string BuildConnectionString(string filePath, string password)
{
StringBuilder builder = new StringBuilder();
if (filePath.EndsWith(".xls", true, System.Globalization.CultureInfo.InvariantCulture))
{
builder.Append("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=");
}
builder.Append(EncodeOleDbConnectionStringValue(filePath));
builder.Append(";ReadOnly=False;Extended Properties=\"Excel 8.0;HDR=Yes\";");
// sanity check
OleDbConnectionStringBuilder connectionBuilder = new OleDbConnectionStringBuilder(builder.ToString());
return connectionBuilder.ToString();
}
/// <summary>
/// Gets the names of all tables in the database
/// </summary>
/// <returns>Names of all tables in the database</returns>
public override List<string> GetTableNames()
{
List<string> tableNames = new List<string>();
DataTable schemaTable = GetTableSchema();
foreach (DataRow row in schemaTable.Rows)
{
string tableNameCandidate = row[ColumnNames.SCHEMA_TABLE_NAME].ToString();
tableNameCandidate = tableNameCandidate.Replace("'", string.Empty);
if ((tableNameCandidate.Split('$').Length > 1) && (string.IsNullOrEmpty(tableNameCandidate.Split('$')[1])))
{
tableNames.Add(tableNameCandidate);
}
}
return tableNames;
}
/// <summary>
/// Returns Code Table names for the project
/// </summary>
/// <param name="project">Project</param>
/// <returns>DataTable</returns>
public override DataTable GetCodeTableNamesForProject(Project project)
{
List<string> tables = project.GetDataTableList();
DataSets.TableSchema.TablesDataTable codeTables = project.GetCodeTableList();
foreach (DataSets.TableSchema.TablesRow row in codeTables)
{
tables.Add(row.TABLE_NAME);
}
DataTable bindingTable = new DataTable();
bindingTable.Columns.Add(ColumnNames.NAME);
foreach (string table in tables)
{
if (!string.IsNullOrEmpty(table))
{
if (project.CollectedData.TableExists(table))
{
bindingTable.Rows.Add(new string[] { table });
}
}
}
return bindingTable;
}
/// <summary>
/// Returns code table list
/// </summary>
/// <param name="db">IDbDriver</param>
/// <returns>Epi.DataSets.TableSchema.TablesDataTable</returns>
public override Epi.DataSets.TableSchema.TablesDataTable GetCodeTableList(IDbDriver db)
{
DataSets.TableSchema.TablesDataTable tables = db.GetTableSchema();
//remove tables without prefix "code"
DataRow[] rowsFiltered = tables.Select("TABLE_NAME not like 'code%'");
foreach (DataRow rowFiltered in rowsFiltered)
{
tables.Rows.Remove(rowFiltered);
}
foreach (DataRow row in tables)
{
if (String.IsNullOrEmpty(row.ItemArray[2].ToString()))
{
//remove a row with an empty string
tables.Rows.Remove(row);
}
}
DataRow[] rowsCode = tables.Select("TABLE_NAME like 'code%'");
return tables;
}
/// <summary>
/// Identify Database
/// Note: This will need to be revisited
/// </summary>
/// <returns></returns>
public override string IdentifyDatabase()
{
return "EXCEL";
}
}
}
| |
// Copyright (c) 2010-2013 SharpDX - Alexandre Mutel
//
// 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;
#if WIN8METRO
using Windows.UI.Core;
using Windows.Graphics.Display;
using Windows.UI.Xaml.Controls;
#elif WP8
#else
using System.Windows.Forms;
#endif
using SharpDX.DXGI;
namespace SharpDX.Toolkit.Graphics
{
/// <summary>
/// Graphics presenter for SwapChain.
/// </summary>
public class SwapChainGraphicsPresenter : GraphicsPresenter
{
private RenderTarget2D backBuffer;
private SwapChain swapChain;
private int bufferCount;
public SwapChainGraphicsPresenter(GraphicsDevice device, PresentationParameters presentationParameters)
: base(device, presentationParameters)
{
PresentInterval = presentationParameters.PresentationInterval;
// Initialize the swap chain
swapChain = ToDispose(CreateSwapChain());
backBuffer = ToDispose(RenderTarget2D.New(device, swapChain.GetBackBuffer<Direct3D11.Texture2D>(0)));
}
public override RenderTarget2D BackBuffer
{
get
{
return backBuffer;
}
}
public override object NativePresenter
{
get
{
return swapChain;
}
}
public override bool IsFullScreen
{
get
{
#if WIN8METRO
return true;
#else
return swapChain.IsFullScreen;
#endif
}
set
{
#if WIN8METRO
if (!value)
{
throw new ArgumentException("Cannot switch to non-full screen in Windows RT");
}
#else
var outputIndex = PrefferedFullScreenOutputIndex;
var output = GraphicsDevice.Adapter.GetOutputAt(outputIndex);
Output currentOutput = null;
try
{
Bool isCurrentlyFullscreen;
swapChain.GetFullscreenState(out isCurrentlyFullscreen, out currentOutput);
// check if the current fullscreen monitor is the same as new one
if (isCurrentlyFullscreen == value && currentOutput != null && currentOutput.NativePointer == ((Output)output).NativePointer)
return;
}
finally
{
if (currentOutput != null)
currentOutput.Dispose();
}
bool switchToFullScreen = value;
// If going to fullscreen mode: call 1) SwapChain.ResizeTarget 2) SwapChain.IsFullScreen
var description = new ModeDescription(backBuffer.Width, backBuffer.Height, Description.RefreshRate, Description.BackBufferFormat);
if (switchToFullScreen)
{
swapChain.ResizeTarget(ref description);
swapChain.SetFullscreenState(true, output);
}
else
swapChain.IsFullScreen = false;
// call 1) SwapChain.IsFullScreen 2) SwapChain.Resize
Resize(backBuffer.Width, backBuffer.Height, backBuffer.Format);
// If going to window mode:
if (!switchToFullScreen)
{
// call 1) SwapChain.IsFullScreen 2) SwapChain.Resize
description.RefreshRate = new Rational(0, 0);
swapChain.ResizeTarget(ref description);
}
#endif
}
}
public override void Present()
{
swapChain.Present((int)PresentInterval, PresentFlags.None);
}
protected override void OnNameChanged()
{
base.OnNameChanged();
if (GraphicsDevice.IsDebugMode && swapChain != null)
{
swapChain.DebugName = Name;
}
}
public override void Resize(int width, int height, Format format)
{
base.Resize(width, height, format);
RemoveAndDispose(ref backBuffer);
swapChain.ResizeBuffers(bufferCount, width, height, format, Description.Flags);
// Recreate the back buffer
backBuffer = ToDispose(RenderTarget2D.New(GraphicsDevice, swapChain.GetBackBuffer<Direct3D11.Texture2D>(0)));
// Reinit the Viewport
DefaultViewport = new ViewportF(0, 0, backBuffer.Width, backBuffer.Height);
}
private SwapChain CreateSwapChain()
{
// Check for Window Handle parameter
if (Description.DeviceWindowHandle == null)
{
throw new ArgumentException("DeviceWindowHandle cannot be null");
}
#if WIN8METRO
return CreateSwapChainForWinRT();
#else
return CreateSwapChainForDesktop();
#endif
}
#if WIN8METRO
private SwapChain CreateSwapChainForWinRT()
{
var coreWindow = Description.DeviceWindowHandle as CoreWindow;
var swapChainBackgroundPanel = Description.DeviceWindowHandle as SwapChainBackgroundPanel;
bufferCount = 2;
var description = new SwapChainDescription1
{
// Automatic sizing
Width = Description.BackBufferWidth,
Height = Description.BackBufferHeight,
Format = SharpDX.DXGI.Format.B8G8R8A8_UNorm, // TODO: Check if we can use the Description.BackBufferFormat
Stereo = false,
SampleDescription = new SharpDX.DXGI.SampleDescription((int)Description.MultiSampleCount, 0),
Usage = Description.RenderTargetUsage,
// Use two buffers to enable flip effect.
BufferCount = bufferCount,
Scaling = SharpDX.DXGI.Scaling.Stretch,
SwapEffect = SharpDX.DXGI.SwapEffect.FlipSequential,
};
if (coreWindow != null)
{
// Creates a SwapChain from a CoreWindow pointer
using (var comWindow = new ComObject(coreWindow)) return ((DXGI.Factory2)GraphicsAdapter.Factory).CreateSwapChainForCoreWindow((Direct3D11.Device)GraphicsDevice, comWindow, ref description, null);
}
else if (swapChainBackgroundPanel != null)
{
var nativePanel = ComObject.As<ISwapChainBackgroundPanelNative>(swapChainBackgroundPanel);
// Creates the swap chain for XAML composition
var swapChain = ((DXGI.Factory2)GraphicsAdapter.Factory).CreateSwapChainForComposition((Direct3D11.Device)GraphicsDevice, ref description, null);
// Associate the SwapChainBackgroundPanel with the swap chain
nativePanel.SwapChain = swapChain;
return swapChain;
}
else
{
throw new NotSupportedException();
}
}
#elif WP8
private SwapChain CreateSwapChainForDesktop()
{
throw new NotImplementedException();
}
#else
private SwapChain CreateSwapChainForDesktop()
{
var control = Description.DeviceWindowHandle as Control;
if (control == null)
{
throw new NotSupportedException(string.Format("Form of type [{0}] is not supported. Only System.Windows.Control are supported", Description.DeviceWindowHandle != null ? Description.DeviceWindowHandle.GetType().Name : "null"));
}
bufferCount = 1;
var description = new SwapChainDescription
{
ModeDescription = new ModeDescription(Description.BackBufferWidth, Description.BackBufferHeight, Description.RefreshRate, Description.BackBufferFormat),
BufferCount = bufferCount, // TODO: Do we really need this to be configurable by the user?
OutputHandle = control.Handle,
SampleDescription = new SampleDescription((int)Description.MultiSampleCount, 0),
SwapEffect = SwapEffect.Discard,
Usage = Description.RenderTargetUsage,
IsWindowed = true,
Flags = Description.Flags,
};
var newSwapChain = new SwapChain(GraphicsAdapter.Factory, (Direct3D11.Device)GraphicsDevice, description);
if (Description.IsFullScreen)
{
// Before fullscreen switch
newSwapChain.ResizeTarget(ref description.ModeDescription);
// Switch to full screen
newSwapChain.IsFullScreen = true;
// This is really important to call ResizeBuffers AFTER switching to IsFullScreen
newSwapChain.ResizeBuffers(bufferCount, Description.BackBufferWidth, Description.BackBufferHeight, Description.BackBufferFormat, SwapChainFlags.AllowModeSwitch);
}
return newSwapChain;
}
#endif
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
namespace System.IO
{
/*
* This class is used to access a contiguous block of memory, likely outside
* the GC heap (or pinned in place in the GC heap, but a MemoryStream may
* make more sense in those cases). It's great if you have a pointer and
* a length for a section of memory mapped in by someone else and you don't
* want to copy this into the GC heap. UnmanagedMemoryStream assumes these
* two things:
*
* 1) All the memory in the specified block is readable or writable,
* depending on the values you pass to the constructor.
* 2) The lifetime of the block of memory is at least as long as the lifetime
* of the UnmanagedMemoryStream.
* 3) You clean up the memory when appropriate. The UnmanagedMemoryStream
* currently will do NOTHING to free this memory.
* 4) All calls to Write and WriteByte may not be threadsafe currently.
*
* It may become necessary to add in some sort of
* DeallocationMode enum, specifying whether we unmap a section of memory,
* call free, run a user-provided delegate to free the memory, etc.
* We'll suggest user write a subclass of UnmanagedMemoryStream that uses
* a SafeHandle subclass to hold onto the memory.
*
*/
/// <summary>
/// Stream over a memory pointer or over a SafeBuffer
/// </summary>
public class UnmanagedMemoryStream : Stream
{
private SafeBuffer _buffer;
private unsafe byte* _mem;
private long _length;
private long _capacity;
private long _position;
private long _offset;
private FileAccess _access;
private bool _isOpen;
private Task<Int32> _lastReadTask; // The last successful task returned from ReadAsync
/// <summary>
/// Creates a closed stream.
/// </summary>
// Needed for subclasses that need to map a file, etc.
protected UnmanagedMemoryStream()
{
unsafe
{
_mem = null;
}
_isOpen = false;
}
/// <summary>
/// Creates a stream over a SafeBuffer.
/// </summary>
/// <param name="buffer"></param>
/// <param name="offset"></param>
/// <param name="length"></param>
public UnmanagedMemoryStream(SafeBuffer buffer, long offset, long length)
{
Initialize(buffer, offset, length, FileAccess.Read);
}
/// <summary>
/// Creates a stream over a SafeBuffer.
/// </summary>
public UnmanagedMemoryStream(SafeBuffer buffer, long offset, long length, FileAccess access)
{
Initialize(buffer, offset, length, access);
}
/// <summary>
/// Subclasses must call this method (or the other overload) to properly initialize all instance fields.
/// </summary>
/// <param name="buffer"></param>
/// <param name="offset"></param>
/// <param name="length"></param>
/// <param name="access"></param>
protected void Initialize(SafeBuffer buffer, long offset, long length, FileAccess access)
{
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer));
}
if (offset < 0)
{
throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (length < 0)
{
throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (buffer.ByteLength < (ulong)(offset + length))
{
throw new ArgumentException(SR.Argument_InvalidSafeBufferOffLen);
}
if (access < FileAccess.Read || access > FileAccess.ReadWrite)
{
throw new ArgumentOutOfRangeException(nameof(access));
}
Contract.EndContractBlock();
if (_isOpen)
{
throw new InvalidOperationException(SR.InvalidOperation_CalledTwice);
}
// check for wraparound
unsafe
{
byte* pointer = null;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
buffer.AcquirePointer(ref pointer);
if ((pointer + offset + length) < pointer)
{
throw new ArgumentException(SR.ArgumentOutOfRange_UnmanagedMemStreamWrapAround);
}
}
finally
{
if (pointer != null)
{
buffer.ReleasePointer();
}
}
}
_offset = offset;
_buffer = buffer;
_length = length;
_capacity = length;
_access = access;
_isOpen = true;
}
/// <summary>
/// Creates a stream over a byte*.
/// </summary>
[CLSCompliant(false)]
public unsafe UnmanagedMemoryStream(byte* pointer, long length)
{
Initialize(pointer, length, length, FileAccess.Read);
}
/// <summary>
/// Creates a stream over a byte*.
/// </summary>
[CLSCompliant(false)]
public unsafe UnmanagedMemoryStream(byte* pointer, long length, long capacity, FileAccess access)
{
Initialize(pointer, length, capacity, access);
}
/// <summary>
/// Subclasses must call this method (or the other overload) to properly initialize all instance fields.
/// </summary>
[CLSCompliant(false)]
protected unsafe void Initialize(byte* pointer, long length, long capacity, FileAccess access)
{
if (pointer == null)
throw new ArgumentNullException(nameof(pointer));
if (length < 0 || capacity < 0)
throw new ArgumentOutOfRangeException((length < 0) ? nameof(length) : nameof(capacity), SR.ArgumentOutOfRange_NeedNonNegNum);
if (length > capacity)
throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_LengthGreaterThanCapacity);
Contract.EndContractBlock();
// Check for wraparound.
if (((byte*)((long)pointer + capacity)) < pointer)
throw new ArgumentOutOfRangeException(nameof(capacity), SR.ArgumentOutOfRange_UnmanagedMemStreamWrapAround);
if (access < FileAccess.Read || access > FileAccess.ReadWrite)
throw new ArgumentOutOfRangeException(nameof(access), SR.ArgumentOutOfRange_Enum);
if (_isOpen)
throw new InvalidOperationException(SR.InvalidOperation_CalledTwice);
_mem = pointer;
_offset = 0;
_length = length;
_capacity = capacity;
_access = access;
_isOpen = true;
}
/// <summary>
/// Returns true if the stream can be read; otherwise returns false.
/// </summary>
public override bool CanRead
{
[Pure]
get { return _isOpen && (_access & FileAccess.Read) != 0; }
}
/// <summary>
/// Returns true if the stream can seek; otherwise returns false.
/// </summary>
public override bool CanSeek
{
[Pure]
get { return _isOpen; }
}
/// <summary>
/// Returns true if the stream can be written to; otherwise returns false.
/// </summary>
public override bool CanWrite
{
[Pure]
get { return _isOpen && (_access & FileAccess.Write) != 0; }
}
/// <summary>
/// Closes the stream. The stream's memory needs to be dealt with separately.
/// </summary>
/// <param name="disposing"></param>
protected override void Dispose(bool disposing)
{
_isOpen = false;
unsafe { _mem = null; }
// Stream allocates WaitHandles for async calls. So for correctness
// call base.Dispose(disposing) for better perf, avoiding waiting
// for the finalizers to run on those types.
base.Dispose(disposing);
}
/// <summary>
/// Since it's a memory stream, this method does nothing.
/// </summary>
public override void Flush()
{
if (!_isOpen) throw Error.GetStreamIsClosed();
}
/// <summary>
/// Since it's a memory stream, this method does nothing specific.
/// </summary>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public override Task FlushAsync(CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
return Task.FromCanceled(cancellationToken);
try
{
Flush();
return Task.CompletedTask;
}
catch (Exception ex)
{
return Task.FromException(ex);
}
}
/// <summary>
/// Number of bytes in the stream.
/// </summary>
public override long Length
{
get
{
if (!_isOpen) throw Error.GetStreamIsClosed();
return Interlocked.Read(ref _length);
}
}
/// <summary>
/// Number of bytes that can be written to the stream.
/// </summary>
public long Capacity
{
get
{
if (!_isOpen) throw Error.GetStreamIsClosed();
return _capacity;
}
}
/// <summary>
/// ReadByte will read byte at the Position in the stream
/// </summary>
public override long Position
{
get
{
if (!CanSeek) throw Error.GetStreamIsClosed();
Contract.EndContractBlock();
return Interlocked.Read(ref _position);
}
set
{
if (value < 0) throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_NeedNonNegNum);
if (!CanSeek) throw Error.GetStreamIsClosed();
Contract.EndContractBlock();
Interlocked.Exchange(ref _position, value);
}
}
/// <summary>
/// Pointer to memory at the current Position in the stream.
/// </summary>
[CLSCompliant(false)]
public unsafe byte* PositionPointer
{
get
{
if (_buffer != null) throw new NotSupportedException(SR.NotSupported_UmsSafeBuffer);
if (!_isOpen) throw Error.GetStreamIsClosed();
// Use a temp to avoid a race
long pos = Interlocked.Read(ref _position);
if (pos > _capacity)
throw new IndexOutOfRangeException(SR.IndexOutOfRange_UMSPosition);
byte* ptr = _mem + pos;
return ptr;
}
set
{
if (_buffer != null) throw new NotSupportedException(SR.NotSupported_UmsSafeBuffer);
if (!_isOpen) throw Error.GetStreamIsClosed();
if (value < _mem)
throw new IOException(SR.IO_SeekBeforeBegin);
long newPosition = (long)value - (long)_mem;
if (newPosition < 0)
throw new ArgumentOutOfRangeException("offset", SR.ArgumentOutOfRange_UnmanagedMemStreamLength);
Interlocked.Exchange(ref _position, newPosition);
}
}
/// <summary>
/// Reads bytes from stream and puts them into the buffer
/// </summary>
/// <param name="buffer">Buffer to read the bytes to.</param>
/// <param name="offset">Starting index in the buffer.</param>
/// <param name="count">Maximum number of bytes to read.</param>
/// <returns>Number of bytes actually read.</returns>
public override int Read(byte[] buffer, int offset, int count)
{
if (buffer == null)
throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
if (offset < 0)
throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum);
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
if (buffer.Length - offset < count)
throw new ArgumentException(SR.Argument_InvalidOffLen);
Contract.EndContractBlock(); // Keep this in sync with contract validation in ReadAsync
if (!_isOpen) throw Error.GetStreamIsClosed();
if (!CanRead) throw Error.GetReadNotSupported();
// Use a local variable to avoid a race where another thread
// changes our position after we decide we can read some bytes.
long pos = Interlocked.Read(ref _position);
long len = Interlocked.Read(ref _length);
long n = len - pos;
if (n > count)
n = count;
if (n <= 0)
return 0;
int nInt = (int)n; // Safe because n <= count, which is an Int32
if (nInt < 0)
return 0; // _position could be beyond EOF
Debug.Assert(pos + nInt >= 0, "_position + n >= 0"); // len is less than 2^63 -1.
unsafe
{
fixed (byte* pBuffer = buffer)
{
if (_buffer != null)
{
byte* pointer = null;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
_buffer.AcquirePointer(ref pointer);
Buffer.Memcpy(pBuffer + offset, pointer + pos + _offset, nInt);
}
finally
{
if (pointer != null)
{
_buffer.ReleasePointer();
}
}
}
else
{
Buffer.Memcpy(pBuffer + offset, _mem + pos, nInt);
}
}
}
Interlocked.Exchange(ref _position, pos + n);
return nInt;
}
/// <summary>
/// Reads bytes from stream and puts them into the buffer
/// </summary>
/// <param name="buffer">Buffer to read the bytes to.</param>
/// <param name="offset">Starting index in the buffer.</param>
/// <param name="count">Maximum number of bytes to read.</param>
/// <param name="cancellationToken">Token that can be used to cancel this operation.</param>
/// <returns>Task that can be used to access the number of bytes actually read.</returns>
public override Task<Int32> ReadAsync(Byte[] buffer, Int32 offset, Int32 count, CancellationToken cancellationToken)
{
if (buffer == null)
throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
if (offset < 0)
throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum);
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
if (buffer.Length - offset < count)
throw new ArgumentException(SR.Argument_InvalidOffLen);
Contract.EndContractBlock(); // contract validation copied from Read(...)
if (cancellationToken.IsCancellationRequested)
return Task.FromCanceled<Int32>(cancellationToken);
try
{
Int32 n = Read(buffer, offset, count);
Task<Int32> t = _lastReadTask;
return (t != null && t.Result == n) ? t : (_lastReadTask = Task.FromResult<Int32>(n));
}
catch (Exception ex)
{
Debug.Assert(!(ex is OperationCanceledException));
return Task.FromException<Int32>(ex);
}
}
/// <summary>
/// Returns the byte at the stream current Position and advances the Position.
/// </summary>
/// <returns></returns>
public override int ReadByte()
{
if (!_isOpen) throw Error.GetStreamIsClosed();
if (!CanRead) throw Error.GetReadNotSupported();
long pos = Interlocked.Read(ref _position); // Use a local to avoid a race condition
long len = Interlocked.Read(ref _length);
if (pos >= len)
return -1;
Interlocked.Exchange(ref _position, pos + 1);
int result;
if (_buffer != null)
{
unsafe
{
byte* pointer = null;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
_buffer.AcquirePointer(ref pointer);
result = *(pointer + pos + _offset);
}
finally
{
if (pointer != null)
{
_buffer.ReleasePointer();
}
}
}
}
else
{
unsafe
{
result = _mem[pos];
}
}
return result;
}
/// <summary>
/// Advanced the Position to specific location in the stream.
/// </summary>
/// <param name="offset">Offset from the loc parameter.</param>
/// <param name="loc">Origin for the offset parameter.</param>
/// <returns></returns>
public override long Seek(long offset, SeekOrigin loc)
{
if (!_isOpen) throw Error.GetStreamIsClosed();
switch (loc)
{
case SeekOrigin.Begin:
if (offset < 0)
throw new IOException(SR.IO_SeekBeforeBegin);
Interlocked.Exchange(ref _position, offset);
break;
case SeekOrigin.Current:
long pos = Interlocked.Read(ref _position);
if (offset + pos < 0)
throw new IOException(SR.IO_SeekBeforeBegin);
Interlocked.Exchange(ref _position, offset + pos);
break;
case SeekOrigin.End:
long len = Interlocked.Read(ref _length);
if (len + offset < 0)
throw new IOException(SR.IO_SeekBeforeBegin);
Interlocked.Exchange(ref _position, len + offset);
break;
default:
throw new ArgumentException(SR.Argument_InvalidSeekOrigin);
}
long finalPos = Interlocked.Read(ref _position);
Debug.Assert(finalPos >= 0, "_position >= 0");
return finalPos;
}
/// <summary>
/// Sets the Length of the stream.
/// </summary>
/// <param name="value"></param>
public override void SetLength(long value)
{
if (value < 0)
throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_NeedNonNegNum);
Contract.EndContractBlock();
if (_buffer != null)
throw new NotSupportedException(SR.NotSupported_UmsSafeBuffer);
if (!_isOpen) throw Error.GetStreamIsClosed();
if (!CanWrite) throw Error.GetWriteNotSupported();
if (value > _capacity)
throw new IOException(SR.IO_FixedCapacity);
long pos = Interlocked.Read(ref _position);
long len = Interlocked.Read(ref _length);
if (value > len)
{
unsafe
{
Buffer.ZeroMemory(_mem + len, value - len);
}
}
Interlocked.Exchange(ref _length, value);
if (pos > value)
{
Interlocked.Exchange(ref _position, value);
}
}
/// <summary>
/// Writes buffer into the stream
/// </summary>
/// <param name="buffer">Buffer that will be written.</param>
/// <param name="offset">Starting index in the buffer.</param>
/// <param name="count">Number of bytes to write.</param>
public override void Write(byte[] buffer, int offset, int count)
{
if (buffer == null)
throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
if (offset < 0)
throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum);
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
if (buffer.Length - offset < count)
throw new ArgumentException(SR.Argument_InvalidOffLen);
Contract.EndContractBlock(); // Keep contract validation in sync with WriteAsync(..)
if (!_isOpen) throw Error.GetStreamIsClosed();
if (!CanWrite) throw Error.GetWriteNotSupported();
long pos = Interlocked.Read(ref _position); // Use a local to avoid a race condition
long len = Interlocked.Read(ref _length);
long n = pos + count;
// Check for overflow
if (n < 0)
throw new IOException(SR.IO_StreamTooLong);
if (n > _capacity)
{
throw new NotSupportedException(SR.IO_FixedCapacity);
}
if (_buffer == null)
{
// Check to see whether we are now expanding the stream and must
// zero any memory in the middle.
if (pos > len)
{
unsafe
{
Buffer.ZeroMemory(_mem + len, pos - len);
}
}
// set length after zeroing memory to avoid race condition of accessing unzeroed memory
if (n > len)
{
Interlocked.Exchange(ref _length, n);
}
}
unsafe
{
fixed (byte* pBuffer = buffer)
{
if (_buffer != null)
{
long bytesLeft = _capacity - pos;
if (bytesLeft < count)
{
throw new ArgumentException(SR.Arg_BufferTooSmall);
}
byte* pointer = null;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
_buffer.AcquirePointer(ref pointer);
Buffer.Memcpy(pointer + pos + _offset, pBuffer + offset, count);
}
finally
{
if (pointer != null)
{
_buffer.ReleasePointer();
}
}
}
else
{
Buffer.Memcpy(_mem + pos, pBuffer + offset, count);
}
}
}
Interlocked.Exchange(ref _position, n);
return;
}
/// <summary>
/// Writes buffer into the stream. The operation completes synchronously.
/// </summary>
/// <param name="buffer">Buffer that will be written.</param>
/// <param name="offset">Starting index in the buffer.</param>
/// <param name="count">Number of bytes to write.</param>
/// <param name="cancellationToken">Token that can be used to cancel the operation.</param>
/// <returns>Task that can be awaited </returns>
public override Task WriteAsync(Byte[] buffer, Int32 offset, Int32 count, CancellationToken cancellationToken)
{
if (buffer == null)
throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
if (offset < 0)
throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum);
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
if (buffer.Length - offset < count)
throw new ArgumentException(SR.Argument_InvalidOffLen);
Contract.EndContractBlock(); // contract validation copied from Write(..)
if (cancellationToken.IsCancellationRequested)
return Task.FromCanceled(cancellationToken);
try
{
Write(buffer, offset, count);
return Task.CompletedTask;
}
catch (Exception ex)
{
Debug.Assert(!(ex is OperationCanceledException));
return Task.FromException(ex);
}
}
/// <summary>
/// Writes a byte to the stream and advances the current Position.
/// </summary>
/// <param name="value"></param>
public override void WriteByte(byte value)
{
if (!_isOpen) throw Error.GetStreamIsClosed();
if (!CanWrite) throw Error.GetWriteNotSupported();
long pos = Interlocked.Read(ref _position); // Use a local to avoid a race condition
long len = Interlocked.Read(ref _length);
long n = pos + 1;
if (pos >= len)
{
// Check for overflow
if (n < 0)
throw new IOException(SR.IO_StreamTooLong);
if (n > _capacity)
throw new NotSupportedException(SR.IO_FixedCapacity);
// Check to see whether we are now expanding the stream and must
// zero any memory in the middle.
// don't do if created from SafeBuffer
if (_buffer == null)
{
if (pos > len)
{
unsafe
{
Buffer.ZeroMemory(_mem + len, pos - len);
}
}
// set length after zeroing memory to avoid race condition of accessing unzeroed memory
Interlocked.Exchange(ref _length, n);
}
}
if (_buffer != null)
{
unsafe
{
byte* pointer = null;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
_buffer.AcquirePointer(ref pointer);
*(pointer + pos + _offset) = value;
}
finally
{
if (pointer != null)
{
_buffer.ReleasePointer();
}
}
}
}
else
{
unsafe
{
_mem[pos] = value;
}
}
Interlocked.Exchange(ref _position, n);
}
}
}
| |
// Copyright (c) 2012-2014 Sharpex2D - Kevin Scholz (ThuCommix)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the 'Software'), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.Diagnostics;
using System.Threading;
using System.Windows.Forms;
namespace Sharpex2D.Surface
{
[Developer("ThuCommix", "developer@sharpex2d.de")]
[TestState(TestState.Tested)]
public class RenderTarget : IComponent, IDisposable
{
private bool _isDisposed;
/// <summary>
/// Initializes a new RenderTarget class.
/// </summary>
/// <param name="handle">The WindowHandle.</param>
internal RenderTarget(IntPtr handle)
{
Handle = handle;
Window = new GameWindow(handle);
Window.FullscreenChanged += WindowFullscreenChanged;
Window.ScreenSizeChanged += WindowScreenSizeChanged;
}
/// <summary>
/// Gets the WindowHandle.
/// </summary>
public IntPtr Handle { get; private set; }
/// <summary>
/// Gets the ISurfaceControl.
/// </summary>
public GameWindow Window { private set; get; }
/// <summary>
/// A value indicating whether the surface is running in fullscreen.
/// </summary>
public bool IsFullscreen
{
get { return Window.IsFullscreen; }
}
/// <summary>
/// A value indicating whether the RenderTarget is valid.
/// </summary>
public bool IsValid
{
get
{
#if Windows
return NativeMethods.IsWindow(Handle);
#elif Mono
return Control.FromHandle(Handle) is Form;
#endif
}
}
/// <summary>
/// Gets the RenderTarget associated with the current process.
/// </summary>
public static RenderTarget Default
{
get
{
IntPtr handle = Process.GetCurrentProcess().MainWindowHandle;
#if Windows
if (NativeMethods.IsWindow(handle))
{
return new RenderTarget(handle);
}
#elif Mono
if(Control.FromHandle(handle) is Form)
{
return new RenderTarget(handle);
}
#endif
throw new InvalidOperationException("Could not get the handle associated with the current process.");
}
}
#region IComponent Implementation
/// <summary>
/// Sets or gets the Guid of the Component.
/// </summary>
public Guid Guid
{
get { return new Guid("0F73D6D0-7CE8-4A77-A184-BE93E77E86B5"); }
}
#endregion
/// <summary>
/// ScreenSizeChanged event.
/// </summary>
public event ScreenSizeEventHandler ScreenSizeChanged;
/// <summary>
/// FullscreenChanged event.
/// </summary>
public event ScreenSizeEventHandler FullscreenChanged;
/// <summary>
/// WindowScreenChanged event.
/// </summary>
/// <param name="sender">The Sender.</param>
/// <param name="e">The EventArgs.</param>
private void WindowScreenSizeChanged(object sender, EventArgs e)
{
if (ScreenSizeChanged != null)
{
ScreenSizeChanged(this, EventArgs.Empty);
}
}
/// <summary>
/// WindowFullscreenChanged event.
/// </summary>
/// <param name="sender">The Sender.</param>
/// <param name="e">The EventArgs.</param>
private void WindowFullscreenChanged(object sender, EventArgs e)
{
if (FullscreenChanged != null)
{
FullscreenChanged(this, EventArgs.Empty);
}
}
/// <summary>
/// Create a new RenderTarget from a specified handle.
/// </summary>
/// <param name="handle">The Handle.</param>
/// <returns>RenderTarget</returns>
public static RenderTarget FromHandle(IntPtr handle)
{
#if Windows
if (NativeMethods.IsWindow(handle))
{
return new RenderTarget(handle);
}
#elif Mono
if(Control.FromHandle(handle) is Form)
{
return new RenderTarget(handle);
}
#endif
throw new InvalidOperationException("The given Handle is not a window.");
}
/// <summary>
/// Creates a new RenderTarget.
/// </summary>
/// <returns>RenderTarget</returns>
public static RenderTarget Create()
{
var surface = new Form();
new Thread(() => Application.Run(surface)).Start();
while (!surface.IsHandleCreated)
{
}
IntPtr handle = IntPtr.Zero;
MethodInvoker br = delegate { handle = surface.Handle; };
surface.Invoke(br);
return new RenderTarget(handle);
}
#region IDisposable Implementation
/// <summary>
/// Disposes the object.
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Disposes the object.
/// </summary>
/// <param name="disposing">Indicates whether managed resources should be disposed.</param>
protected virtual void Dispose(bool disposing)
{
if (!_isDisposed)
{
_isDisposed = true;
if (disposing)
{
Window.Dispose();
}
}
}
#endregion
}
}
| |
#region Copyright & License
//
// Author: Ian Davis <ian.f.davis@gmail.com> Copyright (c) 2007, Ian Davs
//
// Portions of this software were developed for NUnit. See NOTICE.txt for more
// information.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy of
// the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.
//
#endregion
using System;
using System.Collections;
using System.Collections.Generic;
namespace Ensurance.Constraints
{
/// <summary>
/// ConstraintBuilder is used to resolve the Not and All properties, which
/// serve as prefix operators for constraints. With the addition of an
/// operand stack, And and Or could be supported, but we have left them out
/// in favor of a simpler, more type-safe implementation. Use the & and
/// | operator overloads to combine constraints.
/// </summary>
public class ConstraintBuilder
{
private Stack<string> _opnds = new Stack<string>();
private Stack<Op> _ops = new Stack<Op>();
/// <summary>
/// Implicitly convert ConstraintBuilder to an actual Constraint at the
/// point where the syntax demands it.
/// </summary>
/// <param name="builder"></param>
/// <returns></returns>
public static implicit operator Constraint( ConstraintBuilder builder )
{
return builder.Resolve();
}
#region Constraints Without Arguments
/// <summary>
/// Resolves the chain of constraints using EqualConstraint(null) as
/// base.
/// </summary>
public Constraint Null
{
get { return Resolve( new EqualConstraint( null ) ); }
}
/// <summary>
/// Resolves the chain of constraints using EqualConstraint(true) as
/// base.
/// </summary>
public Constraint True
{
get { return Resolve( new EqualConstraint( true ) ); }
}
/// <summary>
/// Resolves the chain of constraints using EqualConstraint(false) as
/// base.
/// </summary>
public Constraint False
{
get { return Resolve( new EqualConstraint( false ) ); }
}
/// <summary>
/// Resolves the chain of constraints using Is.NaN as base.
/// </summary>
public Constraint NaN
{
get { return Resolve( new EqualConstraint( double.NaN ) ); }
}
/// <summary>
/// Resolves the chain of constraints using Is.Empty as base.
/// </summary>
public Constraint Empty
{
get { return Resolve( new EmptyConstraint() ); }
}
/// <summary>
/// Resolves the chain of constraints using Is.Unique as base.
/// </summary>
public Constraint Unique
{
get { return Resolve( new UniqueItemsConstraint() ); }
}
#endregion
#region Constraints with an expected value
#region Equality and Identity
/// <summary>
/// Resolves the chain of constraints using an EqualConstraint as base.
/// </summary>
public Constraint EqualTo( object expected )
{
return Resolve( new EqualConstraint( expected ) );
}
/// <summary>
/// Resolves the chain of constraints using a SameAsConstraint as base.
/// </summary>
public Constraint SameAs( object expected )
{
return Resolve( new SameAsConstraint( expected ) );
}
#endregion
#region Comparison Constraints
/// <summary>
/// Resolves the chain of constraints using a LessThanConstraint as
/// base.
/// </summary>
public Constraint LessThan( IComparable expected )
{
return Resolve( new LessThanConstraint( expected ) );
}
/// <summary>
/// Resolves the chain of constraints using a GreaterThanConstraint as
/// base.
/// </summary>
public Constraint GreaterThan( IComparable expected )
{
return Resolve( new GreaterThanConstraint( expected ) );
}
/// <summary>
/// Resolves the chain of constraints using a LessThanOrEqualConstraint
/// as base.
/// </summary>
public Constraint LessThanOrEqualTo( IComparable expected )
{
return Resolve( new LessThanOrEqualConstraint( expected ) );
}
/// <summary>
/// Resolves the chain of constraints using a LessThanOrEqualConstraint
/// as base.
/// </summary>
public Constraint AtMost( IComparable expected )
{
return Resolve( new LessThanOrEqualConstraint( expected ) );
}
/// <summary>
/// Resolves the chain of constraints using a
/// GreaterThanOrEqualConstraint as base.
/// </summary>
public Constraint GreaterThanOrEqualTo( IComparable expected )
{
return Resolve( new GreaterThanOrEqualConstraint( expected ) );
}
/// <summary>
/// Resolves the chain of constraints using a
/// GreaterThanOrEqualConstraint as base.
/// </summary>
public Constraint AtLeast( IComparable expected )
{
return Resolve( new GreaterThanOrEqualConstraint( expected ) );
}
#endregion
#region Type Constraints
/// <summary>
/// Resolves the chain of constraints using an ExactTypeConstraint as
/// base.
/// </summary>
public Constraint TypeOf( Type expectedType )
{
return Resolve( new ExactTypeConstraint( expectedType ) );
}
/// <summary>
/// Resolves the chain of constraints using an InstanceOfTypeConstraint
/// as base.
/// </summary>
public Constraint InstanceOfType( Type expectedType )
{
return Resolve( new InstanceOfTypeConstraint( expectedType ) );
}
/// <summary>
/// Resolves the chain of constraints using an AssignableFromConstraint
/// as base.
/// </summary>
public Constraint AssignableFrom( Type expectedType )
{
return Resolve( new AssignableFromConstraint( expectedType ) );
}
#endregion
#region Containing Constraint
/// <summary>
/// Resolves the chain of constraints using a ContainsConstraint as
/// base. This constraint will, in turn, make use of the appropriate
/// second-level constraint, depending on the type of the actual
/// argument.
/// </summary>
public Constraint Contains( object expected )
{
return Resolve( new ContainsConstraint( expected ) );
}
/// <summary>
/// Resolves the chain of constraints using a
/// CollectionContainsConstraint as base.
/// </summary>
/// <param name="expected">The expected object</param>
public Constraint Member( object expected )
{
return Resolve( new CollectionContainsConstraint( expected ) );
}
#endregion
#region String Constraints
/// <summary>
/// Resolves the chain of constraints using a StartsWithConstraint as
/// base.
/// </summary>
public Constraint StartsWith( string substring )
{
return Resolve( new StartsWithConstraint( substring ) );
}
/// <summary>
/// Resolves the chain of constraints using a StringEndingConstraint as
/// base.
/// </summary>
public Constraint EndsWith( string substring )
{
return Resolve( new EndsWithConstraint( substring ) );
}
/// <summary>
/// Resolves the chain of constraints using a StringMatchingConstraint
/// as base.
/// </summary>
public Constraint Matches( string pattern )
{
return Resolve( new RegexConstraint( pattern ) );
}
#endregion
#region Collection Constraints
/// <summary>
/// Resolves the chain of constraints using a
/// CollectionEquivalentConstraint as base.
/// </summary>
public Constraint EquivalentTo( ICollection expected )
{
return Resolve( new CollectionEquivalentConstraint( expected ) );
}
/// <summary>
/// Resolves the chain of constraints using a
/// CollectionContainingConstraint as base.
/// </summary>
public Constraint CollectionContaining( object expected )
{
return Resolve( new CollectionContainsConstraint( expected ) );
}
/// <summary>
/// Resolves the chain of constraints using a CollectionSubsetConstraint
/// as base.
/// </summary>
public Constraint SubsetOf( ICollection expected )
{
return Resolve( new CollectionSubsetConstraint( expected ) );
}
#endregion
#region Property Constraints
/// <summary>
/// Resolves the chain of constraints using a PropertyConstraint as base
/// </summary>
public Constraint Property( string name, object expected )
{
return Resolve( new PropertyConstraint( name, new EqualConstraint( expected ) ) );
}
/// <summary>
/// Resolves the chain of constraints using a PropertyCOnstraint on
/// Length as base
/// </summary>
/// <param name="length"></param>
/// <returns></returns>
public Constraint Length( int length )
{
return Property( "Length", length );
}
/// <summary>
/// Resolves the chain of constraints using a PropertyCOnstraint on
/// Length as base
/// </summary>
/// <param name="count"></param>
/// <returns></returns>
public Constraint Count( int count )
{
return Property( "Count", count );
}
#endregion
#endregion
#region Prefix Operators
/// <summary>
/// Modifies the ConstraintBuilder by pushing a Not operator on the
/// stack.
/// </summary>
public ConstraintBuilder Not
{
get
{
_ops.Push( Op.Not );
return this;
}
}
/// <summary>
/// Modifies the ConstraintBuilder by pushing a Not operator on the
/// stack.
/// </summary>
public ConstraintBuilder No
{
get
{
_ops.Push( Op.Not );
return this;
}
}
/// <summary>
/// Modifies the ConstraintBuilder by pushing an All operator on the
/// stack.
/// </summary>
public ConstraintBuilder All
{
get
{
_ops.Push( Op.All );
return this;
}
}
/// <summary>
/// Modifies the ConstraintBuilder by pushing a Some operator on the
/// stack.
/// </summary>
public ConstraintBuilder Some
{
get
{
_ops.Push( Op.Some );
return this;
}
}
/// <summary>
/// Modifies the constraint builder by pushing All and Not operators on
/// the stack
/// </summary>
public ConstraintBuilder None
{
get
{
_ops.Push( Op.None );
return this;
}
}
/// <summary>
/// Modifies the ConstraintBuilder by pushing a Prop operator on the ops
/// stack and the name of the property on the opnds stack.
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public ConstraintBuilder Property( string name )
{
_ops.Push( Op.Prop );
_opnds.Push( name );
return this;
}
#endregion
#region Helper Methods
/// <summary>
/// Resolve a constraint that has been recognized by applying any
/// pending operators and returning the resulting Constraint.
/// </summary>
/// <returns>A constraint that incorporates all pending operators</returns>
private Constraint Resolve( Constraint constraint )
{
while ( _ops.Count > 0 )
{
switch ( _ops.Pop() )
{
case Op.Not:
constraint = new NotConstraint( constraint );
break;
case Op.All:
constraint = new AllItemsConstraint( constraint );
break;
case Op.Some:
constraint = new SomeItemsConstraint( constraint );
break;
case Op.None:
constraint = new NoItemConstraint( constraint );
break;
case Op.Prop:
constraint = new PropertyConstraint( _opnds.Pop(), constraint );
break;
}
}
return constraint;
}
private Constraint Resolve()
{
return Resolve( null );
}
#endregion
#region Nested type: Op
private enum Op
{
Not,
All,
Some,
None,
Prop,
}
#endregion
}
}
| |
// MbUnit Test Framework
//
// Copyright (c) 2004 Jonathan de Halleux
//
// 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.
//
// MbUnit HomePage: http://www.mbunit.com
// Author: Jonathan de Halleux
using MbUnit.Framework;
using System;
using System.Collections;
using System.CodeDom.Compiler;
using System.IO;
using System.Collections.Specialized;
using MbUnit.Core.Exceptions;
using Microsoft.CSharp;
using Microsoft.VisualBasic;
namespace MbUnit.Framework {
/// <summary>
/// Assertion helper for compilation.
/// </summary>
/// <remarks>
/// <para>
/// This class contains static helper methods to verify that snippets are compilable.
/// </para>
/// </remarks>
public sealed class CompilerAssert {
#region Private constructor and fields
private static ICodeCompiler csharp = new CSharpCodeProvider().CreateCompiler();
private static ICodeCompiler vb = new VBCodeProvider().CreateCompiler();
private CompilerAssert() { }
#endregion
/// <summary>
/// Gets the C# compiler from <see cref="CSharpCodeProvider"/>.
/// </summary>
/// <value>
/// C# compiler.
/// </value>
public static ICodeCompiler CSharpCompiler {
get {
return csharp;
}
}
/// <summary>
/// Gets the VB.NET compiler from <see cref="VBCodeProvider"/>.
/// </summary>
/// <value>
/// VB.NET compiler.
/// </value>
public static ICodeCompiler VBCompiler {
get {
return vb;
}
}
/// <summary>
/// Verifies that <paramref name="source"/> compiles using the provided compiler.
/// </summary>
/// <param name="compiler">Compiler instance</param>
/// <param name="source">Source code to compile</param>
public static void Compiles(ICodeCompiler compiler, string source) {
Assert.IsNotNull(compiler);
Assert.IsNotNull(source);
CompilerParameters ps = new CompilerParameters();
Compiles(compiler, ps, source);
}
/// <summary>
/// Verifies that <paramref name="source"/> compiles using the provided compiler.
/// </summary>
/// <param name="compiler">Compiler instance</param>
/// <param name="source">Source code to compile</param>
public static void Compiles(ICodeCompiler compiler, Stream source) {
Assert.IsNotNull(compiler);
Assert.IsNotNull(source);
CompilerParameters ps = new CompilerParameters();
Compiles(compiler, ps, source);
}
/// <summary>
/// Verifies that <paramref name="source"/> compiles using the provided compiler.
/// </summary>
/// <param name="compiler">Compiler instance</param>
/// <param name="references">Referenced assemblies</param>
/// <param name="source">Source code to compile</param>
public static void Compiles(ICodeCompiler compiler, StringCollection references, string source) {
Assert.IsNotNull(compiler);
Assert.IsNotNull(references);
Assert.IsNotNull(source);
CompilerParameters ps = new CompilerParameters();
foreach (string ra in references)
ps.ReferencedAssemblies.Add(ra);
Compiles(compiler, ps, source);
}
/// <summary>
/// Verifies that <paramref name="source"/> compiles using the provided compiler.
/// </summary>
/// <param name="compiler">
/// <see cref="ICodeCompiler"/> instance.</param>
/// <param name="options">Compilation options</param>
/// <param name="source">source to compile</param>
public static void Compiles(ICodeCompiler compiler, CompilerParameters options, string source) {
Assert.IsNotNull(compiler);
Assert.IsNotNull(options);
Assert.IsNotNull(source);
Compiles(compiler, options, source, false);
}
/// <summary>
/// Verifies that <paramref name="source"/> compiles using the provided compiler.
/// </summary>
/// <param name="compiler">
/// <see cref="ICodeCompiler"/> instance.</param>
/// <param name="options">Compilation options</param>
/// <param name="source">Source to compile</param>
/// <param name="throwOnWarning">
/// true if assertion should throw if any warning.
/// </param>
public static void Compiles(ICodeCompiler compiler, CompilerParameters options, string source, bool throwOnWarning) {
Assert.IsNotNull(compiler);
Assert.IsNotNull(options);
CompilerResults results = compiler.CompileAssemblyFromSource(options, source);
if (results.Errors.HasErrors)
throw new CompilationException(compiler, options, results, source);
if (throwOnWarning && results.Errors.HasWarnings)
throw new CompilationException(compiler, options, results, source);
}
/// <summary>
/// Verifies that <paramref name="source"/> compiles using the provided compiler.
/// </summary>
/// <param name="compiler">
/// <see cref="ICodeCompiler"/> instance.</param>
/// <param name="options">Compilation options</param>
/// <param name="source">Stream containing the source to compile</param>
public static void Compiles(ICodeCompiler compiler, CompilerParameters options, Stream source) {
Compiles(compiler, options, source, false);
}
/// <summary>
/// Verifies that <paramref name="source"/> compiles using the provided compiler.
/// </summary>
/// <param name="compiler">
/// <see cref="ICodeCompiler"/> instance.</param>
/// <param name="options">Compilation options</param>
/// <param name="source">Stream containing the source to compile</param>
/// <param name="throwOnWarning">
/// true if assertion should throw if any warning.
/// </param>
public static void Compiles(ICodeCompiler compiler, CompilerParameters options, Stream source, bool throwOnWarning) {
using (StreamReader sr = new StreamReader(source)) {
Compiles(compiler, options, sr.ReadToEnd(), throwOnWarning);
}
}
/// <summary>
/// Verifies that <paramref name="source"/> does not compile using the provided compiler.
/// </summary>
/// <param name="compiler">
/// <see cref="ICodeCompiler"/> instance.</param>
/// <param name="source">Source to compile</param>
public static void NotCompiles(
ICodeCompiler compiler,
string source) {
CompilerParameters options = new CompilerParameters();
NotCompiles(compiler, options, source);
}
/// <summary>
/// Verifies that <paramref name="source"/> does not compile using the provided compiler.
/// </summary>
/// <param name="compiler">
/// <see cref="ICodeCompiler"/> instance.</param>
/// <param name="source">Source to compile</param>
public static void NotCompiles(
ICodeCompiler compiler,
Stream source) {
CompilerParameters options = new CompilerParameters();
NotCompiles(compiler, options, source);
}
/// <summary>
/// Verifies that <paramref name="source"/> does not compile using the provided compiler.
/// </summary>
/// <param name="compiler">
/// <see cref="ICodeCompiler"/> instance.</param>
/// <param name="referencedAssemblies">Collection of referenced assemblies</param>
/// <param name="source">Source to compile</param>
public static void NotCompiles(
ICodeCompiler compiler,
StringCollection referencedAssemblies,
string source) {
CompilerParameters options = new CompilerParameters();
CompilerParameters ps = new CompilerParameters();
foreach (string ra in referencedAssemblies)
ps.ReferencedAssemblies.Add(ra);
NotCompiles(compiler, options, source);
}
/// <summary>
/// Verifies that <paramref name="source"/> does not compile using the provided compiler.
/// </summary>
/// <param name="compiler">
/// <see cref="ICodeCompiler"/> instance.</param>
/// <param name="options">Compilation options</param>
/// <param name="source">Source to compile</param>
public static void NotCompiles(
ICodeCompiler compiler,
CompilerParameters options,
string source) {
Assert.IncrementAssertCount();
if (compiler == null)
throw new ArgumentNullException("compiler");
if (options == null)
throw new ArgumentNullException("options");
CompilerResults results = compiler.CompileAssemblyFromSource(options, source);
if (!results.Errors.HasErrors)
throw new CompilationException(compiler, options, results, source);
}
/// <summary>
/// Verifies that <paramref name="source"/> does not compile using the provided compiler.
/// </summary>
/// <param name="compiler">
/// <see cref="ICodeCompiler"/> instance.</param>
/// <param name="options">Compilation options</param>
/// <param name="source">Source to compile</param>
public static void NotCompiles(
ICodeCompiler compiler,
CompilerParameters options,
Stream source) {
using (StreamReader sr = new StreamReader(source)) {
NotCompiles(compiler, options, sr.ReadToEnd());
}
}
/// <summary>
/// Writes the errors given in the compiler <paramref name="results"/> to the named <paramref name="writer"/>
/// </summary>
/// <param name="results">The <see cref="CompilerResults" /> generated by the compilation</param>
/// <param name="writer">The <see cref="TextWriter"/> to write the errors out to</param>
public static void DisplayErrors(CompilerResults results, TextWriter writer) {
foreach (CompilerError error in results.Errors) {
writer.Write(error);
}
}
}
}
| |
namespace AngleSharp.Core.Tests.Html
{
using AngleSharp.Dom;
using NUnit.Framework;
/// <summary>
/// Tests from https://github.com/html5lib/html5lib-tests:
/// tree-construction/tests21.dat
/// </summary>
[TestFixture]
public class CDataTests
{
[Test]
public void CDataInSvgElement()
{
var doc = (@"<svg><![CDATA[foo]]>").ToHtmlDocument();
var dochtml0 = doc.ChildNodes[0];
Assert.AreEqual(2, dochtml0.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0).Attributes.Length);
Assert.AreEqual("html", dochtml0.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0.NodeType);
var dochtml0head0 = dochtml0.ChildNodes[0];
Assert.AreEqual(0, dochtml0head0.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0head0).Attributes.Length);
Assert.AreEqual("head", dochtml0head0.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0head0.NodeType);
var dochtml0body1 = dochtml0.ChildNodes[1];
Assert.AreEqual(1, dochtml0body1.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0body1).Attributes.Length);
Assert.AreEqual("body", dochtml0body1.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0body1.NodeType);
var dochtml0body1svg0 = dochtml0body1.ChildNodes[0];
Assert.AreEqual(1, dochtml0body1svg0.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0body1svg0).Attributes.Length);
Assert.AreEqual("svg", dochtml0body1svg0.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0body1svg0.NodeType);
var dochtml0body1svg0Text0 = dochtml0body1svg0.ChildNodes[0];
Assert.AreEqual(NodeType.Text, dochtml0body1svg0Text0.NodeType);
Assert.AreEqual("foo", dochtml0body1svg0Text0.TextContent);
}
[Test]
public void CDataInMathElement()
{
var doc = (@"<math><![CDATA[foo]]>").ToHtmlDocument();
var dochtml0 = doc.ChildNodes[0];
Assert.AreEqual(2, dochtml0.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0).Attributes.Length);
Assert.AreEqual("html", dochtml0.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0.NodeType);
var dochtml0head0 = dochtml0.ChildNodes[0];
Assert.AreEqual(0, dochtml0head0.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0head0).Attributes.Length);
Assert.AreEqual("head", dochtml0head0.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0head0.NodeType);
var dochtml0body1 = dochtml0.ChildNodes[1];
Assert.AreEqual(1, dochtml0body1.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0body1).Attributes.Length);
Assert.AreEqual("body", dochtml0body1.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0body1.NodeType);
var dochtml0body1math0 = dochtml0body1.ChildNodes[0];
Assert.AreEqual(1, dochtml0body1math0.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0body1math0).Attributes.Length);
Assert.AreEqual("math", dochtml0body1math0.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0body1math0.NodeType);
var dochtml0body1math0Text0 = dochtml0body1math0.ChildNodes[0];
Assert.AreEqual(NodeType.Text, dochtml0body1math0Text0.NodeType);
Assert.AreEqual("foo", dochtml0body1math0Text0.TextContent);
}
[Test]
public void CDataInDivElement()
{
var doc = (@"<div><![CDATA[foo]]>").ToHtmlDocument();
var dochtml0 = doc.ChildNodes[0];
Assert.AreEqual(2, dochtml0.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0).Attributes.Length);
Assert.AreEqual("html", dochtml0.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0.NodeType);
var dochtml0head0 = dochtml0.ChildNodes[0];
Assert.AreEqual(0, dochtml0head0.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0head0).Attributes.Length);
Assert.AreEqual("head", dochtml0head0.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0head0.NodeType);
var dochtml0body1 = dochtml0.ChildNodes[1];
Assert.AreEqual(1, dochtml0body1.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0body1).Attributes.Length);
Assert.AreEqual("body", dochtml0body1.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0body1.NodeType);
var dochtml0body1div0 = dochtml0body1.ChildNodes[0];
Assert.AreEqual(1, dochtml0body1div0.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0body1div0).Attributes.Length);
Assert.AreEqual("div", dochtml0body1div0.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0body1div0.NodeType);
var dochtml0body1div0Comment0 = dochtml0body1div0.ChildNodes[0];
Assert.AreEqual(NodeType.Comment, dochtml0body1div0Comment0.NodeType);
Assert.AreEqual(@"[CDATA[foo]]", dochtml0body1div0Comment0.TextContent);
}
[Test]
public void CDataUnclosedInSvgElement()
{
var doc = (@"<svg><![CDATA[foo").ToHtmlDocument();
var dochtml0 = doc.ChildNodes[0];
Assert.AreEqual(2, dochtml0.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0).Attributes.Length);
Assert.AreEqual("html", dochtml0.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0.NodeType);
var dochtml0head0 = dochtml0.ChildNodes[0];
Assert.AreEqual(0, dochtml0head0.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0head0).Attributes.Length);
Assert.AreEqual("head", dochtml0head0.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0head0.NodeType);
var dochtml0body1 = dochtml0.ChildNodes[1];
Assert.AreEqual(1, dochtml0body1.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0body1).Attributes.Length);
Assert.AreEqual("body", dochtml0body1.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0body1.NodeType);
var dochtml0body1svg0 = dochtml0body1.ChildNodes[0];
Assert.AreEqual(1, dochtml0body1svg0.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0body1svg0).Attributes.Length);
Assert.AreEqual("svg", dochtml0body1svg0.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0body1svg0.NodeType);
var dochtml0body1svg0Text0 = dochtml0body1svg0.ChildNodes[0];
Assert.AreEqual(NodeType.Text, dochtml0body1svg0Text0.NodeType);
Assert.AreEqual("foo", dochtml0body1svg0Text0.TextContent);
}
[Test]
public void CDataUnclosedWithoutTextInSvgElement()
{
var doc = (@"<svg><![CDATA[").ToHtmlDocument();
var dochtml0 = doc.ChildNodes[0];
Assert.AreEqual(2, dochtml0.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0).Attributes.Length);
Assert.AreEqual("html", dochtml0.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0.NodeType);
var dochtml0head0 = dochtml0.ChildNodes[0];
Assert.AreEqual(0, dochtml0head0.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0head0).Attributes.Length);
Assert.AreEqual("head", dochtml0head0.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0head0.NodeType);
var dochtml0body1 = dochtml0.ChildNodes[1];
Assert.AreEqual(1, dochtml0body1.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0body1).Attributes.Length);
Assert.AreEqual("body", dochtml0body1.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0body1.NodeType);
var dochtml0body1svg0 = dochtml0body1.ChildNodes[0];
Assert.AreEqual(0, dochtml0body1svg0.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0body1svg0).Attributes.Length);
Assert.AreEqual("svg", dochtml0body1svg0.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0body1svg0.NodeType);
}
[Test]
public void CDataWithoutTextInSvgElement()
{
var doc = (@"<svg><![CDATA[]]>").ToHtmlDocument();
var dochtml0 = doc.ChildNodes[0];
Assert.AreEqual(2, dochtml0.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0).Attributes.Length);
Assert.AreEqual("html", dochtml0.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0.NodeType);
var dochtml0head0 = dochtml0.ChildNodes[0];
Assert.AreEqual(0, dochtml0head0.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0head0).Attributes.Length);
Assert.AreEqual("head", dochtml0head0.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0head0.NodeType);
var dochtml0body1 = dochtml0.ChildNodes[1];
Assert.AreEqual(1, dochtml0body1.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0body1).Attributes.Length);
Assert.AreEqual("body", dochtml0body1.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0body1.NodeType);
var dochtml0body1svg0 = dochtml0body1.ChildNodes[0];
Assert.AreEqual(0, dochtml0body1svg0.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0body1svg0).Attributes.Length);
Assert.AreEqual("svg", dochtml0body1svg0.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0body1svg0.NodeType);
}
[Test]
public void CDataClosedWrongInSvgElement()
{
var doc = (@"<svg><![CDATA[]] >]]>").ToHtmlDocument();
var dochtml0 = doc.ChildNodes[0];
Assert.AreEqual(2, dochtml0.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0).Attributes.Length);
Assert.AreEqual("html", dochtml0.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0.NodeType);
var dochtml0head0 = dochtml0.ChildNodes[0];
Assert.AreEqual(0, dochtml0head0.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0head0).Attributes.Length);
Assert.AreEqual("head", dochtml0head0.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0head0.NodeType);
var dochtml0body1 = dochtml0.ChildNodes[1];
Assert.AreEqual(1, dochtml0body1.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0body1).Attributes.Length);
Assert.AreEqual("body", dochtml0body1.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0body1.NodeType);
var dochtml0body1svg0 = dochtml0body1.ChildNodes[0];
Assert.AreEqual(1, dochtml0body1svg0.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0body1svg0).Attributes.Length);
Assert.AreEqual("svg", dochtml0body1svg0.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0body1svg0.NodeType);
var dochtml0body1svg0Text0 = dochtml0body1svg0.ChildNodes[0];
Assert.AreEqual(NodeType.Text, dochtml0body1svg0Text0.NodeType);
Assert.AreEqual("]] >", dochtml0body1svg0Text0.TextContent);
}
[Test]
public void CDataMissingClosingBracketInSvgElement()
{
var doc = (@"<svg><![CDATA[]]").ToHtmlDocument();
var dochtml0 = doc.ChildNodes[0];
Assert.AreEqual(2, dochtml0.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0).Attributes.Length);
Assert.AreEqual("html", dochtml0.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0.NodeType);
var dochtml0head0 = dochtml0.ChildNodes[0];
Assert.AreEqual(0, dochtml0head0.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0head0).Attributes.Length);
Assert.AreEqual("head", dochtml0head0.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0head0.NodeType);
var dochtml0body1 = dochtml0.ChildNodes[1];
Assert.AreEqual(1, dochtml0body1.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0body1).Attributes.Length);
Assert.AreEqual("body", dochtml0body1.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0body1.NodeType);
var dochtml0body1svg0 = dochtml0body1.ChildNodes[0];
Assert.AreEqual(1, dochtml0body1svg0.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0body1svg0).Attributes.Length);
Assert.AreEqual("svg", dochtml0body1svg0.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0body1svg0.NodeType);
var dochtml0body1svg0Text0 = dochtml0body1svg0.ChildNodes[0];
Assert.AreEqual(NodeType.Text, dochtml0body1svg0Text0.NodeType);
Assert.AreEqual("]]", dochtml0body1svg0Text0.TextContent);
}
[Test]
public void CDataMissingClosingBracketsInSvgElement()
{
var doc = (@"<svg><![CDATA[]").ToHtmlDocument();
var dochtml0 = doc.ChildNodes[0];
Assert.AreEqual(2, dochtml0.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0).Attributes.Length);
Assert.AreEqual("html", dochtml0.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0.NodeType);
var dochtml0head0 = dochtml0.ChildNodes[0];
Assert.AreEqual(0, dochtml0head0.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0head0).Attributes.Length);
Assert.AreEqual("head", dochtml0head0.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0head0.NodeType);
var dochtml0body1 = dochtml0.ChildNodes[1];
Assert.AreEqual(1, dochtml0body1.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0body1).Attributes.Length);
Assert.AreEqual("body", dochtml0body1.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0body1.NodeType);
var dochtml0body1svg0 = dochtml0body1.ChildNodes[0];
Assert.AreEqual(1, dochtml0body1svg0.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0body1svg0).Attributes.Length);
Assert.AreEqual("svg", dochtml0body1svg0.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0body1svg0.NodeType);
var dochtml0body1svg0Text0 = dochtml0body1svg0.ChildNodes[0];
Assert.AreEqual(NodeType.Text, dochtml0body1svg0Text0.NodeType);
Assert.AreEqual("]", dochtml0body1svg0Text0.TextContent);
}
[Test]
public void CDataMissingClosingSquareBracketInSvgElement()
{
var doc = (@"<svg><![CDATA[]>a").ToHtmlDocument();
var dochtml0 = doc.ChildNodes[0];
Assert.AreEqual(2, dochtml0.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0).Attributes.Length);
Assert.AreEqual("html", dochtml0.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0.NodeType);
var dochtml0head0 = dochtml0.ChildNodes[0];
Assert.AreEqual(0, dochtml0head0.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0head0).Attributes.Length);
Assert.AreEqual("head", dochtml0head0.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0head0.NodeType);
var dochtml0body1 = dochtml0.ChildNodes[1];
Assert.AreEqual(1, dochtml0body1.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0body1).Attributes.Length);
Assert.AreEqual("body", dochtml0body1.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0body1.NodeType);
var dochtml0body1svg0 = dochtml0body1.ChildNodes[0];
Assert.AreEqual(1, dochtml0body1svg0.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0body1svg0).Attributes.Length);
Assert.AreEqual("svg", dochtml0body1svg0.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0body1svg0.NodeType);
var dochtml0body1svg0Text0 = dochtml0body1svg0.ChildNodes[0];
Assert.AreEqual(NodeType.Text, dochtml0body1svg0Text0.NodeType);
Assert.AreEqual("]>a", dochtml0body1svg0Text0.TextContent);
}
[Test]
public void CDataWithAdditionalClosingSquareBracketInSvgElementWithStandardDoctype()
{
var doc = (@"<!DOCTYPE html><svg><![CDATA[foo]]]>").ToHtmlDocument();
var docType0 = doc.ChildNodes[0] as DocumentType;
Assert.IsNotNull(docType0);
Assert.AreEqual(NodeType.DocumentType, docType0.NodeType);
Assert.AreEqual(@"html", docType0.Name);
var dochtml1 = doc.ChildNodes[1];
Assert.AreEqual(2, dochtml1.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml1).Attributes.Length);
Assert.AreEqual("html", dochtml1.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml1.NodeType);
var dochtml1head0 = dochtml1.ChildNodes[0];
Assert.AreEqual(0, dochtml1head0.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml1head0).Attributes.Length);
Assert.AreEqual("head", dochtml1head0.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml1head0.NodeType);
var dochtml1body1 = dochtml1.ChildNodes[1];
Assert.AreEqual(1, dochtml1body1.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml1body1).Attributes.Length);
Assert.AreEqual("body", dochtml1body1.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml1body1.NodeType);
var dochtml1body1svg0 = dochtml1body1.ChildNodes[0];
Assert.AreEqual(1, dochtml1body1svg0.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml1body1svg0).Attributes.Length);
Assert.AreEqual("svg", dochtml1body1svg0.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml1body1svg0.NodeType);
var dochtml1body1svg0Text0 = dochtml1body1svg0.ChildNodes[0];
Assert.AreEqual(NodeType.Text, dochtml1body1svg0Text0.NodeType);
Assert.AreEqual("foo]", dochtml1body1svg0Text0.TextContent);
}
[Test]
public void CDataWithManyClosingSquareBracketsInSvgElementWithStandardDoctype()
{
var doc = (@"<!DOCTYPE html><svg><![CDATA[foo]]]]>").ToHtmlDocument();
var docType0 = doc.ChildNodes[0] as DocumentType;
Assert.IsNotNull(docType0);
Assert.AreEqual(NodeType.DocumentType, docType0.NodeType);
Assert.AreEqual(@"html", docType0.Name);
var dochtml1 = doc.ChildNodes[1];
Assert.AreEqual(2, dochtml1.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml1).Attributes.Length);
Assert.AreEqual("html", dochtml1.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml1.NodeType);
var dochtml1head0 = dochtml1.ChildNodes[0];
Assert.AreEqual(0, dochtml1head0.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml1head0).Attributes.Length);
Assert.AreEqual("head", dochtml1head0.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml1head0.NodeType);
var dochtml1body1 = dochtml1.ChildNodes[1];
Assert.AreEqual(1, dochtml1body1.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml1body1).Attributes.Length);
Assert.AreEqual("body", dochtml1body1.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml1body1.NodeType);
var dochtml1body1svg0 = dochtml1body1.ChildNodes[0];
Assert.AreEqual(1, dochtml1body1svg0.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml1body1svg0).Attributes.Length);
Assert.AreEqual("svg", dochtml1body1svg0.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml1body1svg0.NodeType);
var dochtml1body1svg0Text0 = dochtml1body1svg0.ChildNodes[0];
Assert.AreEqual(NodeType.Text, dochtml1body1svg0Text0.NodeType);
Assert.AreEqual("foo]]", dochtml1body1svg0Text0.TextContent);
}
[Test]
public void CDataWithManyMoreClosingSquareBracketsInSvgElementWithStandardDoctype()
{
var doc = (@"<!DOCTYPE html><svg><![CDATA[foo]]]]]>").ToHtmlDocument();
var docType0 = doc.ChildNodes[0] as DocumentType;
Assert.IsNotNull(docType0);
Assert.AreEqual(NodeType.DocumentType, docType0.NodeType);
Assert.AreEqual(@"html", docType0.Name);
var dochtml1 = doc.ChildNodes[1];
Assert.AreEqual(2, dochtml1.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml1).Attributes.Length);
Assert.AreEqual("html", dochtml1.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml1.NodeType);
var dochtml1head0 = dochtml1.ChildNodes[0];
Assert.AreEqual(0, dochtml1head0.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml1head0).Attributes.Length);
Assert.AreEqual("head", dochtml1head0.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml1head0.NodeType);
var dochtml1body1 = dochtml1.ChildNodes[1];
Assert.AreEqual(1, dochtml1body1.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml1body1).Attributes.Length);
Assert.AreEqual("body", dochtml1body1.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml1body1.NodeType);
var dochtml1body1svg0 = dochtml1body1.ChildNodes[0];
Assert.AreEqual(1, dochtml1body1svg0.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml1body1svg0).Attributes.Length);
Assert.AreEqual("svg", dochtml1body1svg0.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml1body1svg0.NodeType);
var dochtml1body1svg0Text0 = dochtml1body1svg0.ChildNodes[0];
Assert.AreEqual(NodeType.Text, dochtml1body1svg0Text0.NodeType);
Assert.AreEqual("foo]]]", dochtml1body1svg0Text0.TextContent);
}
[Test]
public void CDataInDivLocatedInForeignObjectWhichIsPlacedInSvgElement()
{
var doc = (@"<svg><foreignObject><div><![CDATA[foo]]>").ToHtmlDocument();
var dochtml0 = doc.ChildNodes[0];
Assert.AreEqual(2, dochtml0.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0).Attributes.Length);
Assert.AreEqual("html", dochtml0.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0.NodeType);
var dochtml0head0 = dochtml0.ChildNodes[0];
Assert.AreEqual(0, dochtml0head0.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0head0).Attributes.Length);
Assert.AreEqual("head", dochtml0head0.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0head0.NodeType);
var dochtml0body1 = dochtml0.ChildNodes[1];
Assert.AreEqual(1, dochtml0body1.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0body1).Attributes.Length);
Assert.AreEqual("body", dochtml0body1.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0body1.NodeType);
var dochtml0body1svg0 = dochtml0body1.ChildNodes[0];
Assert.AreEqual(1, dochtml0body1svg0.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0body1svg0).Attributes.Length);
Assert.AreEqual("svg", dochtml0body1svg0.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0body1svg0.NodeType);
var dochtml0body1svg0foreignObject0 = dochtml0body1svg0.ChildNodes[0];
Assert.AreEqual(1, dochtml0body1svg0foreignObject0.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0body1svg0foreignObject0).Attributes.Length);
Assert.AreEqual("foreignObject", dochtml0body1svg0foreignObject0.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0body1svg0foreignObject0.NodeType);
var dochtml0body1svg0foreignObject0div0 = dochtml0body1svg0foreignObject0.ChildNodes[0];
Assert.AreEqual(1, dochtml0body1svg0foreignObject0div0.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0body1svg0foreignObject0div0).Attributes.Length);
Assert.AreEqual("div", dochtml0body1svg0foreignObject0div0.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0body1svg0foreignObject0div0.NodeType);
var dochtml0body1svg0foreignObject0div0Comment0 = dochtml0body1svg0foreignObject0div0.ChildNodes[0];
Assert.AreEqual(NodeType.Comment, dochtml0body1svg0foreignObject0div0Comment0.NodeType);
Assert.AreEqual(@"[CDATA[foo]]", dochtml0body1svg0foreignObject0div0Comment0.TextContent);
}
[Test]
public void CDataWithSvgTagInSvgElement()
{
var doc = (@"<svg><![CDATA[<svg>]]>").ToHtmlDocument();
var dochtml0 = doc.ChildNodes[0];
Assert.AreEqual(2, dochtml0.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0).Attributes.Length);
Assert.AreEqual("html", dochtml0.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0.NodeType);
var dochtml0head0 = dochtml0.ChildNodes[0];
Assert.AreEqual(0, dochtml0head0.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0head0).Attributes.Length);
Assert.AreEqual("head", dochtml0head0.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0head0.NodeType);
var dochtml0body1 = dochtml0.ChildNodes[1];
Assert.AreEqual(1, dochtml0body1.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0body1).Attributes.Length);
Assert.AreEqual("body", dochtml0body1.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0body1.NodeType);
var dochtml0body1svg0 = dochtml0body1.ChildNodes[0];
Assert.AreEqual(1, dochtml0body1svg0.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0body1svg0).Attributes.Length);
Assert.AreEqual("svg", dochtml0body1svg0.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0body1svg0.NodeType);
var dochtml0body1svg0Text0 = dochtml0body1svg0.ChildNodes[0];
Assert.AreEqual(NodeType.Text, dochtml0body1svg0Text0.NodeType);
Assert.AreEqual("<svg>", dochtml0body1svg0Text0.TextContent);
}
[Test]
public void CDataWithClosingSvgTagInSvgElement()
{
var doc = (@"<svg><![CDATA[</svg>a]]>").ToHtmlDocument();
var dochtml0 = doc.ChildNodes[0];
Assert.AreEqual(2, dochtml0.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0).Attributes.Length);
Assert.AreEqual("html", dochtml0.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0.NodeType);
var dochtml0head0 = dochtml0.ChildNodes[0];
Assert.AreEqual(0, dochtml0head0.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0head0).Attributes.Length);
Assert.AreEqual("head", dochtml0head0.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0head0.NodeType);
var dochtml0body1 = dochtml0.ChildNodes[1];
Assert.AreEqual(1, dochtml0body1.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0body1).Attributes.Length);
Assert.AreEqual("body", dochtml0body1.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0body1.NodeType);
var dochtml0body1svg0 = dochtml0body1.ChildNodes[0];
Assert.AreEqual(1, dochtml0body1svg0.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0body1svg0).Attributes.Length);
Assert.AreEqual("svg", dochtml0body1svg0.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0body1svg0.NodeType);
var dochtml0body1svg0Text0 = dochtml0body1svg0.ChildNodes[0];
Assert.AreEqual(NodeType.Text, dochtml0body1svg0Text0.NodeType);
Assert.AreEqual("</svg>a", dochtml0body1svg0Text0.TextContent);
}
[Test]
public void CDataWithSvgTagUnclosedInSvgElement()
{
var doc = (@"<svg><![CDATA[<svg>a").ToHtmlDocument();
var dochtml0 = doc.ChildNodes[0];
Assert.AreEqual(2, dochtml0.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0).Attributes.Length);
Assert.AreEqual("html", dochtml0.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0.NodeType);
var dochtml0head0 = dochtml0.ChildNodes[0];
Assert.AreEqual(0, dochtml0head0.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0head0).Attributes.Length);
Assert.AreEqual("head", dochtml0head0.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0head0.NodeType);
var dochtml0body1 = dochtml0.ChildNodes[1];
Assert.AreEqual(1, dochtml0body1.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0body1).Attributes.Length);
Assert.AreEqual("body", dochtml0body1.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0body1.NodeType);
var dochtml0body1svg0 = dochtml0body1.ChildNodes[0];
Assert.AreEqual(1, dochtml0body1svg0.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0body1svg0).Attributes.Length);
Assert.AreEqual("svg", dochtml0body1svg0.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0body1svg0.NodeType);
var dochtml0body1svg0Text0 = dochtml0body1svg0.ChildNodes[0];
Assert.AreEqual(NodeType.Text, dochtml0body1svg0Text0.NodeType);
Assert.AreEqual("<svg>a", dochtml0body1svg0Text0.TextContent);
}
[Test]
public void CDataWithClosingSvgTagUnclosedInSvgElement()
{
var doc = (@"<svg><![CDATA[</svg>a").ToHtmlDocument();
var dochtml0 = doc.ChildNodes[0];
Assert.AreEqual(2, dochtml0.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0).Attributes.Length);
Assert.AreEqual("html", dochtml0.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0.NodeType);
var dochtml0head0 = dochtml0.ChildNodes[0];
Assert.AreEqual(0, dochtml0head0.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0head0).Attributes.Length);
Assert.AreEqual("head", dochtml0head0.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0head0.NodeType);
var dochtml0body1 = dochtml0.ChildNodes[1];
Assert.AreEqual(1, dochtml0body1.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0body1).Attributes.Length);
Assert.AreEqual("body", dochtml0body1.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0body1.NodeType);
var dochtml0body1svg0 = dochtml0body1.ChildNodes[0];
Assert.AreEqual(1, dochtml0body1svg0.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0body1svg0).Attributes.Length);
Assert.AreEqual("svg", dochtml0body1svg0.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0body1svg0.NodeType);
var dochtml0body1svg0Text0 = dochtml0body1svg0.ChildNodes[0];
Assert.AreEqual(NodeType.Text, dochtml0body1svg0Text0.NodeType);
Assert.AreEqual("</svg>a", dochtml0body1svg0Text0.TextContent);
}
[Test]
public void CDataWithSvgTagInSvgElementFollowedByPath()
{
var doc = (@"<svg><![CDATA[<svg>]]><path>").ToHtmlDocument();
var dochtml0 = doc.ChildNodes[0];
Assert.AreEqual(2, dochtml0.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0).Attributes.Length);
Assert.AreEqual("html", dochtml0.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0.NodeType);
var dochtml0head0 = dochtml0.ChildNodes[0];
Assert.AreEqual(0, dochtml0head0.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0head0).Attributes.Length);
Assert.AreEqual("head", dochtml0head0.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0head0.NodeType);
var dochtml0body1 = dochtml0.ChildNodes[1];
Assert.AreEqual(1, dochtml0body1.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0body1).Attributes.Length);
Assert.AreEqual("body", dochtml0body1.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0body1.NodeType);
var dochtml0body1svg0 = dochtml0body1.ChildNodes[0];
Assert.AreEqual(2, dochtml0body1svg0.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0body1svg0).Attributes.Length);
Assert.AreEqual("svg", dochtml0body1svg0.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0body1svg0.NodeType);
var dochtml0body1svg0Text0 = dochtml0body1svg0.ChildNodes[0];
Assert.AreEqual(NodeType.Text, dochtml0body1svg0Text0.NodeType);
Assert.AreEqual("<svg>", dochtml0body1svg0Text0.TextContent);
var dochtml0body1svg0path1 = dochtml0body1svg0.ChildNodes[1];
Assert.AreEqual(0, dochtml0body1svg0path1.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0body1svg0path1).Attributes.Length);
Assert.AreEqual("path", dochtml0body1svg0path1.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0body1svg0path1.NodeType);
}
[Test]
public void CDataWithSvgTagInSvgElementFollowedByClosingPath()
{
var doc = (@"<svg><![CDATA[<svg>]]></path>").ToHtmlDocument();
var dochtml0 = doc.ChildNodes[0];
Assert.AreEqual(2, dochtml0.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0).Attributes.Length);
Assert.AreEqual("html", dochtml0.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0.NodeType);
var dochtml0head0 = dochtml0.ChildNodes[0];
Assert.AreEqual(0, dochtml0head0.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0head0).Attributes.Length);
Assert.AreEqual("head", dochtml0head0.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0head0.NodeType);
var dochtml0body1 = dochtml0.ChildNodes[1];
Assert.AreEqual(1, dochtml0body1.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0body1).Attributes.Length);
Assert.AreEqual("body", dochtml0body1.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0body1.NodeType);
var dochtml0body1svg0 = dochtml0body1.ChildNodes[0];
Assert.AreEqual(1, dochtml0body1svg0.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0body1svg0).Attributes.Length);
Assert.AreEqual("svg", dochtml0body1svg0.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0body1svg0.NodeType);
var dochtml0body1svg0Text0 = dochtml0body1svg0.ChildNodes[0];
Assert.AreEqual(NodeType.Text, dochtml0body1svg0Text0.NodeType);
Assert.AreEqual("<svg>", dochtml0body1svg0Text0.TextContent);
}
[Test]
public void CDataWithSvgTagInSvgElementFollowedByComment()
{
var doc = (@"<svg><![CDATA[<svg>]]><!--path-->").ToHtmlDocument();
var dochtml0 = doc.ChildNodes[0];
Assert.AreEqual(2, dochtml0.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0).Attributes.Length);
Assert.AreEqual("html", dochtml0.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0.NodeType);
var dochtml0head0 = dochtml0.ChildNodes[0];
Assert.AreEqual(0, dochtml0head0.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0head0).Attributes.Length);
Assert.AreEqual("head", dochtml0head0.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0head0.NodeType);
var dochtml0body1 = dochtml0.ChildNodes[1];
Assert.AreEqual(1, dochtml0body1.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0body1).Attributes.Length);
Assert.AreEqual("body", dochtml0body1.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0body1.NodeType);
var dochtml0body1svg0 = dochtml0body1.ChildNodes[0];
Assert.AreEqual(2, dochtml0body1svg0.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0body1svg0).Attributes.Length);
Assert.AreEqual("svg", dochtml0body1svg0.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0body1svg0.NodeType);
var dochtml0body1svg0Text0 = dochtml0body1svg0.ChildNodes[0];
Assert.AreEqual(NodeType.Text, dochtml0body1svg0Text0.NodeType);
Assert.AreEqual("<svg>", dochtml0body1svg0Text0.TextContent);
var dochtml0body1svg0Comment1 = dochtml0body1svg0.ChildNodes[1];
Assert.AreEqual(NodeType.Comment, dochtml0body1svg0Comment1.NodeType);
Assert.AreEqual(@"path", dochtml0body1svg0Comment1.TextContent);
}
[Test]
public void CDataWithSvgTagInSvgElementFollowedByText()
{
var doc = (@"<svg><![CDATA[<svg>]]>path").ToHtmlDocument();
var dochtml0 = doc.ChildNodes[0];
Assert.AreEqual(2, dochtml0.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0).Attributes.Length);
Assert.AreEqual("html", dochtml0.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0.NodeType);
var dochtml0head0 = dochtml0.ChildNodes[0];
Assert.AreEqual(0, dochtml0head0.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0head0).Attributes.Length);
Assert.AreEqual("head", dochtml0head0.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0head0.NodeType);
var dochtml0body1 = dochtml0.ChildNodes[1];
Assert.AreEqual(1, dochtml0body1.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0body1).Attributes.Length);
Assert.AreEqual("body", dochtml0body1.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0body1.NodeType);
var dochtml0body1svg0 = dochtml0body1.ChildNodes[0];
Assert.AreEqual(1, dochtml0body1svg0.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0body1svg0).Attributes.Length);
Assert.AreEqual("svg", dochtml0body1svg0.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0body1svg0.NodeType);
var dochtml0body1svg0Text0 = dochtml0body1svg0.ChildNodes[0];
Assert.AreEqual(NodeType.Text, dochtml0body1svg0Text0.NodeType);
Assert.AreEqual("<svg>path", dochtml0body1svg0Text0.TextContent);
}
[Test]
public void CDataWithCommentInSvgElement()
{
var doc = (@"<svg><![CDATA[<!--svg-->]]>").ToHtmlDocument();
var dochtml0 = doc.ChildNodes[0];
Assert.AreEqual(2, dochtml0.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0).Attributes.Length);
Assert.AreEqual("html", dochtml0.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0.NodeType);
var dochtml0head0 = dochtml0.ChildNodes[0];
Assert.AreEqual(0, dochtml0head0.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0head0).Attributes.Length);
Assert.AreEqual("head", dochtml0head0.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0head0.NodeType);
var dochtml0body1 = dochtml0.ChildNodes[1];
Assert.AreEqual(1, dochtml0body1.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0body1).Attributes.Length);
Assert.AreEqual("body", dochtml0body1.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0body1.NodeType);
var dochtml0body1svg0 = dochtml0body1.ChildNodes[0];
Assert.AreEqual(1, dochtml0body1svg0.ChildNodes.Length);
Assert.AreEqual(0, ((Element)dochtml0body1svg0).Attributes.Length);
Assert.AreEqual("svg", dochtml0body1svg0.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml0body1svg0.NodeType);
var dochtml0body1svg0Text0 = dochtml0body1svg0.ChildNodes[0];
Assert.AreEqual(NodeType.Text, dochtml0body1svg0Text0.NodeType);
Assert.AreEqual("<!--svg-->", dochtml0body1svg0Text0.TextContent);
}
}
}
| |
using System;
using Hades.Common.Source;
namespace Hades.Syntax.Lexeme
{
public sealed class Token : IEquatable<Token>
{
private readonly Lazy<Category> _category;
public Token(string value)
{
Value = value;
}
public Token(Classifier kind, string contents, SourceLocation start, SourceLocation end)
{
Kind = kind;
Value = contents;
Span = new Span(start, end);
_category = new Lazy<Category>(GetTokenCategory);
}
public Category Category => _category.Value;
public Classifier Kind { get; }
public Span Span { get; }
public string Value { get; set; }
public bool Equals(Token other)
{
if (other == null)
{
return false;
}
return other.Value == Value &&
other.Span == Span &&
other.Kind == Kind;
}
public static bool operator !=(Token left, string right)
{
return left?.Value != right;
}
public static bool operator !=(string left, Token right)
{
return right?.Value != left;
}
public static bool operator !=(Token left, Classifier right)
{
return left?.Kind != right;
}
public static bool operator !=(Classifier left, Token right)
{
return right?.Kind != left;
}
public static bool operator ==(Token left, string right)
{
return left?.Value == right;
}
public static bool operator ==(string left, Token right)
{
return right?.Value == left;
}
public static bool operator ==(Token left, Classifier right)
{
return left?.Kind == right;
}
public static bool operator ==(Classifier left, Token right)
{
return right?.Kind == left;
}
public override bool Equals(object obj)
{
if (obj is Token token)
{
return Equals(token);
}
return base.Equals(obj);
}
public override int GetHashCode()
{
return Value.GetHashCode() ^ Span.GetHashCode() ^ Kind.GetHashCode();
}
public bool IsTrivia()
{
return Category == Category.WhiteSpace || Category == Category.Comment;
}
private Category GetTokenCategory()
{
switch (Kind)
{
case Classifier.Arrow:
case Classifier.FatArrow:
case Classifier.Colon:
case Classifier.Comma:
case Classifier.Underscore:
case Classifier.At:
case Classifier.Dot:
return Category.Punctuation;
case Classifier.Equal:
case Classifier.NotEqual:
case Classifier.LessThan:
case Classifier.LessThanOrEqual:
case Classifier.GreaterThan:
case Classifier.GreaterThanOrEqual:
case Classifier.Mod:
case Classifier.Mul:
case Classifier.Plus:
case Classifier.Div:
case Classifier.BooleanOr:
case Classifier.BooleanAnd:
case Classifier.BitwiseXor:
case Classifier.BitwiseOr:
case Classifier.BitwiseAnd:
case Classifier.BitShiftLeft:
case Classifier.BitShiftRight:
case Classifier.BitwiseNegate:
case Classifier.Minus:
case Classifier.Not:
return Category.Operator;
case Classifier.MinusMinus:
case Classifier.PlusPlus:
return Category.RightHand;
case Classifier.Assignment:
case Classifier.MulEqual:
case Classifier.MinusEqual:
case Classifier.ModEqual:
case Classifier.PlusEqual:
case Classifier.BitwiseXorEqual:
case Classifier.BitwiseOrEqual:
case Classifier.BitwiseAndEqual:
case Classifier.BitShiftLeftEqual:
case Classifier.BitShiftRightEqual:
case Classifier.BitwiseNegateEqual:
case Classifier.DivEqual:
return Category.Assignment;
case Classifier.BlockComment:
case Classifier.LineComment:
return Category.Comment;
case Classifier.NewLine:
case Classifier.WhiteSpace:
return Category.WhiteSpace;
case Classifier.LeftBrace:
case Classifier.LeftBracket:
case Classifier.LeftParenthesis:
case Classifier.RightBrace:
case Classifier.RightBracket:
case Classifier.RightParenthesis:
return Category.Grouping;
case Classifier.Identifier:
case Classifier.Keyword:
return Category.Identifier;
case Classifier.StringLiteral:
case Classifier.DecLiteral:
case Classifier.IntLiteral:
case Classifier.BoolLiteral:
case Classifier.MultiLineStringLiteral:
return Category.Literal;
case Classifier.Error:
return Category.Invalid;
case Classifier.Pipeline:
case Classifier.Tag:
case Classifier.Question:
return Category.Other;
default: return Category.Unknown;
}
}
public override string ToString()
{
return $"{Kind} : {Value}";
}
}
}
| |
#region
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Threading.Tasks;
using Android.App;
using Android.Content;
using Android.Content.PM;
using Android.Graphics;
using Android.OS;
using Android.Runtime;
using Android.Text.Method;
using Android.Views;
using Android.Views.InputMethods;
using Android.Widget;
using Java.Lang;
using Xamarin;
using Xsseract.Droid.Extensions;
using Xsseract.Droid.Fragments;
using Environment = System.Environment;
using Exception = System.Exception;
using File = Java.IO.File;
using Path = System.IO.Path;
using String = System.String;
using Uri = Android.Net.Uri;
#endregion
namespace Xsseract.Droid
{
// TODO: android.view.WindowLeaked: Activity md5b71b1bed33a31f85ecaffba202309a1f.ResultActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{43b5f40 G.E..... R.....ID 0,0-1026,348} that was originally added here
[Activity(WindowSoftInputMode = SoftInput.AdjustResize, Theme = "@style/AppTheme", ConfigurationChanges = ConfigChanges.Orientation | ConfigChanges.ScreenSize)]
public class ResultActivity : ContextualHelpActivity
{
#region Fields
private Bitmap cropped;
private Rect cropRect;
private ImageView imgResult;
private bool pipeResult;
private bool ratingAskedForThisImage;
private string result;
private Func<Task> toDoOnResume;
private EditText txtEditResult;
private TextView txtViewResult;
#endregion
public override bool OnTouchEvent(MotionEvent e)
{
if (txtEditResult.Visibility != ViewStates.Visible)
{
return base.OnTouchEvent(e);
}
var coords = new int[2];
txtEditResult.GetLocationOnScreen(coords);
var rect = new Rect(coords[0], coords[1], coords[0] + txtEditResult.Width, coords[1] + txtEditResult.Height);
if (!rect.Contains((int)e.GetX(), (int)e.GetY()))
{
ResumeResultView();
}
return base.OnTouchEvent(e);
}
public override bool OnKeyDown([GeneratedEnum] Keycode keyCode, KeyEvent e)
{
if (keyCode != Keycode.Back)
{
return base.OnKeyDown(keyCode, e);
}
if (txtEditResult.Visibility == ViewStates.Visible)
{
ResumeResultView();
return true;
}
else
{
AskForRating(async () =>
{
await Task.Yield();
SetResult(Result.Canceled);
Finish();
});
return true;
}
}
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
SetContentView(Resource.Layout.Result);
txtViewResult = FindViewById<TextView>(Resource.Id.txtViewResult);
imgResult = FindViewById<ImageView>(Resource.Id.imgResult);
txtEditResult = FindViewById<EditText>(Resource.Id.txtEditResult);
txtViewResult.MovementMethod = new ScrollingMovementMethod();
txtViewResult.LongClick += txtViewResult_Click;
imgResult.Focusable = true;
Toolbar.CopyToClipboard += Toolbar_CopyToClipboard;
Toolbar.Share += Toolbar_Share;
Toolbar.Accept += Toolbar_Accept;
}
protected override async void OnResume()
{
base.OnResume();
var cropRectString = Intent.GetStringExtra(Constants.CropRect).Split(',');
cropRect = new Rect(Int32.Parse(cropRectString[0]), Int32.Parse(cropRectString[1]), Int32.Parse(cropRectString[2]), Int32.Parse(cropRectString[3]));
pipeResult = Intent.GetBooleanExtra(Constants.PipeResult, false);
txtEditResult.Visibility = ViewStates.Gone;
if (!pipeResult)
{
Toolbar.ShowResultTools(true);
}
else
{
Toolbar.ShowResultToolsNoShare(true);
}
if (null == cropped)
{
ITrackHandle handle = null;
var sw = new Stopwatch();
try
{
DisplayProgress(Resources.GetString(Resource.String.progress_OCR));
handle = XsseractContext.LogTimedEvent(AppTrackingEvents.ImageParseDuration);
sw.Start();
handle.Start();
await PerformOcrAsync();
XsseractContext.IncrementSuccessCounter();
handle.Stop();
sw.Stop();
var data = new Dictionary<string, string>
{
{ AppTrackingEventsDataKey.ImageResW, cropped.Width.ToString() },
{ AppTrackingEventsDataKey.ImageResH, cropped.Height.ToString() },
{ AppTrackingEventsDataKey.ImageDensity, cropped.Density.ToString() },
{ AppTrackingEventsDataKey.OriginalImageResW, cropped.Width.ToString() },
{ AppTrackingEventsDataKey.OriginalImageResH, cropped.Height.ToString() }
};
if (0 != sw.ElapsedMilliseconds)
{
data.Add(AppTrackingEventsDataKey.ParseSpeedPixelsPerMs, ((cropped.Width * cropped.Height) / sw.ElapsedMilliseconds).ToString());
}
XsseractContext.LogEvent(AppTrackingEvents.ImageDetails, data);
HideProgress();
}
catch(Exception e)
{
handle.DisposeIfRunning();
sw.Stop();
HideProgress();
LogError(e);
DisplayError(e);
Finish();
return;
}
}
imgResult.SetImageBitmap(cropped);
txtViewResult.Text = result;
if (null != toDoOnResume)
{
await toDoOnResume.Invoke();
toDoOnResume = null;
}
else
{
Toast t = Toast.MakeText(this, Resource.String.toast_TapToEditResult, ToastLength.Short);
t.Show();
}
}
protected override void OnDestroy()
{
if (null != cropped)
{
imgResult.SetImageBitmap(null);
cropped.Recycle();
cropped.Dispose();
cropped = null;
result = null;
}
base.OnDestroy();
}
protected override DismissableFragment GetHelpFragment()
{
return new HelpResultsPagerFragment(true);
}
#region Private Methods
private void AskForRating(Func<Task> callback)
{
if (ratingAskedForThisImage || !XsseractContext.ShouldAskForRating())
{
callback?.Invoke();
return;
}
ratingAskedForThisImage = true;
ShowRatingDialog(callback);
return;
}
private void CopyToClipboard()
{
var service = (ClipboardManager)GetSystemService(ClipboardService);
var data = ClipData.NewPlainText(Resources.GetString(Resource.String.text_ClipboardLabel),
$"{Resources.GetString(Resource.String.text_SendToSubject)}: {Environment.NewLine}{result}");
service.PrimaryClip = data;
var toast = Toast.MakeText(this, Resource.String.toast_CopiedToClipboard, ToastLength.Long);
toast.Show();
}
private async Task<Bitmap> GetImageAsync()
{
return await Task.Factory.StartNew(
() =>
{
var image = XsseractContext.GetBitmap();
float scale = 1;
Bitmap res = null;
do
{
try
{
Bitmap tmp = Bitmap.CreateBitmap((int)(cropRect.Width() / scale), (int)(cropRect.Height() / scale), Bitmap.Config.Argb8888);
{
var canvas = new Canvas(tmp);
var dstRect = new RectF(0, 0, cropRect.Width(), cropRect.Height());
canvas.DrawBitmap(image, cropRect, dstRect, null);
}
res = tmp;
}
catch(OutOfMemoryError)
{
scale += 1;
}
} while(null == res);
return res;
});
}
private async Task<File> GetImageAttachmentAsync()
{
return await Task.Factory.StartNew(
() =>
{
var imagePath = XsseractContext.GetImageUri();
var fileName = String.Format("{0}-cropped.png", Path.GetFileNameWithoutExtension(imagePath));
var path = Path.GetDirectoryName(imagePath);
var file = new File(Path.Combine(path, fileName));
if (file.Exists())
{
file.Delete();
}
using(var fs = new FileStream(file.AbsolutePath, FileMode.Create, FileAccess.Write))
{
cropped.Compress(Bitmap.CompressFormat.Png, 100, fs);
}
file.DeleteOnExit();
return file;
});
}
private async Task PerformOcrAsync()
{
cropped = await GetImageAsync();
var tess = await XsseractContext.GetTessInstanceAsync();
result = await tess.RecognizeAsync(XsseractContext.GetBitmap(), cropRect);
}
private void ResumeResultView()
{
var imm = (InputMethodManager)GetSystemService(InputMethodService);
imm.HideSoftInputFromWindow(txtEditResult.WindowToken, 0);
bool hasChanged = 0 != String.Compare(txtEditResult.Text, result);
txtViewResult.Text = result = txtEditResult.Text;
txtViewResult.Visibility = ViewStates.Visible;
txtEditResult.Visibility = ViewStates.Gone;
if (!pipeResult)
{
Toolbar.ShowResultTools(false);
}
else
{
Toolbar.ShowResultToolsNoShare(false);
}
if (hasChanged)
{
XsseractContext.LogEvent(AppTrackingEvents.ResultManuallyEdited);
}
}
private async Task ShareResult()
{
CopyToClipboard();
DisplayProgress(Resources.GetString(Resource.String.progress_PrepareShare));
var attachment = await GetImageAttachmentAsync();
HideProgress();
var sendIntent = new Intent(Intent.ActionSendMultiple);
sendIntent.SetType("image/*");
sendIntent.PutExtra(Intent.ExtraSubject, Resource.String.text_SendToSubject);
sendIntent.PutExtra(Intent.ExtraText, $"{Resources.GetString(Resource.String.text_SendToSubject)}: {Environment.NewLine}{result}");
sendIntent.PutParcelableArrayListExtra(Intent.ExtraStream, new JavaList<IParcelable>
{
Uri.FromFile(attachment)
});
sendIntent.AddFlags(ActivityFlags.GrantReadUriPermission);
StartActivity(Intent.CreateChooser(sendIntent, Resources.GetString(Resource.String.text_SendToTitle)));
}
private void ShowRatingDialog(Func<Task> callback)
{
Dialog d = new Dialog(this);
d.SetTitle(Resource.String.text_RatingPromptTitle);
d.SetContentView(Resource.Layout.RatingDialog);
var btnNow = d.FindViewById<Button>(Resource.Id.btnNow);
var btnLater = d.FindViewById<Button>(Resource.Id.btnLater);
var btnNever = d.FindViewById<Button>(Resource.Id.btnNever);
btnNow.Click += (sender, e) =>
{
toDoOnResume = callback;
d.Hide();
StartRateApplicationActivity();
};
btnLater.Click += async (sender, e) =>
{
XsseractContext.LogEvent(AppTrackingEvents.RateLater);
d.Hide();
if(null != callback) {
await callback.Invoke();
}
else {
await Task.Yield();
}
};
btnNever.Click += async (sender, e) =>
{
XsseractContext.SetDontRateFlag();
XsseractContext.LogEvent(AppTrackingEvents.RateNever);
d.Hide();
if(null != callback) {
await callback.Invoke();
}
else {
await Task.Yield();
}
};
d.Show();
}
private void Toolbar_Accept(object sender, EventArgs eventArgs)
{
AskForRating(async () =>
{
await Task.Yield();
XsseractContext.LogEvent(AppTrackingEvents.Accept);
var intent = new Intent();
intent.PutExtra(Constants.Accept, true);
intent.PutExtra(Constants.Result, result);
SetResult(Result.Ok, intent);
Finish();
});
}
private void Toolbar_CopyToClipboard(object sender, EventArgs eventArgs)
{
AskForRating(async () =>
{
await Task.Yield();
CopyToClipboard();
XsseractContext.LogEvent(AppTrackingEvents.CopyToClipboard);
});
}
private void Toolbar_Share(object sender, EventArgs eventArgs)
{
AskForRating(async () =>
{
await ShareResult();
XsseractContext.LogEvent(AppTrackingEvents.Share);
});
}
private void txtViewResult_Click(object sender, EventArgs eventArgs)
{
txtEditResult.Text = txtViewResult.Text;
txtViewResult.Visibility = ViewStates.Gone;
txtEditResult.Visibility = ViewStates.Visible;
var inputMethodManager = (InputMethodManager)BaseContext.GetSystemService(InputMethodService);
inputMethodManager.ShowSoftInput(txtEditResult, ShowFlags.Forced);
inputMethodManager.ToggleSoftInput(ShowFlags.Forced, HideSoftInputFlags.ImplicitOnly);
Toolbar.HideAll();
}
#endregion
#region Inner Classes/Enums
public static class Constants
{
public const string
ImagePath = "ImagePath",
CropRect = "CropRect",
PipeResult = "PipeResult",
Rotation = "Rotation",
Accept = "Accept",
Result = "Result";
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//
namespace System.Reflection
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Globalization;
using System.Runtime;
using System.Runtime.ConstrainedExecution;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Security.Permissions;
using System.Text;
using RuntimeTypeCache = System.RuntimeType.RuntimeTypeCache;
[Serializable]
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof(_PropertyInfo))]
#pragma warning disable 618
[PermissionSetAttribute(SecurityAction.InheritanceDemand, Name = "FullTrust")]
#pragma warning restore 618
[System.Runtime.InteropServices.ComVisible(true)]
public abstract class PropertyInfo : MemberInfo, _PropertyInfo
{
#region Constructor
protected PropertyInfo() { }
#endregion
public static bool operator ==(PropertyInfo left, PropertyInfo right)
{
if (ReferenceEquals(left, right))
return true;
if ((object)left == null || (object)right == null ||
left is RuntimePropertyInfo || right is RuntimePropertyInfo)
{
return false;
}
return left.Equals(right);
}
public static bool operator !=(PropertyInfo left, PropertyInfo right)
{
return !(left == right);
}
public override bool Equals(object obj)
{
return base.Equals(obj);
}
public override int GetHashCode()
{
return base.GetHashCode();
}
#region MemberInfo Overrides
public override MemberTypes MemberType { get { return System.Reflection.MemberTypes.Property; } }
#endregion
#region Public Abstract\Virtual Members
public virtual object GetConstantValue()
{
throw new NotImplementedException();
}
public virtual object GetRawConstantValue()
{
throw new NotImplementedException();
}
public abstract Type PropertyType { get; }
public abstract void SetValue(Object obj, Object value, BindingFlags invokeAttr, Binder binder, Object[] index, CultureInfo culture);
public abstract MethodInfo[] GetAccessors(bool nonPublic);
public abstract MethodInfo GetGetMethod(bool nonPublic);
public abstract MethodInfo GetSetMethod(bool nonPublic);
public abstract ParameterInfo[] GetIndexParameters();
public abstract PropertyAttributes Attributes { get; }
public abstract bool CanRead { get; }
public abstract bool CanWrite { get; }
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
public Object GetValue(Object obj)
{
return GetValue(obj, null);
}
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
public virtual Object GetValue(Object obj,Object[] index)
{
return GetValue(obj, BindingFlags.Default, null, index, null);
}
public abstract Object GetValue(Object obj, BindingFlags invokeAttr, Binder binder, Object[] index, CultureInfo culture);
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
public void SetValue(Object obj, Object value)
{
SetValue(obj, value, null);
}
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
public virtual void SetValue(Object obj, Object value, Object[] index)
{
SetValue(obj, value, BindingFlags.Default, null, index, null);
}
#endregion
#region Public Members
public virtual Type[] GetRequiredCustomModifiers() { return EmptyArray<Type>.Value; }
public virtual Type[] GetOptionalCustomModifiers() { return EmptyArray<Type>.Value; }
public MethodInfo[] GetAccessors() { return GetAccessors(false); }
public virtual MethodInfo GetMethod
{
get
{
return GetGetMethod(true);
}
}
public virtual MethodInfo SetMethod
{
get
{
return GetSetMethod(true);
}
}
public MethodInfo GetGetMethod() { return GetGetMethod(false); }
public MethodInfo GetSetMethod() { return GetSetMethod(false); }
public bool IsSpecialName { get { return(Attributes & PropertyAttributes.SpecialName) != 0; } }
#endregion
#if !FEATURE_CORECLR
Type _PropertyInfo.GetType()
{
return base.GetType();
}
void _PropertyInfo.GetTypeInfoCount(out uint pcTInfo)
{
throw new NotImplementedException();
}
void _PropertyInfo.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo)
{
throw new NotImplementedException();
}
void _PropertyInfo.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
{
throw new NotImplementedException();
}
// If you implement this method, make sure to include _PropertyInfo.Invoke in VM\DangerousAPIs.h and
// include _PropertyInfo in SystemDomain::IsReflectionInvocationMethod in AppDomain.cpp.
void _PropertyInfo.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
{
throw new NotImplementedException();
}
#endif
}
[Serializable]
internal unsafe sealed class RuntimePropertyInfo : PropertyInfo, ISerializable
{
#region Private Data Members
private int m_token;
private string m_name;
[System.Security.SecurityCritical]
private void* m_utf8name;
private PropertyAttributes m_flags;
private RuntimeTypeCache m_reflectedTypeCache;
private RuntimeMethodInfo m_getterMethod;
private RuntimeMethodInfo m_setterMethod;
private MethodInfo[] m_otherMethod;
private RuntimeType m_declaringType;
private BindingFlags m_bindingFlags;
private Signature m_signature;
private ParameterInfo[] m_parameters;
#endregion
#region Constructor
[System.Security.SecurityCritical] // auto-generated
internal RuntimePropertyInfo(
int tkProperty, RuntimeType declaredType, RuntimeTypeCache reflectedTypeCache, out bool isPrivate)
{
Contract.Requires(declaredType != null);
Contract.Requires(reflectedTypeCache != null);
Contract.Assert(!reflectedTypeCache.IsGlobal);
MetadataImport scope = declaredType.GetRuntimeModule().MetadataImport;
m_token = tkProperty;
m_reflectedTypeCache = reflectedTypeCache;
m_declaringType = declaredType;
ConstArray sig;
scope.GetPropertyProps(tkProperty, out m_utf8name, out m_flags, out sig);
RuntimeMethodInfo dummy;
Associates.AssignAssociates(scope, tkProperty, declaredType, reflectedTypeCache.GetRuntimeType(),
out dummy, out dummy, out dummy,
out m_getterMethod, out m_setterMethod, out m_otherMethod,
out isPrivate, out m_bindingFlags);
}
#endregion
#region Internal Members
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
internal override bool CacheEquals(object o)
{
RuntimePropertyInfo m = o as RuntimePropertyInfo;
if ((object)m == null)
return false;
return m.m_token == m_token &&
RuntimeTypeHandle.GetModule(m_declaringType).Equals(
RuntimeTypeHandle.GetModule(m.m_declaringType));
}
internal Signature Signature
{
[System.Security.SecuritySafeCritical] // auto-generated
get
{
if (m_signature == null)
{
PropertyAttributes flags;
ConstArray sig;
void* name;
GetRuntimeModule().MetadataImport.GetPropertyProps(
m_token, out name, out flags, out sig);
m_signature = new Signature(sig.Signature.ToPointer(), (int)sig.Length, m_declaringType);
}
return m_signature;
}
}
internal bool EqualsSig(RuntimePropertyInfo target)
{
//@Asymmetry - Legacy policy is to remove duplicate properties, including hidden properties.
// The comparison is done by name and by sig. The EqualsSig comparison is expensive
// but forutnetly it is only called when an inherited property is hidden by name or
// when an interfaces declare properies with the same signature.
// Note that we intentionally don't resolve generic arguments so that we don't treat
// signatures that only match in certain instantiations as duplicates. This has the
// down side of treating overriding and overriden properties as different properties
// in some cases. But PopulateProperties in rttype.cs should have taken care of that
// by comparing VTable slots.
//
// Class C1(Of T, Y)
// Property Prop1(ByVal t1 As T) As Integer
// Get
// ... ...
// End Get
// End Property
// Property Prop1(ByVal y1 As Y) As Integer
// Get
// ... ...
// End Get
// End Property
// End Class
//
Contract.Requires(Name.Equals(target.Name));
Contract.Requires(this != target);
Contract.Requires(this.ReflectedType == target.ReflectedType);
return Signature.CompareSig(this.Signature, target.Signature);
}
internal BindingFlags BindingFlags { get { return m_bindingFlags; } }
#endregion
#region Object Overrides
public override String ToString()
{
return FormatNameAndSig(false);
}
private string FormatNameAndSig(bool serialization)
{
StringBuilder sbName = new StringBuilder(PropertyType.FormatTypeName(serialization));
sbName.Append(" ");
sbName.Append(Name);
RuntimeType[] arguments = Signature.Arguments;
if (arguments.Length > 0)
{
sbName.Append(" [");
sbName.Append(MethodBase.ConstructParameters(arguments, Signature.CallingConvention, serialization));
sbName.Append("]");
}
return sbName.ToString();
}
#endregion
#region ICustomAttributeProvider
public override Object[] GetCustomAttributes(bool inherit)
{
return CustomAttribute.GetCustomAttributes(this, typeof(object) as RuntimeType);
}
public override Object[] GetCustomAttributes(Type attributeType, bool inherit)
{
if (attributeType == null)
throw new ArgumentNullException(nameof(attributeType));
Contract.EndContractBlock();
RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
if (attributeRuntimeType == null)
throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),nameof(attributeType));
return CustomAttribute.GetCustomAttributes(this, attributeRuntimeType);
}
[System.Security.SecuritySafeCritical] // auto-generated
public override bool IsDefined(Type attributeType, bool inherit)
{
if (attributeType == null)
throw new ArgumentNullException(nameof(attributeType));
Contract.EndContractBlock();
RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
if (attributeRuntimeType == null)
throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),nameof(attributeType));
return CustomAttribute.IsDefined(this, attributeRuntimeType);
}
public override IList<CustomAttributeData> GetCustomAttributesData()
{
return CustomAttributeData.GetCustomAttributesInternal(this);
}
#endregion
#region MemberInfo Overrides
public override MemberTypes MemberType { get { return MemberTypes.Property; } }
public override String Name
{
[System.Security.SecuritySafeCritical] // auto-generated
get
{
if (m_name == null)
m_name = new Utf8String(m_utf8name).ToString();
return m_name;
}
}
public override Type DeclaringType
{
get
{
return m_declaringType;
}
}
public override Type ReflectedType
{
get
{
return ReflectedTypeInternal;
}
}
private RuntimeType ReflectedTypeInternal
{
get
{
return m_reflectedTypeCache.GetRuntimeType();
}
}
public override int MetadataToken { get { return m_token; } }
public override Module Module { get { return GetRuntimeModule(); } }
internal RuntimeModule GetRuntimeModule() { return m_declaringType.GetRuntimeModule(); }
#endregion
#region PropertyInfo Overrides
#region Non Dynamic
public override Type[] GetRequiredCustomModifiers()
{
return Signature.GetCustomModifiers(0, true);
}
public override Type[] GetOptionalCustomModifiers()
{
return Signature.GetCustomModifiers(0, false);
}
[System.Security.SecuritySafeCritical] // auto-generated
internal object GetConstantValue(bool raw)
{
Object defaultValue = MdConstant.GetValue(GetRuntimeModule().MetadataImport, m_token, PropertyType.GetTypeHandleInternal(), raw);
if (defaultValue == DBNull.Value)
// Arg_EnumLitValueNotFound -> "Literal value was not found."
throw new InvalidOperationException(Environment.GetResourceString("Arg_EnumLitValueNotFound"));
return defaultValue;
}
public override object GetConstantValue() { return GetConstantValue(false); }
public override object GetRawConstantValue() { return GetConstantValue(true); }
public override MethodInfo[] GetAccessors(bool nonPublic)
{
List<MethodInfo> accessorList = new List<MethodInfo>();
if (Associates.IncludeAccessor(m_getterMethod, nonPublic))
accessorList.Add(m_getterMethod);
if (Associates.IncludeAccessor(m_setterMethod, nonPublic))
accessorList.Add(m_setterMethod);
if ((object)m_otherMethod != null)
{
for(int i = 0; i < m_otherMethod.Length; i ++)
{
if (Associates.IncludeAccessor(m_otherMethod[i] as MethodInfo, nonPublic))
accessorList.Add(m_otherMethod[i]);
}
}
return accessorList.ToArray();
}
public override Type PropertyType
{
get { return Signature.ReturnType; }
}
public override MethodInfo GetGetMethod(bool nonPublic)
{
if (!Associates.IncludeAccessor(m_getterMethod, nonPublic))
return null;
return m_getterMethod;
}
public override MethodInfo GetSetMethod(bool nonPublic)
{
if (!Associates.IncludeAccessor(m_setterMethod, nonPublic))
return null;
return m_setterMethod;
}
public override ParameterInfo[] GetIndexParameters()
{
ParameterInfo[] indexParams = GetIndexParametersNoCopy();
int numParams = indexParams.Length;
if (numParams == 0)
return indexParams;
ParameterInfo[] ret = new ParameterInfo[numParams];
Array.Copy(indexParams, ret, numParams);
return ret;
}
internal ParameterInfo[] GetIndexParametersNoCopy()
{
// @History - Logic ported from RTM
// No need to lock because we don't guarantee the uniqueness of ParameterInfo objects
if (m_parameters == null)
{
int numParams = 0;
ParameterInfo[] methParams = null;
// First try to get the Get method.
MethodInfo m = GetGetMethod(true);
if (m != null)
{
// There is a Get method so use it.
methParams = m.GetParametersNoCopy();
numParams = methParams.Length;
}
else
{
// If there is no Get method then use the Set method.
m = GetSetMethod(true);
if (m != null)
{
methParams = m.GetParametersNoCopy();
numParams = methParams.Length - 1;
}
}
// Now copy over the parameter info's and change their
// owning member info to the current property info.
ParameterInfo[] propParams = new ParameterInfo[numParams];
for (int i = 0; i < numParams; i++)
propParams[i] = new RuntimeParameterInfo((RuntimeParameterInfo)methParams[i], this);
m_parameters = propParams;
}
return m_parameters;
}
public override PropertyAttributes Attributes
{
get
{
return m_flags;
}
}
public override bool CanRead
{
get
{
return m_getterMethod != null;
}
}
public override bool CanWrite
{
get
{
return m_setterMethod != null;
}
}
#endregion
#region Dynamic
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
public override Object GetValue(Object obj,Object[] index)
{
return GetValue(obj, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static,
null, index, null);
}
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
public override Object GetValue(Object obj, BindingFlags invokeAttr, Binder binder, Object[] index, CultureInfo culture)
{
MethodInfo m = GetGetMethod(true);
if (m == null)
throw new ArgumentException(System.Environment.GetResourceString("Arg_GetMethNotFnd"));
return m.Invoke(obj, invokeAttr, binder, index, null);
}
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
public override void SetValue(Object obj, Object value, Object[] index)
{
SetValue(obj,
value,
BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static,
null,
index,
null);
}
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
public override void SetValue(Object obj, Object value, BindingFlags invokeAttr, Binder binder, Object[] index, CultureInfo culture)
{
MethodInfo m = GetSetMethod(true);
if (m == null)
throw new ArgumentException(System.Environment.GetResourceString("Arg_SetMethNotFnd"));
Object[] args = null;
if (index != null)
{
args = new Object[index.Length + 1];
for(int i=0;i<index.Length;i++)
args[i] = index[i];
args[index.Length] = value;
}
else
{
args = new Object[1];
args[0] = value;
}
m.Invoke(obj, invokeAttr, binder, args, culture);
}
#endregion
#endregion
#region ISerializable Implementation
[System.Security.SecurityCritical] // auto-generated
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info == null)
throw new ArgumentNullException(nameof(info));
Contract.EndContractBlock();
MemberInfoSerializationHolder.GetSerializationInfo(
info,
Name,
ReflectedTypeInternal,
ToString(),
SerializationToString(),
MemberTypes.Property,
null);
}
internal string SerializationToString()
{
return FormatNameAndSig(true);
}
#endregion
}
}
| |
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Windows.Forms;
using DpSdkEngLib;
using DPSDKOPSLib;
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Diagnostics;
using System.Windows.Forms;
using System.Linq;
using System.Xml.Linq;
// ERROR: Not supported in C#: OptionDeclaration
using Microsoft.VisualBasic.PowerPacks;
namespace _4PosBackOffice.NET
{
internal partial class frmCustomerTransactionNotes : System.Windows.Forms.Form
{
private ADODB.Recordset withEventsField_adoPrimaryRS;
public ADODB.Recordset adoPrimaryRS {
get { return withEventsField_adoPrimaryRS; }
set {
if (withEventsField_adoPrimaryRS != null) {
withEventsField_adoPrimaryRS.MoveComplete -= adoPrimaryRS_MoveComplete;
withEventsField_adoPrimaryRS.WillChangeRecord -= adoPrimaryRS_WillChangeRecord;
}
withEventsField_adoPrimaryRS = value;
if (withEventsField_adoPrimaryRS != null) {
withEventsField_adoPrimaryRS.MoveComplete += adoPrimaryRS_MoveComplete;
withEventsField_adoPrimaryRS.WillChangeRecord += adoPrimaryRS_WillChangeRecord;
}
}
}
bool mbChangedByCode;
int mvBookMark;
bool mbEditFlag;
bool mbAddNewFlag;
bool mbDataChanged;
int gID;
short gSection;
const short sec_Payment = 0;
const short sec_Debit = 1;
const short sec_Credit = 2;
const short sec_DebitNote = 3;
const short sec_CreditNote = 4;
List<TextBox> txtFields = new List<TextBox>();
List<TextBox> txtfloat = new List<TextBox>();
private void loadLanguage()
{
//frmCustomerTransactionNotes= No Code [Customer Transaction]
//rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000
//If rsLang.RecordCount Then frmCustomerTransactionNotes.Caption = rsLang("LanguageLayoutLnk_Description"): frmCustomerTransactionNotes.RightToLeft = rsLang("LanguageLayoutLnk_RightTL")
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1074;
//Undo|Checked
if (modRecordSet.rsLang.RecordCount){cmdCancel.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;cmdCancel.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1004;
//Exit|
if (modRecordSet.rsLang.RecordCount){cmdClose.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;cmdClose.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1010;
//General|Checked
if (modRecordSet.rsLang.RecordCount){_lbl_1.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;_lbl_1.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1284;
//Invoice Name|Checked
if (modRecordSet.rsLang.RecordCount){_lblLabels_2.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;_lblLabels_2.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1285;
//Department|Checked
if (modRecordSet.rsLang.RecordCount){_lblLabels_3.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;_lblLabels_3.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1286;
//Responsible Person Name|Checked
if (modRecordSet.rsLang.RecordCount){_lblLabels_4.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;_lblLabels_4.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1287;
//Surname|Checked
if (modRecordSet.rsLang.RecordCount){_lblLabels_5.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;_lblLabels_5.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1288;
//Telephone|Checked
if (modRecordSet.rsLang.RecordCount){_lblLabels_8.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;_lblLabels_8.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1289;
//Fax|Checked
if (modRecordSet.rsLang.RecordCount){_lblLabels_9.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;_lblLabels_9.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1290;
//Email|Checked
if (modRecordSet.rsLang.RecordCount){_lblLabels_10.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;_lblLabels_10.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1291;
//Physical Address|Checked
if (modRecordSet.rsLang.RecordCount){_lblLabels_0.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;_lblLabels_6.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1292;
//Postal Address|Checked
if (modRecordSet.rsLang.RecordCount){_lblLabels_7.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;_lblLabels_7.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1319;
//Financials|Checked
if (modRecordSet.rsLang.RecordCount){_lbl_0.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;_lbl_0.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1293;
//Credit Limit|Checked
if (modRecordSet.rsLang.RecordCount){_lblLabels_12.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;_lblLabels_12.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1295;
//Current|Checked
if (modRecordSet.rsLang.RecordCount){_lblLabels_13.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;_lblLabels_13.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1297;
//60 Days|Checked
if (modRecordSet.rsLang.RecordCount){_lblLabels_15.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;_lblLabels_15.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1299;
//120 Days|Checked
if (modRecordSet.rsLang.RecordCount){_lblLabels_17.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;_lblLabels_17.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1296;
//30 Days|Checked
if (modRecordSet.rsLang.RecordCount){_lblLabels_14.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;_lblLabels_14.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1298;
//90 Days|Checked
if (modRecordSet.rsLang.RecordCount){_lblLabels_16.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;_lblLabels_16.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1300;
//150 Days|Checked
if (modRecordSet.rsLang.RecordCount){_lblLabels_18.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;_lblLabels_18.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
//_lbl_2 = No Code [Transaction]
//rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000
//If rsLang.RecordCount Then _lbl_2.Caption = rsLang("LanguageLayoutLnk_Description"): _lbl_2.RightToLeft = rsLang("LanguageLayoutLnk_RightTL")
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1327;
//Narrative|Checked
if (modRecordSet.rsLang.RecordCount){_lblLabels_0.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;_lblLabels_0.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1328;
//Notes|Checked
if (modRecordSet.rsLang.RecordCount){_lblLabels_1.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;_lblLabels_1.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1329;
//Amount|Checked
if (modRecordSet.rsLang.RecordCount){_lblLabels_11.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;_lblLabels_11.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1330;
//Settlement|Checked
if (modRecordSet.rsLang.RecordCount){lblSett.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;lblSett.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1331;
//Settlement|Checked
if (modRecordSet.rsLang.RecordCount){Label2.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;Label2.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1332;
//Process|Checked
if (modRecordSet.rsLang.RecordCount){cmdProcess.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;cmdProcess.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsHelp.filter = "Help_Section=0 AND Help_Form='" + this.Name + "'";
//UPGRADE_ISSUE: Form property frmCustomerTransactionNotes.ToolTip1 was not upgraded. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="CC4C7EC0-C903-48FC-ACCC-81861D12DA4A"'
if (modRecordSet.rsHelp.RecordCount)
this.ToolTip1 = modRecordSet.rsHelp.Fields("Help_ContextID").Value;
}
public void loadItem(ref int id, ref short section)
{
System.Windows.Forms.TextBox oText = null;
System.Windows.Forms.CheckBox oCheck = null;
// ERROR: Not supported in C#: OnErrorStatement
this.lblSett.Visible = true;
this.txtSettlement.Visible = true;
if (id) {
adoPrimaryRS = modRecordSet.getRS(ref "select * from Customer WHERE CustomerID = " + id);
} else {
this.Close();
return;
}
gSection = section;
switch (gSection) {
case sec_DebitNote:
this.lblSett.Visible = false;
this.txtSettlement.Visible = false;
this.Text = " Debit Note";
break;
case sec_CreditNote:
this.lblSett.Visible = false;
this.txtSettlement.Visible = false;
this.Text = "Credit note";
break;
default:
this.Close();
return;
break;
}
_lbl_2.Text = "&3. Transaction (" + this.Text + ")";
// If adoPrimaryRS.BOF Or adoPrimaryRS.EOF Then
// Else
foreach (TextBox oText_loopVariable in txtFields) {
oText = oText_loopVariable;
oText.DataBindings.Add(adoPrimaryRS);
oText.MaxLength = adoPrimaryRS.Fields(oText.DataBindings).DefinedSize;
}
// For Each oText In Me.txtInteger
// Set oText.DataBindings.Add(adoPrimaryRS)
// txtInteger_LostFocus oText.Index
// Next
foreach (TextBox oText_loopVariable in txtfloat) {
oText = oText_loopVariable;
oText.DataBindings.Add(adoPrimaryRS);
if (string.IsNullOrEmpty(oText.Text))
oText.Text = "0";
oText.Text = Convert.ToString(Convert.ToDouble(oText.Text) * 100);
oText.Leave += txtFloat_Leave;
//txtFloat_Leave(txtfloat.Item((oText.Index)), New System.EventArgs())
}
//Bind the check boxes to the data provider
// For Each oCheck In Me.chkFields
// Set oCheck.DataBindings.Add(adoPrimaryRS)
// Next
//buildDataControls()
mbDataChanged = false;
loadLanguage();
ShowDialog();
// End If
}
private void cmdProcess_Click(System.Object eventSender, System.EventArgs eventArgs)
{
decimal amount = default(decimal);
string sql = null;
string sql1 = null;
ADODB.Recordset rs = default(ADODB.Recordset);
string id = null;
decimal days120 = default(decimal);
decimal days60 = default(decimal);
decimal current = default(decimal);
decimal lAmount = default(decimal);
decimal days30 = default(decimal);
decimal days90 = default(decimal);
decimal days150 = default(decimal);
System.Windows.Forms.Application.DoEvents();
if (string.IsNullOrEmpty(txtNarrative.Text)) {
Interaction.MsgBox("Narrative is a mandarory field", MsgBoxStyle.Exclamation, this.Text);
txtNarrative.Focus();
return;
}
if (Convert.ToDecimal(txtAmount.Text) == 0) {
Interaction.MsgBox("Amount is a mandarory field", MsgBoxStyle.Exclamation, this.Text);
txtAmount.Focus();
return;
}
sql = "INSERT INTO CustomerTransaction ( CustomerTransaction_CustomerID, CustomerTransaction_TransactionTypeID, CustomerTransaction_DayEndID, CustomerTransaction_MonthEndID, CustomerTransaction_ReferenceID, CustomerTransaction_Date, CustomerTransaction_Description, CustomerTransaction_Amount, CustomerTransaction_Reference, CustomerTransaction_PersonName )";
switch (gSection) {
case sec_Payment:
sql = sql + "SELECT " + adoPrimaryRS.Fields("CustomerID").Value + " AS Customer, 3 AS [type], Company.Company_DayEndID, Company.Company_MonthEndID, 0 AS referenceID, Now() AS [Date], '" + Strings.Replace(this.txtNotes.Text, "'", "''") + "' AS description, " + Convert.ToDecimal(0 - Convert.ToDecimal(this.txtAmount.Text)) + " AS amount, '" + Strings.Replace(this.txtNarrative.Text, "'", "''") + "' AS reference, 'System' AS person FROM Company;";
break;
case sec_Debit:
sql = sql + "SELECT " + adoPrimaryRS.Fields("CustomerID").Value + " AS Customer, 4 AS [type], Company.Company_DayEndID, Company.Company_MonthEndID, 0 AS referenceID, Now() AS [Date], '" + Strings.Replace(this.txtNotes.Text, "'", "''") + "' AS description, " + Convert.ToDecimal(this.txtAmount.Text) + " AS amount, '" + Strings.Replace(this.txtNarrative.Text, "'", "''") + "' AS reference, 'System' AS person FROM Company;";
break;
case sec_Credit:
sql = sql + "SELECT " + adoPrimaryRS.Fields("CustomerID").Value + " AS Customer, 5 AS [type], Company.Company_DayEndID, Company.Company_MonthEndID, 0 AS referenceID, Now() AS [Date], '" + Strings.Replace(this.txtNotes.Text, "'", "''") + "' AS description, " + Convert.ToDecimal(0 - Convert.ToDecimal(this.txtAmount.Text)) + " AS amount, '" + Strings.Replace(this.txtNarrative.Text, "'", "''") + "' AS reference, 'System' AS person FROM Company;";
break;
case sec_DebitNote:
sql = sql + "SELECT " + adoPrimaryRS.Fields("CustomerID").Value + " AS Customer, 7 AS [type], Company.Company_DayEndID, Company.Company_MonthEndID, 0 AS referenceID, Now() AS [Date], '" + Strings.Replace(this.txtNotes.Text, "'", "''") + "' AS description, " + Convert.ToDecimal(this.txtAmount.Text) + " AS amount, '" + Strings.Replace(this.txtNarrative.Text, "'", "''") + "' AS reference, 'System' AS person FROM Company;";
break;
case sec_CreditNote:
sql = sql + "SELECT " + adoPrimaryRS.Fields("CustomerID").Value + " AS Customer, 6 AS [type], Company.Company_DayEndID, Company.Company_MonthEndID, 0 AS referenceID, Now() AS [Date], '" + Strings.Replace(this.txtNotes.Text, "'", "''") + "' AS description, " + Convert.ToDecimal(0 - Convert.ToDecimal(this.txtAmount.Text)) + " AS amount, '" + Strings.Replace(this.txtNarrative.Text, "'", "''") + "' AS reference, 'System' AS person FROM Company;";
break;
}
modRecordSet.cnnDB.Execute(sql);
rs = modRecordSet.getRS(ref "SELECT MAX(CustomerTransactionID) AS id From CustomerTransaction");
if (rs.BOF | rs.EOF) {
} else {
id = rs.Fields("id").Value;
modRecordSet.cnnDB.Execute("UPDATE Customer INNER JOIN CustomerTransaction ON Customer.CustomerID = CustomerTransaction.CustomerTransaction_CustomerID SET Customer.Customer_Current = 0 WHERE (((CustomerTransaction.CustomerTransactionID)=" + id + ") AND ((Customer.Customer_Current) Is Null));");
modRecordSet.cnnDB.Execute("UPDATE Customer INNER JOIN CustomerTransaction ON Customer.CustomerID = CustomerTransaction.CustomerTransaction_CustomerID SET Customer.Customer_30Days = 0 WHERE (((CustomerTransaction.CustomerTransactionID)=" + id + ") AND ((Customer.Customer_30Days) Is Null));");
modRecordSet.cnnDB.Execute("UPDATE Customer INNER JOIN CustomerTransaction ON Customer.CustomerID = CustomerTransaction.CustomerTransaction_CustomerID SET Customer.Customer_60Days = 0 WHERE (((CustomerTransaction.CustomerTransactionID)=" + id + ") AND ((Customer.Customer_60Days) Is Null));");
modRecordSet.cnnDB.Execute("UPDATE Customer INNER JOIN CustomerTransaction ON Customer.CustomerID = CustomerTransaction.CustomerTransaction_CustomerID SET Customer.Customer_90Days = 0 WHERE (((CustomerTransaction.CustomerTransactionID)=" + id + ") AND ((Customer.Customer_90Days) Is Null));");
modRecordSet.cnnDB.Execute("UPDATE Customer INNER JOIN CustomerTransaction ON Customer.CustomerID = CustomerTransaction.CustomerTransaction_CustomerID SET Customer.Customer_120Days = 0 WHERE (((CustomerTransaction.CustomerTransactionID)=" + id + ") AND ((Customer.Customer_120Days) Is Null));");
modRecordSet.cnnDB.Execute("UPDATE Customer INNER JOIN CustomerTransaction ON Customer.CustomerID = CustomerTransaction.CustomerTransaction_CustomerID SET Customer.Customer_150Days = 0 WHERE (((CustomerTransaction.CustomerTransactionID)=" + id + ") AND ((Customer.Customer_150Days) Is Null));");
rs = modRecordSet.getRS(ref "SELECT CustomerTransaction.CustomerTransaction_CustomerID, CustomerTransaction.CustomerTransaction_Amount, Customer.Customer_Current, Customer.Customer_30Days, Customer.Customer_60Days, Customer.Customer_90Days, Customer.Customer_120Days, Customer.Customer_150Days FROM Customer INNER JOIN CustomerTransaction ON Customer.CustomerID = CustomerTransaction.CustomerTransaction_CustomerID Where (((CustomerTransaction.CustomerTransactionID) = " + id + "));");
amount = rs.Fields("CustomerTransaction_Amount").Value;
current = rs.Fields("Customer_Current").Value;
days30 = rs.Fields("Customer_30Days").Value;
days60 = rs.Fields("Customer_60Days").Value;
days90 = rs.Fields("Customer_90Days").Value;
days120 = rs.Fields("Customer_120Days").Value;
days150 = rs.Fields("Customer_150Days").Value;
if (amount < 0) {
days150 = days150 + amount;
if ((days150 < 0)) {
amount = days150;
days150 = 0;
} else {
amount = 0;
}
days120 = days120 + amount;
if ((days120 < 0)) {
amount = days120;
days120 = 0;
} else {
amount = 0;
}
days90 = days90 + amount;
if ((days90 < 0)) {
amount = days90;
days90 = 0;
} else {
amount = 0;
}
days60 = days60 + amount;
if ((days60 < 0)) {
amount = days60;
days60 = 0;
} else {
amount = 0;
}
days30 = days30 + amount;
if ((days30 < 0)) {
amount = days30;
days30 = 0;
} else {
amount = 0;
}
}
current = current + amount;
modRecordSet.cnnDB.Execute("UPDATE Customer SET Customer.Customer_Current = " + current + ", Customer.Customer_30Days = " + days30 + ", Customer.Customer_60Days = " + days60 + ", Customer.Customer_90Days = " + days90 + ", Customer.Customer_120Days = " + days120 + ", Customer.Customer_150Days = 0" + days150 + " WHERE (((Customer.CustomerID)=" + rs.Fields("CustomerTransaction_CustomerID").Value + "));");
}
if (Conversion.Val(txtSettlement.Text) > 0) {
sql1 = "INSERT INTO CustomerTransaction ( CustomerTransaction_CustomerID, CustomerTransaction_TransactionTypeID, CustomerTransaction_DayEndID, CustomerTransaction_MonthEndID, CustomerTransaction_ReferenceID, CustomerTransaction_Date, CustomerTransaction_Description, CustomerTransaction_Amount, CustomerTransaction_Reference, CustomerTransaction_PersonName )";
sql1 = sql1 + "SELECT " + adoPrimaryRS.Fields("CustomerID").Value + " AS Customer, 8 AS [type], Company.Company_DayEndID, Company.Company_MonthEndID, 0 AS referenceID, Now() AS [Date], '" + Strings.Replace(this.txtNotes.Text, "'", "''") + "' AS description, " + Convert.ToDecimal(0 - Convert.ToDecimal(this.txtSettlement.Text)) + " AS amount,'" + Strings.Replace(this.txtNarrative.Text, "'", "''") + "', 'System' AS person FROM Company;";
modRecordSet.cnnDB.Execute(sql1);
rs = modRecordSet.getRS(ref "SELECT MAX(CustomerTransactionID) AS id From CustomerTransaction");
if (rs.BOF | rs.EOF) {
} else {
id = rs.Fields("id").Value;
modRecordSet.cnnDB.Execute("UPDATE Customer INNER JOIN CustomerTransaction ON Customer.CustomerID = CustomerTransaction.CustomerTransaction_CustomerID SET Customer.Customer_Current = 0 WHERE (((CustomerTransaction.CustomerTransactionID)=" + id + ") AND ((Customer.Customer_Current) Is Null));");
modRecordSet.cnnDB.Execute("UPDATE Customer INNER JOIN CustomerTransaction ON Customer.CustomerID = CustomerTransaction.CustomerTransaction_CustomerID SET Customer.Customer_30Days = 0 WHERE (((CustomerTransaction.CustomerTransactionID)=" + id + ") AND ((Customer.Customer_30Days) Is Null));");
modRecordSet.cnnDB.Execute("UPDATE Customer INNER JOIN CustomerTransaction ON Customer.CustomerID = CustomerTransaction.CustomerTransaction_CustomerID SET Customer.Customer_60Days = 0 WHERE (((CustomerTransaction.CustomerTransactionID)=" + id + ") AND ((Customer.Customer_60Days) Is Null));");
modRecordSet.cnnDB.Execute("UPDATE Customer INNER JOIN CustomerTransaction ON Customer.CustomerID = CustomerTransaction.CustomerTransaction_CustomerID SET Customer.Customer_90Days = 0 WHERE (((CustomerTransaction.CustomerTransactionID)=" + id + ") AND ((Customer.Customer_90Days) Is Null));");
modRecordSet.cnnDB.Execute("UPDATE Customer INNER JOIN CustomerTransaction ON Customer.CustomerID = CustomerTransaction.CustomerTransaction_CustomerID SET Customer.Customer_120Days = 0 WHERE (((CustomerTransaction.CustomerTransactionID)=" + id + ") AND ((Customer.Customer_120Days) Is Null));");
modRecordSet.cnnDB.Execute("UPDATE Customer INNER JOIN CustomerTransaction ON Customer.CustomerID = CustomerTransaction.CustomerTransaction_CustomerID SET Customer.Customer_150Days = 0 WHERE (((CustomerTransaction.CustomerTransactionID)=" + id + ") AND ((Customer.Customer_150Days) Is Null));");
rs = modRecordSet.getRS(ref "SELECT CustomerTransaction.CustomerTransaction_CustomerID, CustomerTransaction.CustomerTransaction_Amount, Customer.Customer_Current, Customer.Customer_30Days, Customer.Customer_60Days, Customer.Customer_90Days, Customer.Customer_120Days, Customer.Customer_150Days FROM Customer INNER JOIN CustomerTransaction ON Customer.CustomerID = CustomerTransaction.CustomerTransaction_CustomerID Where (((CustomerTransaction.CustomerTransactionID) = " + id + "));");
amount = rs.Fields("CustomerTransaction_Amount").Value;
current = rs.Fields("Customer_Current").Value;
days30 = rs.Fields("Customer_30Days").Value;
days60 = rs.Fields("Customer_60Days").Value;
days90 = rs.Fields("Customer_90Days").Value;
days120 = rs.Fields("Customer_120Days").Value;
days150 = rs.Fields("Customer_150Days").Value;
if (amount < 0) {
days150 = days150 + amount;
if ((days150 < 0)) {
amount = days150;
days150 = 0;
} else {
amount = 0;
}
days120 = days120 + amount;
if ((days120 < 0)) {
amount = days120;
days120 = 0;
} else {
amount = 0;
}
days90 = days90 + amount;
if ((days90 < 0)) {
amount = days90;
days90 = 0;
} else {
amount = 0;
}
days60 = days60 + amount;
if ((days60 < 0)) {
amount = days60;
days60 = 0;
} else {
amount = 0;
}
days30 = days30 + amount;
if ((days30 < 0)) {
amount = days30;
days30 = 0;
} else {
amount = 0;
}
}
current = amount;
modRecordSet.cnnDB.Execute("UPDATE Customer SET Customer.Customer_Current = " + current + ", Customer.Customer_30Days = " + days30 + ", Customer.Customer_60Days = " + days60 + ", Customer.Customer_90Days = " + days90 + ", Customer.Customer_120Days = " + days120 + ", Customer.Customer_150Days = 0" + days150 + " WHERE (((Customer.CustomerID)=" + rs.Fields("CustomerTransaction_CustomerID").Value + "));");
}
}
cmdStatement_Click();
this.Close();
}
private void cmdProcess_Enter(System.Object eventSender, System.EventArgs eventArgs)
{
txtTotalAmount.Text = Strings.FormatNumber(Convert.ToDecimal(txtAmount.Text) + Convert.ToDecimal(txtSettlement.Text), 2);
}
private void cmdStatement_Click()
{
modApplication.report_CustomerNotes(ref adoPrimaryRS.Fields("CustomerID").Value, ref gSection);
}
private void frmCustomerTransactionNotes_Load(object sender, System.EventArgs e)
{
txtFields.AddRange(new TextBox[] {
_txtFields_2,
_txtFields_3,
_txtFields_4,
_txtFields_5,
_txtFields_6,
_txtFields_7,
_txtFields_8,
_txtFields_9,
_txtFields_10
});
txtfloat.AddRange(new TextBox[] {
_txtFloat_12,
_txtFloat_13,
_txtFloat_14,
_txtFloat_15,
_txtFloat_16,
_txtFloat_17,
_txtFloat_18
});
TextBox tb = new TextBox();
foreach (TextBox tb_loopVariable in txtFields) {
tb = tb_loopVariable;
tb.Enter += txtFields_Enter;
}
foreach (TextBox tb_loopVariable in txtfloat) {
tb = tb_loopVariable;
tb.Enter += txtFloat_Enter;
tb.KeyPress += txtFloat_KeyPress;
}
}
private void frmCustomerTransactionNotes_Resize(System.Object eventSender, System.EventArgs eventArgs)
{
Button cmdLast = new Button();
Button cmdnext = new Button();
Label lblStatus = new Label();
// ERROR: Not supported in C#: OnErrorStatement
lblStatus.Width = sizeConvertors.pixelToTwips(this.Width, true) - 1500;
cmdnext.Left = lblStatus.Width + 700;
cmdLast.Left = cmdnext.Left + 340;
}
private void frmCustomerTransactionNotes_KeyDown(System.Object eventSender, System.Windows.Forms.KeyEventArgs eventArgs)
{
short KeyCode = eventArgs.KeyCode;
short Shift = eventArgs.KeyData / 0x10000;
if (mbEditFlag | mbAddNewFlag)
return;
switch (KeyCode) {
case System.Windows.Forms.Keys.Escape:
KeyCode = 0;
System.Windows.Forms.Application.DoEvents();
adoPrimaryRS.Move(0);
cmdClose_Click(cmdClose, new System.EventArgs());
break;
}
}
private void frmCustomerTransactionNotes_FormClosed(System.Object eventSender, System.Windows.Forms.FormClosedEventArgs eventArgs)
{
System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Default;
}
private void adoPrimaryRS_MoveComplete(ADODB.EventReasonEnum adReason, ADODB.Error pError, ref ADODB.EventStatusEnum adStatus, ADODB.Recordset pRecordset)
{
//This will display the current record position for this recordset
}
private void adoPrimaryRS_WillChangeRecord(ADODB.EventReasonEnum adReason, int cRecords, ref ADODB.EventStatusEnum adStatus, ADODB.Recordset pRecordset)
{
//This is where you put validation code
//This event gets called when the following actions occur
bool bCancel = false;
switch (adReason) {
case ADODB.EventReasonEnum.adRsnAddNew:
break;
case ADODB.EventReasonEnum.adRsnClose:
break;
case ADODB.EventReasonEnum.adRsnDelete:
break;
case ADODB.EventReasonEnum.adRsnFirstChange:
break;
case ADODB.EventReasonEnum.adRsnMove:
break;
case ADODB.EventReasonEnum.adRsnRequery:
break;
case ADODB.EventReasonEnum.adRsnResynch:
break;
case ADODB.EventReasonEnum.adRsnUndoAddNew:
break;
case ADODB.EventReasonEnum.adRsnUndoDelete:
break;
case ADODB.EventReasonEnum.adRsnUndoUpdate:
break;
case ADODB.EventReasonEnum.adRsnUpdate:
break;
}
if (bCancel)
adStatus = ADODB.EventStatusEnum.adStatusCancel;
}
private void cmdCancel_Click(System.Object eventSender, System.EventArgs eventArgs)
{
TextBox oText = new TextBox();
// ERROR: Not supported in C#: OnErrorStatement
if (mbAddNewFlag) {
this.Close();
} else {
mbEditFlag = false;
mbAddNewFlag = false;
adoPrimaryRS.CancelUpdate();
if (mvBookMark > 0) {
adoPrimaryRS.Bookmark = mvBookMark;
} else {
adoPrimaryRS.MoveFirst();
}
foreach (TextBox oText_loopVariable in txtfloat) {
oText = oText_loopVariable;
if (string.IsNullOrEmpty(oText.Text))
oText.Text = "0";
oText.Text = oText.Text * 100;
oText.Leave += txtFloat_Leave;
//txtFloat_Leave(txtfloat.Item(oText.Index), New System.EventArgs())
}
mbDataChanged = false;
}
}
private bool update_Renamed()
{
bool functionReturnValue = false;
// ERROR: Not supported in C#: OnErrorStatement
functionReturnValue = true;
return functionReturnValue;
// If _txtFields_2.Text = "" Then
// _txtFields_2.Text = "[Customer]"
// End If
adoPrimaryRS.UpdateBatch(ADODB.AffectEnum.adAffectAll);
if (mbAddNewFlag) {
adoPrimaryRS.MoveLast();
//move to the new record
}
mbEditFlag = false;
mbAddNewFlag = false;
mbDataChanged = false;
return functionReturnValue;
UpdateErr:
Interaction.MsgBox(Err().Description);
functionReturnValue = false;
return functionReturnValue;
}
private void cmdClose_Click(System.Object eventSender, System.EventArgs eventArgs)
{
cmdClose.Focus();
System.Windows.Forms.Application.DoEvents();
if (update_Renamed()) {
this.Close();
}
}
private void txtAmount_Enter(System.Object eventSender, System.EventArgs eventArgs)
{
modUtilities.MyGotFocusNumeric(ref txtAmount.Text());
}
private void txtAmount_KeyPress(System.Object eventSender, System.Windows.Forms.KeyPressEventArgs eventArgs)
{
short KeyAscii = Strings.Asc(eventArgs.KeyChar);
modUtilities.MyKeyPress(ref KeyAscii);
eventArgs.KeyChar = Strings.Chr(KeyAscii);
if (KeyAscii == 0) {
eventArgs.Handled = true;
}
}
private void txtAmount_Leave(System.Object eventSender, System.EventArgs eventArgs)
{
modUtilities.MyLostFocus(ref txtAmount, ref 2);
}
//Handles txtFields.Enter
private void txtFields_Enter(System.Object eventSender, System.EventArgs eventArgs)
{
int Index = 0;
TextBox txtBox = new TextBox();
txtBox = (TextBox)eventSender;
Index = GetIndex.GetIndexer(ref txtBox, ref txtFields);
modUtilities.MyGotFocus(ref txtFields[Index]);
}
private void txtInteger_MyGotFocus(ref short Index)
{
// MyGotFocusNumeric txtInteger(Index)
}
private void txtInteger_KeyPress(ref short Index, ref short KeyAscii)
{
// KeyPress KeyAscii
}
private void txtInteger_MyLostFocus(ref short Index)
{
// LostFocus txtInteger(Index), 0
}
//Handles txtFloat.Enter
private void txtFloat_Enter(System.Object eventSender, System.EventArgs eventArgs)
{
int Index = 0;
TextBox txtBox = new TextBox();
txtBox = (TextBox)eventSender;
Index = GetIndex.GetIndexer(ref txtBox, ref txtfloat);
modUtilities.MyGotFocusNumeric(ref txtfloat[Index]);
}
//Handles txtfloat.
private void txtFloat_KeyPress(System.Object eventSender, System.Windows.Forms.KeyPressEventArgs eventArgs)
{
short KeyAscii = Strings.Asc(eventArgs.KeyChar);
//Dim Index As Short = txtFloat.GetIndex(eventSender)
modUtilities.MyKeyPress(ref KeyAscii);
eventArgs.KeyChar = Strings.Chr(KeyAscii);
if (KeyAscii == 0) {
eventArgs.Handled = true;
}
}
//Handles txtFloat.Leave
private void txtFloat_Leave(System.Object eventSender, System.EventArgs eventArgs)
{
int Index = 0;
TextBox txtBox = new TextBox();
txtBox = (TextBox)eventSender;
Index = GetIndex.GetIndexer(ref txtBox, ref txtfloat);
modUtilities.MyLostFocus(ref txtfloat[Index], ref 2);
}
private void txtNarrative_Enter(System.Object eventSender, System.EventArgs eventArgs)
{
modUtilities.MyGotFocus(ref txtNarrative.Text());
}
private void txtNotes_Enter(System.Object eventSender, System.EventArgs eventArgs)
{
modUtilities.MyGotFocus(ref txtNotes.Text());
}
private void txtSettlement_Enter(System.Object eventSender, System.EventArgs eventArgs)
{
modUtilities.MyGotFocusNumeric(ref txtSettlement.Text());
}
private void txtSettlement_KeyPress(System.Object eventSender, System.Windows.Forms.KeyPressEventArgs eventArgs)
{
short KeyAscii = Strings.Asc(eventArgs.KeyChar);
modUtilities.MyKeyPress(ref KeyAscii);
eventArgs.KeyChar = Strings.Chr(KeyAscii);
if (KeyAscii == 0) {
eventArgs.Handled = true;
}
}
private void txtSettlement_Leave(System.Object eventSender, System.EventArgs eventArgs)
{
modUtilities.MyLostFocus(ref txtSettlement, ref 2);
}
}
}
| |
#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
#if !(NET20 || NET35)
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System;
using System.Linq.Expressions;
using System.Reflection;
using Newtonsoft.Json.Serialization;
namespace Newtonsoft.Json.Utilities
{
internal class ExpressionReflectionDelegateFactory : ReflectionDelegateFactory
{
private static readonly ExpressionReflectionDelegateFactory _instance = new ExpressionReflectionDelegateFactory();
internal static ReflectionDelegateFactory Instance
{
get { return _instance; }
}
public override ObjectConstructor<object> CreateParameterizedConstructor(MethodBase method)
{
ValidationUtils.ArgumentNotNull(method, nameof(method));
Type type = typeof(object);
ParameterExpression argsParameterExpression = Expression.Parameter(typeof(object[]), "args");
Expression callExpression = BuildMethodCall(method, type, null, argsParameterExpression);
LambdaExpression lambdaExpression = Expression.Lambda(typeof(ObjectConstructor<object>), callExpression, argsParameterExpression);
ObjectConstructor<object> compiled = (ObjectConstructor<object>)lambdaExpression.Compile();
return compiled;
}
public override MethodCall<T, object> CreateMethodCall<T>(MethodBase method)
{
ValidationUtils.ArgumentNotNull(method, nameof(method));
Type type = typeof(object);
ParameterExpression targetParameterExpression = Expression.Parameter(type, "target");
ParameterExpression argsParameterExpression = Expression.Parameter(typeof(object[]), "args");
Expression callExpression = BuildMethodCall(method, type, targetParameterExpression, argsParameterExpression);
LambdaExpression lambdaExpression = Expression.Lambda(typeof(MethodCall<T, object>), callExpression, targetParameterExpression, argsParameterExpression);
MethodCall<T, object> compiled = (MethodCall<T, object>)lambdaExpression.Compile();
return compiled;
}
private class ByRefParameter
{
public Expression Value;
public ParameterExpression Variable;
public bool IsOut;
}
private Expression BuildMethodCall(MethodBase method, Type type, ParameterExpression targetParameterExpression, ParameterExpression argsParameterExpression)
{
ParameterInfo[] parametersInfo = method.GetParameters();
Expression[] argsExpression = new Expression[parametersInfo.Length];
IList<ByRefParameter> refParameterMap = new List<ByRefParameter>();
for (int i = 0; i < parametersInfo.Length; i++)
{
ParameterInfo parameter = parametersInfo[i];
Type parameterType = parameter.ParameterType;
bool isByRef = false;
if (parameterType.IsByRef)
{
parameterType = parameterType.GetElementType();
isByRef = true;
}
Expression indexExpression = Expression.Constant(i);
Expression paramAccessorExpression = Expression.ArrayIndex(argsParameterExpression, indexExpression);
Expression argExpression;
if (parameterType.IsValueType())
{
BinaryExpression ensureValueTypeNotNull = Expression.Coalesce(paramAccessorExpression, Expression.New(parameterType));
argExpression = EnsureCastExpression(ensureValueTypeNotNull, parameterType);
}
else
{
argExpression = EnsureCastExpression(paramAccessorExpression, parameterType);
}
if (isByRef)
{
ParameterExpression variable = Expression.Variable(parameterType);
refParameterMap.Add(new ByRefParameter
{
Value = argExpression,
Variable = variable,
IsOut = parameter.IsOut
});
argExpression = variable;
}
argsExpression[i] = argExpression;
}
Expression callExpression;
if (method.IsConstructor)
{
callExpression = Expression.New((ConstructorInfo)method, argsExpression);
}
else if (method.IsStatic)
{
callExpression = Expression.Call((MethodInfo)method, argsExpression);
}
else
{
Expression readParameter = EnsureCastExpression(targetParameterExpression, method.DeclaringType);
callExpression = Expression.Call(readParameter, (MethodInfo)method, argsExpression);
}
if (method is MethodInfo)
{
MethodInfo m = (MethodInfo)method;
if (m.ReturnType != typeof(void))
{
callExpression = EnsureCastExpression(callExpression, type);
}
else
{
callExpression = Expression.Block(callExpression, Expression.Constant(null));
}
}
else
{
callExpression = EnsureCastExpression(callExpression, type);
}
if (refParameterMap.Count > 0)
{
IList<ParameterExpression> variableExpressions = new List<ParameterExpression>();
IList<Expression> bodyExpressions = new List<Expression>();
foreach (ByRefParameter p in refParameterMap)
{
if (!p.IsOut)
{
bodyExpressions.Add(Expression.Assign(p.Variable, p.Value));
}
variableExpressions.Add(p.Variable);
}
bodyExpressions.Add(callExpression);
callExpression = Expression.Block(variableExpressions, bodyExpressions);
}
return callExpression;
}
public override Func<T> CreateDefaultConstructor<T>(Type type)
{
ValidationUtils.ArgumentNotNull(type, "type");
// avoid error from expressions compiler because of abstract class
if (type.IsAbstract())
{
return () => (T)Activator.CreateInstance(type);
}
try
{
Type resultType = typeof(T);
Expression expression = Expression.New(type);
expression = EnsureCastExpression(expression, resultType);
LambdaExpression lambdaExpression = Expression.Lambda(typeof(Func<T>), expression);
Func<T> compiled = (Func<T>)lambdaExpression.Compile();
return compiled;
}
catch
{
// an error can be thrown if constructor is not valid on Win8
// will have INVOCATION_FLAGS_NON_W8P_FX_API invocation flag
return () => (T)Activator.CreateInstance(type);
}
}
public override Func<T, object> CreateGet<T>(PropertyInfo propertyInfo)
{
ValidationUtils.ArgumentNotNull(propertyInfo, nameof(propertyInfo));
Type instanceType = typeof(T);
Type resultType = typeof(object);
ParameterExpression parameterExpression = Expression.Parameter(instanceType, "instance");
Expression resultExpression;
MethodInfo getMethod = propertyInfo.GetGetMethod(true);
if (getMethod.IsStatic)
{
resultExpression = Expression.MakeMemberAccess(null, propertyInfo);
}
else
{
Expression readParameter = EnsureCastExpression(parameterExpression, propertyInfo.DeclaringType);
resultExpression = Expression.MakeMemberAccess(readParameter, propertyInfo);
}
resultExpression = EnsureCastExpression(resultExpression, resultType);
LambdaExpression lambdaExpression = Expression.Lambda(typeof(Func<T, object>), resultExpression, parameterExpression);
Func<T, object> compiled = (Func<T, object>)lambdaExpression.Compile();
return compiled;
}
public override Func<T, object> CreateGet<T>(FieldInfo fieldInfo)
{
ValidationUtils.ArgumentNotNull(fieldInfo, nameof(fieldInfo));
ParameterExpression sourceParameter = Expression.Parameter(typeof(T), "source");
Expression fieldExpression;
if (fieldInfo.IsStatic)
{
fieldExpression = Expression.Field(null, fieldInfo);
}
else
{
Expression sourceExpression = EnsureCastExpression(sourceParameter, fieldInfo.DeclaringType);
fieldExpression = Expression.Field(sourceExpression, fieldInfo);
}
fieldExpression = EnsureCastExpression(fieldExpression, typeof(object));
Func<T, object> compiled = Expression.Lambda<Func<T, object>>(fieldExpression, sourceParameter).Compile();
return compiled;
}
public override Action<T, object> CreateSet<T>(FieldInfo fieldInfo)
{
ValidationUtils.ArgumentNotNull(fieldInfo, nameof(fieldInfo));
// use reflection for structs
// expression doesn't correctly set value
if (fieldInfo.DeclaringType.IsValueType() || fieldInfo.IsInitOnly)
{
return LateBoundReflectionDelegateFactory.Instance.CreateSet<T>(fieldInfo);
}
ParameterExpression sourceParameterExpression = Expression.Parameter(typeof(T), "source");
ParameterExpression valueParameterExpression = Expression.Parameter(typeof(object), "value");
Expression fieldExpression;
if (fieldInfo.IsStatic)
{
fieldExpression = Expression.Field(null, fieldInfo);
}
else
{
Expression sourceExpression = EnsureCastExpression(sourceParameterExpression, fieldInfo.DeclaringType);
fieldExpression = Expression.Field(sourceExpression, fieldInfo);
}
Expression valueExpression = EnsureCastExpression(valueParameterExpression, fieldExpression.Type);
BinaryExpression assignExpression = Expression.Assign(fieldExpression, valueExpression);
LambdaExpression lambdaExpression = Expression.Lambda(typeof(Action<T, object>), assignExpression, sourceParameterExpression, valueParameterExpression);
Action<T, object> compiled = (Action<T, object>)lambdaExpression.Compile();
return compiled;
}
public override Action<T, object> CreateSet<T>(PropertyInfo propertyInfo)
{
ValidationUtils.ArgumentNotNull(propertyInfo, nameof(propertyInfo));
// use reflection for structs
// expression doesn't correctly set value
if (propertyInfo.DeclaringType.IsValueType())
{
return LateBoundReflectionDelegateFactory.Instance.CreateSet<T>(propertyInfo);
}
Type instanceType = typeof(T);
Type valueType = typeof(object);
ParameterExpression instanceParameter = Expression.Parameter(instanceType, "instance");
ParameterExpression valueParameter = Expression.Parameter(valueType, "value");
Expression readValueParameter = EnsureCastExpression(valueParameter, propertyInfo.PropertyType);
MethodInfo setMethod = propertyInfo.GetSetMethod(true);
Expression setExpression;
if (setMethod.IsStatic)
{
setExpression = Expression.Call(setMethod, readValueParameter);
}
else
{
Expression readInstanceParameter = EnsureCastExpression(instanceParameter, propertyInfo.DeclaringType);
setExpression = Expression.Call(readInstanceParameter, setMethod, readValueParameter);
}
LambdaExpression lambdaExpression = Expression.Lambda(typeof(Action<T, object>), setExpression, instanceParameter, valueParameter);
Action<T, object> compiled = (Action<T, object>)lambdaExpression.Compile();
return compiled;
}
private Expression EnsureCastExpression(Expression expression, Type targetType)
{
Type expressionType = expression.Type;
// check if a cast or conversion is required
if (expressionType == targetType || (!expressionType.IsValueType() && targetType.IsAssignableFrom(expressionType)))
{
return expression;
}
return Expression.Convert(expression, targetType);
}
}
}
#endif
| |
using System;
using System.Collections.Specialized;
using gov.va.medora.mdo;
using gov.va.medora.mdo.api;
using gov.va.medora.mdo.dao;
using gov.va.medora.mdws.dto;
using System.Configuration;
using System.Xml;
using System.Reflection;
using System.IO;
using System.Web;
using gov.va.medora.mdws.conf;
using System.Collections.Generic;
using gov.va.medora.mdo.domain.pool.connection;
using gov.va.medora.mdo.dao.vista;
namespace gov.va.medora.mdws
{
[Serializable]
public class MySession
{
// REST
public string Token { get; set; }
public DateTime LastUsed { get; set; }
//Dictionary<string, AbstractConnection> _authCxns;
//public Dictionary<string, AbstractConnection> AuthenticatedConnections
//{
// get
// {
// if (_authCxns == null)
// {
// _authCxns = new Dictionary<string, AbstractConnection>();
// }
// return _authCxns;
// }
// set { _authCxns = value; }
//}
// END REST
MdwsConfiguration _mdwsConfig;
string _facadeName;
SiteTable _siteTable;
// set outside class
ConnectionSet _cxnSet = new ConnectionSet();
User _user;
AbstractCredentials _credentials;
string _defaultVisitMethod;
public bool _excludeSite200;
string _defaultPermissionString;
AbstractPermission _primaryPermission;
Patient _patient;
//public ILog log;
public MySession()
{
_mdwsConfig = new MdwsConfiguration();
_defaultVisitMethod = _mdwsConfig.AllConfigs[MdwsConfigConstants.MDWS_CONFIG_SECTION][MdwsConfigConstants.DEFAULT_VISIT_METHOD];
_defaultPermissionString = _mdwsConfig.AllConfigs[MdwsConfigConstants.MDWS_CONFIG_SECTION][MdwsConfigConstants.DEFAULT_CONTEXT];
try
{
_siteTable = new mdo.SiteTable(_mdwsConfig.ResourcesPath + "xml\\" + _mdwsConfig.FacadeConfiguration.SitesFileName);
}
catch (Exception) { /* SiteTable is going to be null - how do we let the user know?? */ }
}
/// <summary>
/// Every client application requesting a MDWS session (invokes a function with EnableSession = True attribute) passes
/// through this point. Fetches facade configuration settings and sets up session for subsequent calls
/// </summary>
/// <param name="facadeName">The facade name being invoked (e.g. EmrSvc)</param>
/// <exception cref="System.Configuration.ConfigurationErrorsException" />
public MySession(string facadeName)
{
this._facadeName = facadeName;
_mdwsConfig = new MdwsConfiguration(facadeName);
_defaultVisitMethod = _mdwsConfig.AllConfigs[MdwsConfigConstants.MDWS_CONFIG_SECTION][MdwsConfigConstants.DEFAULT_VISIT_METHOD];
_defaultPermissionString = _mdwsConfig.AllConfigs[MdwsConfigConstants.MDWS_CONFIG_SECTION][MdwsConfigConstants.DEFAULT_CONTEXT];
_excludeSite200 = String.Equals("true", _mdwsConfig.AllConfigs[MdwsConfigConstants.MDWS_CONFIG_SECTION][MdwsConfigConstants.EXCLUDE_SITE_200],
StringComparison.CurrentCultureIgnoreCase);
try
{
_siteTable = new mdo.SiteTable(_mdwsConfig.ResourcesPath + "xml\\" + _mdwsConfig.FacadeConfiguration.SitesFileName);
watchSitesFile(_mdwsConfig.ResourcesPath + "xml\\");
}
catch (Exception) { /* SiteTable is going to be null - how do we let the user know?? */ }
}
/// <summary>
/// Allow a client application to specifiy their sites file by name
/// </summary>
/// <param name="sitesFileName">The name of the sites file</param>
/// <returns>SiteArray of parsed sites file</returns>
public SiteArray setSites(string sitesFileName)
{
SiteArray result = new SiteArray();
try
{
_siteTable = new mdo.SiteTable(_mdwsConfig.ResourcesPath + "xml\\" + sitesFileName);
_mdwsConfig.FacadeConfiguration.SitesFileName = sitesFileName;
watchSitesFile(_mdwsConfig.ResourcesPath + "xml\\");
result = new SiteArray(_siteTable.Sites);
}
catch (Exception)
{
result.fault = new FaultTO("A sites file with that name does not exist on the server!");
}
return result;
}
#region Setters and Getters
public MdwsConfiguration MdwsConfiguration
{
get { return _mdwsConfig; }
}
public string FacadeName
{
get { return _facadeName; }
}
public SiteTable SiteTable
{
get { return _siteTable; }
}
public ConnectionSet ConnectionSet
{
get { return _cxnSet ?? (_cxnSet = new ConnectionSet()); }
set { _cxnSet = value; }
}
/// <summary>
/// Call this function after all connections in ConnectionSet have been authenticated to set the session state for each of the connections
/// </summary>
internal void setAuthorized()
{
if (null == _cxnSet || 0 == _cxnSet.Count)
{
throw new ArgumentException("No connections!");
}
if (this.Sessions == null)
{
this.Sessions = new VistaStates();
}
foreach (string key in _cxnSet.Connections.Keys)
{
this.Sessions.setState(key, new VistaState(_cxnSet.Connections[key].getState()));
}
}
/// <summary>
/// Call this function after all connections in ConnectionSet have been authenticated to set the session state for each of the connections
/// </summary>
internal void setAuthorized(string id)
{
if (null == _cxnSet || 0 == _cxnSet.Count || null == _cxnSet.Connections || !_cxnSet.Connections.ContainsKey(id))
{
throw new ArgumentException("No connections!");
}
if (this.Sessions == null)
{
this.Sessions = new VistaStates();
}
this.Sessions.setState(id, new VistaState(_cxnSet.Connections[id].getState()));
}
public User User
{
get { return _user; }
set { _user = value; }
}
public Patient Patient
{
get { return _patient; }
set { _patient = value; }
}
public AbstractCredentials Credentials
{
get { return _credentials; }
set { _credentials = value; }
}
public string DefaultPermissionString
{
get { return _defaultPermissionString; }
set { _defaultPermissionString = value; }
}
public AbstractPermission PrimaryPermission
{
get { return _primaryPermission; }
set
{
_primaryPermission = value;
_primaryPermission.IsPrimary = true;
}
}
/// <summary>
/// Defaults to MdwsConstants.BSE_CREDENTIALS_V2WEB if configuration key is not found in web.config
/// </summary>
public string DefaultVisitMethod
{
get { return String.IsNullOrEmpty(_defaultVisitMethod) ? MdwsConstants.BSE_CREDENTIALS_V2WEB : _defaultVisitMethod; }
set { _defaultVisitMethod = value; }
}
#endregion
public Object execute(string className, string methodName, object[] args)
{
string userIdStr = "";
//if (_user != null)
//{
// userIdStr = _user.LogonSiteId.Id + '/' + _user.Uid + ": ";
//}
string fullClassName = className;
if (!fullClassName.StartsWith("gov."))
{
fullClassName = "gov.va.medora.mdws." + fullClassName;
}
Object theLib = Activator.CreateInstance(Type.GetType(fullClassName), new object[] { this });
Type theClass = theLib.GetType();
Type[] theParamTypes = new Type[args.Length];
for (int i = 0; i < args.Length; i++)
{
theParamTypes[i] = args[i].GetType();
}
MethodInfo theMethod = theClass.GetMethod(methodName, theParamTypes);
Object result = null;
if (theMethod == null)
{
result = new Exception("Method " + className + " " + methodName + " does not exist.");
}
try
{
result = theMethod.Invoke(theLib, BindingFlags.InvokeMethod, null, args, null);
}
catch (Exception e)
{
if (e.GetType().IsAssignableFrom(typeof(System.Reflection.TargetInvocationException)) &&
e.InnerException != null)
{
result = e.InnerException;
}
else
{
result = e;
}
return result;
}
return result;
}
public bool HasBaseConnection
{
get
{
if (_cxnSet == null)
{
return false;
}
return _cxnSet.HasBaseConnection;
}
}
public void close()
{
_cxnSet.disconnectAll();
_user = null;
_patient = null;
}
void watchSitesFile(string path)
{
// This needs to be finished and tested before we implement - #2829
//if (_mdwsConfig == null || _mdwsConfig.AllConfigs == null || !_mdwsConfig.AllConfigs.ContainsKey(MdwsConfigConstants.MDWS_CONFIG_SECTION)
// || !_mdwsConfig.AllConfigs[MdwsConfigConstants.MDWS_CONFIG_SECTION].ContainsKey(MdwsConfigConstants.WATCH_SITES_FILE))
//{
// return;
//}
//bool watchFile = false;
//Boolean.TryParse(_mdwsConfig.AllConfigs[MdwsConfigConstants.MDWS_CONFIG_SECTION][MdwsConfigConstants.WATCH_SITES_FILE], out watchFile);
//if (!watchFile)
//{
// return;
//}
FileSystemWatcher watcher = new FileSystemWatcher(path);
watcher.Filter = (_mdwsConfig.FacadeConfiguration.SitesFileName);
watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.CreationTime
| NotifyFilters.DirectoryName | NotifyFilters.FileName | NotifyFilters.Size;
watcher.EnableRaisingEvents = true;
watcher.Changed += new FileSystemEventHandler(watcher_Changed);
watcher.Deleted += new FileSystemEventHandler(watcher_Changed);
watcher.Created += new FileSystemEventHandler(watcher_Changed);
}
void watcher_Changed(object sender, FileSystemEventArgs e)
{
_siteTable = new SiteTable(_mdwsConfig.ResourcesPath + "xml\\" + _mdwsConfig.FacadeConfiguration.SitesFileName);
}
public bool hasExpired()
{
if (DateTime.Now.Subtract(this.LastUsed).CompareTo(this.MdwsConfiguration.TimeOut) > 0)
{
return true;
}
return false;
}
public AbstractStates Sessions { get; set; }
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gaxgrpc = Google.Api.Gax.Grpc;
using wkt = Google.Protobuf.WellKnownTypes;
using grpccore = Grpc.Core;
using moq = Moq;
using st = System.Threading;
using stt = System.Threading.Tasks;
using xunit = Xunit;
namespace Google.Cloud.Dialogflow.Cx.V3.Tests
{
/// <summary>Generated unit tests.</summary>
public sealed class GeneratedExperimentsClientTest
{
[xunit::FactAttribute]
public void GetExperimentRequestObject()
{
moq::Mock<Experiments.ExperimentsClient> mockGrpcClient = new moq::Mock<Experiments.ExperimentsClient>(moq::MockBehavior.Strict);
GetExperimentRequest request = new GetExperimentRequest
{
ExperimentName = ExperimentName.FromProjectLocationAgentEnvironmentExperiment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]", "[EXPERIMENT]"),
};
Experiment expectedResponse = new Experiment
{
ExperimentName = ExperimentName.FromProjectLocationAgentEnvironmentExperiment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]", "[EXPERIMENT]"),
DisplayName = "display_name137f65c2",
Description = "description2cf9da67",
State = Experiment.Types.State.Done,
Definition = new Experiment.Types.Definition(),
Result = new Experiment.Types.Result(),
CreateTime = new wkt::Timestamp(),
StartTime = new wkt::Timestamp(),
EndTime = new wkt::Timestamp(),
LastUpdateTime = new wkt::Timestamp(),
ExperimentLength = new wkt::Duration(),
VariantsHistory =
{
new VariantsHistory(),
},
RolloutConfig = new RolloutConfig(),
RolloutState = new RolloutState(),
RolloutFailureReason = "rollout_failure_reason2f2db6d3",
};
mockGrpcClient.Setup(x => x.GetExperiment(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ExperimentsClient client = new ExperimentsClientImpl(mockGrpcClient.Object, null);
Experiment response = client.GetExperiment(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetExperimentRequestObjectAsync()
{
moq::Mock<Experiments.ExperimentsClient> mockGrpcClient = new moq::Mock<Experiments.ExperimentsClient>(moq::MockBehavior.Strict);
GetExperimentRequest request = new GetExperimentRequest
{
ExperimentName = ExperimentName.FromProjectLocationAgentEnvironmentExperiment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]", "[EXPERIMENT]"),
};
Experiment expectedResponse = new Experiment
{
ExperimentName = ExperimentName.FromProjectLocationAgentEnvironmentExperiment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]", "[EXPERIMENT]"),
DisplayName = "display_name137f65c2",
Description = "description2cf9da67",
State = Experiment.Types.State.Done,
Definition = new Experiment.Types.Definition(),
Result = new Experiment.Types.Result(),
CreateTime = new wkt::Timestamp(),
StartTime = new wkt::Timestamp(),
EndTime = new wkt::Timestamp(),
LastUpdateTime = new wkt::Timestamp(),
ExperimentLength = new wkt::Duration(),
VariantsHistory =
{
new VariantsHistory(),
},
RolloutConfig = new RolloutConfig(),
RolloutState = new RolloutState(),
RolloutFailureReason = "rollout_failure_reason2f2db6d3",
};
mockGrpcClient.Setup(x => x.GetExperimentAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Experiment>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ExperimentsClient client = new ExperimentsClientImpl(mockGrpcClient.Object, null);
Experiment responseCallSettings = await client.GetExperimentAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Experiment responseCancellationToken = await client.GetExperimentAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetExperiment()
{
moq::Mock<Experiments.ExperimentsClient> mockGrpcClient = new moq::Mock<Experiments.ExperimentsClient>(moq::MockBehavior.Strict);
GetExperimentRequest request = new GetExperimentRequest
{
ExperimentName = ExperimentName.FromProjectLocationAgentEnvironmentExperiment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]", "[EXPERIMENT]"),
};
Experiment expectedResponse = new Experiment
{
ExperimentName = ExperimentName.FromProjectLocationAgentEnvironmentExperiment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]", "[EXPERIMENT]"),
DisplayName = "display_name137f65c2",
Description = "description2cf9da67",
State = Experiment.Types.State.Done,
Definition = new Experiment.Types.Definition(),
Result = new Experiment.Types.Result(),
CreateTime = new wkt::Timestamp(),
StartTime = new wkt::Timestamp(),
EndTime = new wkt::Timestamp(),
LastUpdateTime = new wkt::Timestamp(),
ExperimentLength = new wkt::Duration(),
VariantsHistory =
{
new VariantsHistory(),
},
RolloutConfig = new RolloutConfig(),
RolloutState = new RolloutState(),
RolloutFailureReason = "rollout_failure_reason2f2db6d3",
};
mockGrpcClient.Setup(x => x.GetExperiment(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ExperimentsClient client = new ExperimentsClientImpl(mockGrpcClient.Object, null);
Experiment response = client.GetExperiment(request.Name);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetExperimentAsync()
{
moq::Mock<Experiments.ExperimentsClient> mockGrpcClient = new moq::Mock<Experiments.ExperimentsClient>(moq::MockBehavior.Strict);
GetExperimentRequest request = new GetExperimentRequest
{
ExperimentName = ExperimentName.FromProjectLocationAgentEnvironmentExperiment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]", "[EXPERIMENT]"),
};
Experiment expectedResponse = new Experiment
{
ExperimentName = ExperimentName.FromProjectLocationAgentEnvironmentExperiment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]", "[EXPERIMENT]"),
DisplayName = "display_name137f65c2",
Description = "description2cf9da67",
State = Experiment.Types.State.Done,
Definition = new Experiment.Types.Definition(),
Result = new Experiment.Types.Result(),
CreateTime = new wkt::Timestamp(),
StartTime = new wkt::Timestamp(),
EndTime = new wkt::Timestamp(),
LastUpdateTime = new wkt::Timestamp(),
ExperimentLength = new wkt::Duration(),
VariantsHistory =
{
new VariantsHistory(),
},
RolloutConfig = new RolloutConfig(),
RolloutState = new RolloutState(),
RolloutFailureReason = "rollout_failure_reason2f2db6d3",
};
mockGrpcClient.Setup(x => x.GetExperimentAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Experiment>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ExperimentsClient client = new ExperimentsClientImpl(mockGrpcClient.Object, null);
Experiment responseCallSettings = await client.GetExperimentAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Experiment responseCancellationToken = await client.GetExperimentAsync(request.Name, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetExperimentResourceNames()
{
moq::Mock<Experiments.ExperimentsClient> mockGrpcClient = new moq::Mock<Experiments.ExperimentsClient>(moq::MockBehavior.Strict);
GetExperimentRequest request = new GetExperimentRequest
{
ExperimentName = ExperimentName.FromProjectLocationAgentEnvironmentExperiment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]", "[EXPERIMENT]"),
};
Experiment expectedResponse = new Experiment
{
ExperimentName = ExperimentName.FromProjectLocationAgentEnvironmentExperiment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]", "[EXPERIMENT]"),
DisplayName = "display_name137f65c2",
Description = "description2cf9da67",
State = Experiment.Types.State.Done,
Definition = new Experiment.Types.Definition(),
Result = new Experiment.Types.Result(),
CreateTime = new wkt::Timestamp(),
StartTime = new wkt::Timestamp(),
EndTime = new wkt::Timestamp(),
LastUpdateTime = new wkt::Timestamp(),
ExperimentLength = new wkt::Duration(),
VariantsHistory =
{
new VariantsHistory(),
},
RolloutConfig = new RolloutConfig(),
RolloutState = new RolloutState(),
RolloutFailureReason = "rollout_failure_reason2f2db6d3",
};
mockGrpcClient.Setup(x => x.GetExperiment(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ExperimentsClient client = new ExperimentsClientImpl(mockGrpcClient.Object, null);
Experiment response = client.GetExperiment(request.ExperimentName);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetExperimentResourceNamesAsync()
{
moq::Mock<Experiments.ExperimentsClient> mockGrpcClient = new moq::Mock<Experiments.ExperimentsClient>(moq::MockBehavior.Strict);
GetExperimentRequest request = new GetExperimentRequest
{
ExperimentName = ExperimentName.FromProjectLocationAgentEnvironmentExperiment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]", "[EXPERIMENT]"),
};
Experiment expectedResponse = new Experiment
{
ExperimentName = ExperimentName.FromProjectLocationAgentEnvironmentExperiment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]", "[EXPERIMENT]"),
DisplayName = "display_name137f65c2",
Description = "description2cf9da67",
State = Experiment.Types.State.Done,
Definition = new Experiment.Types.Definition(),
Result = new Experiment.Types.Result(),
CreateTime = new wkt::Timestamp(),
StartTime = new wkt::Timestamp(),
EndTime = new wkt::Timestamp(),
LastUpdateTime = new wkt::Timestamp(),
ExperimentLength = new wkt::Duration(),
VariantsHistory =
{
new VariantsHistory(),
},
RolloutConfig = new RolloutConfig(),
RolloutState = new RolloutState(),
RolloutFailureReason = "rollout_failure_reason2f2db6d3",
};
mockGrpcClient.Setup(x => x.GetExperimentAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Experiment>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ExperimentsClient client = new ExperimentsClientImpl(mockGrpcClient.Object, null);
Experiment responseCallSettings = await client.GetExperimentAsync(request.ExperimentName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Experiment responseCancellationToken = await client.GetExperimentAsync(request.ExperimentName, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void CreateExperimentRequestObject()
{
moq::Mock<Experiments.ExperimentsClient> mockGrpcClient = new moq::Mock<Experiments.ExperimentsClient>(moq::MockBehavior.Strict);
CreateExperimentRequest request = new CreateExperimentRequest
{
ParentAsEnvironmentName = EnvironmentName.FromProjectLocationAgentEnvironment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]"),
Experiment = new Experiment(),
};
Experiment expectedResponse = new Experiment
{
ExperimentName = ExperimentName.FromProjectLocationAgentEnvironmentExperiment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]", "[EXPERIMENT]"),
DisplayName = "display_name137f65c2",
Description = "description2cf9da67",
State = Experiment.Types.State.Done,
Definition = new Experiment.Types.Definition(),
Result = new Experiment.Types.Result(),
CreateTime = new wkt::Timestamp(),
StartTime = new wkt::Timestamp(),
EndTime = new wkt::Timestamp(),
LastUpdateTime = new wkt::Timestamp(),
ExperimentLength = new wkt::Duration(),
VariantsHistory =
{
new VariantsHistory(),
},
RolloutConfig = new RolloutConfig(),
RolloutState = new RolloutState(),
RolloutFailureReason = "rollout_failure_reason2f2db6d3",
};
mockGrpcClient.Setup(x => x.CreateExperiment(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ExperimentsClient client = new ExperimentsClientImpl(mockGrpcClient.Object, null);
Experiment response = client.CreateExperiment(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CreateExperimentRequestObjectAsync()
{
moq::Mock<Experiments.ExperimentsClient> mockGrpcClient = new moq::Mock<Experiments.ExperimentsClient>(moq::MockBehavior.Strict);
CreateExperimentRequest request = new CreateExperimentRequest
{
ParentAsEnvironmentName = EnvironmentName.FromProjectLocationAgentEnvironment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]"),
Experiment = new Experiment(),
};
Experiment expectedResponse = new Experiment
{
ExperimentName = ExperimentName.FromProjectLocationAgentEnvironmentExperiment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]", "[EXPERIMENT]"),
DisplayName = "display_name137f65c2",
Description = "description2cf9da67",
State = Experiment.Types.State.Done,
Definition = new Experiment.Types.Definition(),
Result = new Experiment.Types.Result(),
CreateTime = new wkt::Timestamp(),
StartTime = new wkt::Timestamp(),
EndTime = new wkt::Timestamp(),
LastUpdateTime = new wkt::Timestamp(),
ExperimentLength = new wkt::Duration(),
VariantsHistory =
{
new VariantsHistory(),
},
RolloutConfig = new RolloutConfig(),
RolloutState = new RolloutState(),
RolloutFailureReason = "rollout_failure_reason2f2db6d3",
};
mockGrpcClient.Setup(x => x.CreateExperimentAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Experiment>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ExperimentsClient client = new ExperimentsClientImpl(mockGrpcClient.Object, null);
Experiment responseCallSettings = await client.CreateExperimentAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Experiment responseCancellationToken = await client.CreateExperimentAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void CreateExperiment()
{
moq::Mock<Experiments.ExperimentsClient> mockGrpcClient = new moq::Mock<Experiments.ExperimentsClient>(moq::MockBehavior.Strict);
CreateExperimentRequest request = new CreateExperimentRequest
{
ParentAsEnvironmentName = EnvironmentName.FromProjectLocationAgentEnvironment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]"),
Experiment = new Experiment(),
};
Experiment expectedResponse = new Experiment
{
ExperimentName = ExperimentName.FromProjectLocationAgentEnvironmentExperiment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]", "[EXPERIMENT]"),
DisplayName = "display_name137f65c2",
Description = "description2cf9da67",
State = Experiment.Types.State.Done,
Definition = new Experiment.Types.Definition(),
Result = new Experiment.Types.Result(),
CreateTime = new wkt::Timestamp(),
StartTime = new wkt::Timestamp(),
EndTime = new wkt::Timestamp(),
LastUpdateTime = new wkt::Timestamp(),
ExperimentLength = new wkt::Duration(),
VariantsHistory =
{
new VariantsHistory(),
},
RolloutConfig = new RolloutConfig(),
RolloutState = new RolloutState(),
RolloutFailureReason = "rollout_failure_reason2f2db6d3",
};
mockGrpcClient.Setup(x => x.CreateExperiment(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ExperimentsClient client = new ExperimentsClientImpl(mockGrpcClient.Object, null);
Experiment response = client.CreateExperiment(request.Parent, request.Experiment);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CreateExperimentAsync()
{
moq::Mock<Experiments.ExperimentsClient> mockGrpcClient = new moq::Mock<Experiments.ExperimentsClient>(moq::MockBehavior.Strict);
CreateExperimentRequest request = new CreateExperimentRequest
{
ParentAsEnvironmentName = EnvironmentName.FromProjectLocationAgentEnvironment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]"),
Experiment = new Experiment(),
};
Experiment expectedResponse = new Experiment
{
ExperimentName = ExperimentName.FromProjectLocationAgentEnvironmentExperiment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]", "[EXPERIMENT]"),
DisplayName = "display_name137f65c2",
Description = "description2cf9da67",
State = Experiment.Types.State.Done,
Definition = new Experiment.Types.Definition(),
Result = new Experiment.Types.Result(),
CreateTime = new wkt::Timestamp(),
StartTime = new wkt::Timestamp(),
EndTime = new wkt::Timestamp(),
LastUpdateTime = new wkt::Timestamp(),
ExperimentLength = new wkt::Duration(),
VariantsHistory =
{
new VariantsHistory(),
},
RolloutConfig = new RolloutConfig(),
RolloutState = new RolloutState(),
RolloutFailureReason = "rollout_failure_reason2f2db6d3",
};
mockGrpcClient.Setup(x => x.CreateExperimentAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Experiment>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ExperimentsClient client = new ExperimentsClientImpl(mockGrpcClient.Object, null);
Experiment responseCallSettings = await client.CreateExperimentAsync(request.Parent, request.Experiment, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Experiment responseCancellationToken = await client.CreateExperimentAsync(request.Parent, request.Experiment, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void CreateExperimentResourceNames()
{
moq::Mock<Experiments.ExperimentsClient> mockGrpcClient = new moq::Mock<Experiments.ExperimentsClient>(moq::MockBehavior.Strict);
CreateExperimentRequest request = new CreateExperimentRequest
{
ParentAsEnvironmentName = EnvironmentName.FromProjectLocationAgentEnvironment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]"),
Experiment = new Experiment(),
};
Experiment expectedResponse = new Experiment
{
ExperimentName = ExperimentName.FromProjectLocationAgentEnvironmentExperiment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]", "[EXPERIMENT]"),
DisplayName = "display_name137f65c2",
Description = "description2cf9da67",
State = Experiment.Types.State.Done,
Definition = new Experiment.Types.Definition(),
Result = new Experiment.Types.Result(),
CreateTime = new wkt::Timestamp(),
StartTime = new wkt::Timestamp(),
EndTime = new wkt::Timestamp(),
LastUpdateTime = new wkt::Timestamp(),
ExperimentLength = new wkt::Duration(),
VariantsHistory =
{
new VariantsHistory(),
},
RolloutConfig = new RolloutConfig(),
RolloutState = new RolloutState(),
RolloutFailureReason = "rollout_failure_reason2f2db6d3",
};
mockGrpcClient.Setup(x => x.CreateExperiment(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ExperimentsClient client = new ExperimentsClientImpl(mockGrpcClient.Object, null);
Experiment response = client.CreateExperiment(request.ParentAsEnvironmentName, request.Experiment);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CreateExperimentResourceNamesAsync()
{
moq::Mock<Experiments.ExperimentsClient> mockGrpcClient = new moq::Mock<Experiments.ExperimentsClient>(moq::MockBehavior.Strict);
CreateExperimentRequest request = new CreateExperimentRequest
{
ParentAsEnvironmentName = EnvironmentName.FromProjectLocationAgentEnvironment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]"),
Experiment = new Experiment(),
};
Experiment expectedResponse = new Experiment
{
ExperimentName = ExperimentName.FromProjectLocationAgentEnvironmentExperiment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]", "[EXPERIMENT]"),
DisplayName = "display_name137f65c2",
Description = "description2cf9da67",
State = Experiment.Types.State.Done,
Definition = new Experiment.Types.Definition(),
Result = new Experiment.Types.Result(),
CreateTime = new wkt::Timestamp(),
StartTime = new wkt::Timestamp(),
EndTime = new wkt::Timestamp(),
LastUpdateTime = new wkt::Timestamp(),
ExperimentLength = new wkt::Duration(),
VariantsHistory =
{
new VariantsHistory(),
},
RolloutConfig = new RolloutConfig(),
RolloutState = new RolloutState(),
RolloutFailureReason = "rollout_failure_reason2f2db6d3",
};
mockGrpcClient.Setup(x => x.CreateExperimentAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Experiment>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ExperimentsClient client = new ExperimentsClientImpl(mockGrpcClient.Object, null);
Experiment responseCallSettings = await client.CreateExperimentAsync(request.ParentAsEnvironmentName, request.Experiment, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Experiment responseCancellationToken = await client.CreateExperimentAsync(request.ParentAsEnvironmentName, request.Experiment, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void UpdateExperimentRequestObject()
{
moq::Mock<Experiments.ExperimentsClient> mockGrpcClient = new moq::Mock<Experiments.ExperimentsClient>(moq::MockBehavior.Strict);
UpdateExperimentRequest request = new UpdateExperimentRequest
{
Experiment = new Experiment(),
UpdateMask = new wkt::FieldMask(),
};
Experiment expectedResponse = new Experiment
{
ExperimentName = ExperimentName.FromProjectLocationAgentEnvironmentExperiment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]", "[EXPERIMENT]"),
DisplayName = "display_name137f65c2",
Description = "description2cf9da67",
State = Experiment.Types.State.Done,
Definition = new Experiment.Types.Definition(),
Result = new Experiment.Types.Result(),
CreateTime = new wkt::Timestamp(),
StartTime = new wkt::Timestamp(),
EndTime = new wkt::Timestamp(),
LastUpdateTime = new wkt::Timestamp(),
ExperimentLength = new wkt::Duration(),
VariantsHistory =
{
new VariantsHistory(),
},
RolloutConfig = new RolloutConfig(),
RolloutState = new RolloutState(),
RolloutFailureReason = "rollout_failure_reason2f2db6d3",
};
mockGrpcClient.Setup(x => x.UpdateExperiment(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ExperimentsClient client = new ExperimentsClientImpl(mockGrpcClient.Object, null);
Experiment response = client.UpdateExperiment(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task UpdateExperimentRequestObjectAsync()
{
moq::Mock<Experiments.ExperimentsClient> mockGrpcClient = new moq::Mock<Experiments.ExperimentsClient>(moq::MockBehavior.Strict);
UpdateExperimentRequest request = new UpdateExperimentRequest
{
Experiment = new Experiment(),
UpdateMask = new wkt::FieldMask(),
};
Experiment expectedResponse = new Experiment
{
ExperimentName = ExperimentName.FromProjectLocationAgentEnvironmentExperiment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]", "[EXPERIMENT]"),
DisplayName = "display_name137f65c2",
Description = "description2cf9da67",
State = Experiment.Types.State.Done,
Definition = new Experiment.Types.Definition(),
Result = new Experiment.Types.Result(),
CreateTime = new wkt::Timestamp(),
StartTime = new wkt::Timestamp(),
EndTime = new wkt::Timestamp(),
LastUpdateTime = new wkt::Timestamp(),
ExperimentLength = new wkt::Duration(),
VariantsHistory =
{
new VariantsHistory(),
},
RolloutConfig = new RolloutConfig(),
RolloutState = new RolloutState(),
RolloutFailureReason = "rollout_failure_reason2f2db6d3",
};
mockGrpcClient.Setup(x => x.UpdateExperimentAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Experiment>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ExperimentsClient client = new ExperimentsClientImpl(mockGrpcClient.Object, null);
Experiment responseCallSettings = await client.UpdateExperimentAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Experiment responseCancellationToken = await client.UpdateExperimentAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void UpdateExperiment()
{
moq::Mock<Experiments.ExperimentsClient> mockGrpcClient = new moq::Mock<Experiments.ExperimentsClient>(moq::MockBehavior.Strict);
UpdateExperimentRequest request = new UpdateExperimentRequest
{
Experiment = new Experiment(),
UpdateMask = new wkt::FieldMask(),
};
Experiment expectedResponse = new Experiment
{
ExperimentName = ExperimentName.FromProjectLocationAgentEnvironmentExperiment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]", "[EXPERIMENT]"),
DisplayName = "display_name137f65c2",
Description = "description2cf9da67",
State = Experiment.Types.State.Done,
Definition = new Experiment.Types.Definition(),
Result = new Experiment.Types.Result(),
CreateTime = new wkt::Timestamp(),
StartTime = new wkt::Timestamp(),
EndTime = new wkt::Timestamp(),
LastUpdateTime = new wkt::Timestamp(),
ExperimentLength = new wkt::Duration(),
VariantsHistory =
{
new VariantsHistory(),
},
RolloutConfig = new RolloutConfig(),
RolloutState = new RolloutState(),
RolloutFailureReason = "rollout_failure_reason2f2db6d3",
};
mockGrpcClient.Setup(x => x.UpdateExperiment(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ExperimentsClient client = new ExperimentsClientImpl(mockGrpcClient.Object, null);
Experiment response = client.UpdateExperiment(request.Experiment, request.UpdateMask);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task UpdateExperimentAsync()
{
moq::Mock<Experiments.ExperimentsClient> mockGrpcClient = new moq::Mock<Experiments.ExperimentsClient>(moq::MockBehavior.Strict);
UpdateExperimentRequest request = new UpdateExperimentRequest
{
Experiment = new Experiment(),
UpdateMask = new wkt::FieldMask(),
};
Experiment expectedResponse = new Experiment
{
ExperimentName = ExperimentName.FromProjectLocationAgentEnvironmentExperiment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]", "[EXPERIMENT]"),
DisplayName = "display_name137f65c2",
Description = "description2cf9da67",
State = Experiment.Types.State.Done,
Definition = new Experiment.Types.Definition(),
Result = new Experiment.Types.Result(),
CreateTime = new wkt::Timestamp(),
StartTime = new wkt::Timestamp(),
EndTime = new wkt::Timestamp(),
LastUpdateTime = new wkt::Timestamp(),
ExperimentLength = new wkt::Duration(),
VariantsHistory =
{
new VariantsHistory(),
},
RolloutConfig = new RolloutConfig(),
RolloutState = new RolloutState(),
RolloutFailureReason = "rollout_failure_reason2f2db6d3",
};
mockGrpcClient.Setup(x => x.UpdateExperimentAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Experiment>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ExperimentsClient client = new ExperimentsClientImpl(mockGrpcClient.Object, null);
Experiment responseCallSettings = await client.UpdateExperimentAsync(request.Experiment, request.UpdateMask, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Experiment responseCancellationToken = await client.UpdateExperimentAsync(request.Experiment, request.UpdateMask, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void DeleteExperimentRequestObject()
{
moq::Mock<Experiments.ExperimentsClient> mockGrpcClient = new moq::Mock<Experiments.ExperimentsClient>(moq::MockBehavior.Strict);
DeleteExperimentRequest request = new DeleteExperimentRequest
{
ExperimentName = ExperimentName.FromProjectLocationAgentEnvironmentExperiment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]", "[EXPERIMENT]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteExperiment(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ExperimentsClient client = new ExperimentsClientImpl(mockGrpcClient.Object, null);
client.DeleteExperiment(request);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task DeleteExperimentRequestObjectAsync()
{
moq::Mock<Experiments.ExperimentsClient> mockGrpcClient = new moq::Mock<Experiments.ExperimentsClient>(moq::MockBehavior.Strict);
DeleteExperimentRequest request = new DeleteExperimentRequest
{
ExperimentName = ExperimentName.FromProjectLocationAgentEnvironmentExperiment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]", "[EXPERIMENT]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteExperimentAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ExperimentsClient client = new ExperimentsClientImpl(mockGrpcClient.Object, null);
await client.DeleteExperimentAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.DeleteExperimentAsync(request, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void DeleteExperiment()
{
moq::Mock<Experiments.ExperimentsClient> mockGrpcClient = new moq::Mock<Experiments.ExperimentsClient>(moq::MockBehavior.Strict);
DeleteExperimentRequest request = new DeleteExperimentRequest
{
ExperimentName = ExperimentName.FromProjectLocationAgentEnvironmentExperiment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]", "[EXPERIMENT]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteExperiment(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ExperimentsClient client = new ExperimentsClientImpl(mockGrpcClient.Object, null);
client.DeleteExperiment(request.Name);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task DeleteExperimentAsync()
{
moq::Mock<Experiments.ExperimentsClient> mockGrpcClient = new moq::Mock<Experiments.ExperimentsClient>(moq::MockBehavior.Strict);
DeleteExperimentRequest request = new DeleteExperimentRequest
{
ExperimentName = ExperimentName.FromProjectLocationAgentEnvironmentExperiment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]", "[EXPERIMENT]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteExperimentAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ExperimentsClient client = new ExperimentsClientImpl(mockGrpcClient.Object, null);
await client.DeleteExperimentAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.DeleteExperimentAsync(request.Name, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void DeleteExperimentResourceNames()
{
moq::Mock<Experiments.ExperimentsClient> mockGrpcClient = new moq::Mock<Experiments.ExperimentsClient>(moq::MockBehavior.Strict);
DeleteExperimentRequest request = new DeleteExperimentRequest
{
ExperimentName = ExperimentName.FromProjectLocationAgentEnvironmentExperiment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]", "[EXPERIMENT]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteExperiment(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ExperimentsClient client = new ExperimentsClientImpl(mockGrpcClient.Object, null);
client.DeleteExperiment(request.ExperimentName);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task DeleteExperimentResourceNamesAsync()
{
moq::Mock<Experiments.ExperimentsClient> mockGrpcClient = new moq::Mock<Experiments.ExperimentsClient>(moq::MockBehavior.Strict);
DeleteExperimentRequest request = new DeleteExperimentRequest
{
ExperimentName = ExperimentName.FromProjectLocationAgentEnvironmentExperiment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]", "[EXPERIMENT]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteExperimentAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ExperimentsClient client = new ExperimentsClientImpl(mockGrpcClient.Object, null);
await client.DeleteExperimentAsync(request.ExperimentName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.DeleteExperimentAsync(request.ExperimentName, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void StartExperimentRequestObject()
{
moq::Mock<Experiments.ExperimentsClient> mockGrpcClient = new moq::Mock<Experiments.ExperimentsClient>(moq::MockBehavior.Strict);
StartExperimentRequest request = new StartExperimentRequest
{
ExperimentName = ExperimentName.FromProjectLocationAgentEnvironmentExperiment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]", "[EXPERIMENT]"),
};
Experiment expectedResponse = new Experiment
{
ExperimentName = ExperimentName.FromProjectLocationAgentEnvironmentExperiment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]", "[EXPERIMENT]"),
DisplayName = "display_name137f65c2",
Description = "description2cf9da67",
State = Experiment.Types.State.Done,
Definition = new Experiment.Types.Definition(),
Result = new Experiment.Types.Result(),
CreateTime = new wkt::Timestamp(),
StartTime = new wkt::Timestamp(),
EndTime = new wkt::Timestamp(),
LastUpdateTime = new wkt::Timestamp(),
ExperimentLength = new wkt::Duration(),
VariantsHistory =
{
new VariantsHistory(),
},
RolloutConfig = new RolloutConfig(),
RolloutState = new RolloutState(),
RolloutFailureReason = "rollout_failure_reason2f2db6d3",
};
mockGrpcClient.Setup(x => x.StartExperiment(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ExperimentsClient client = new ExperimentsClientImpl(mockGrpcClient.Object, null);
Experiment response = client.StartExperiment(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task StartExperimentRequestObjectAsync()
{
moq::Mock<Experiments.ExperimentsClient> mockGrpcClient = new moq::Mock<Experiments.ExperimentsClient>(moq::MockBehavior.Strict);
StartExperimentRequest request = new StartExperimentRequest
{
ExperimentName = ExperimentName.FromProjectLocationAgentEnvironmentExperiment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]", "[EXPERIMENT]"),
};
Experiment expectedResponse = new Experiment
{
ExperimentName = ExperimentName.FromProjectLocationAgentEnvironmentExperiment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]", "[EXPERIMENT]"),
DisplayName = "display_name137f65c2",
Description = "description2cf9da67",
State = Experiment.Types.State.Done,
Definition = new Experiment.Types.Definition(),
Result = new Experiment.Types.Result(),
CreateTime = new wkt::Timestamp(),
StartTime = new wkt::Timestamp(),
EndTime = new wkt::Timestamp(),
LastUpdateTime = new wkt::Timestamp(),
ExperimentLength = new wkt::Duration(),
VariantsHistory =
{
new VariantsHistory(),
},
RolloutConfig = new RolloutConfig(),
RolloutState = new RolloutState(),
RolloutFailureReason = "rollout_failure_reason2f2db6d3",
};
mockGrpcClient.Setup(x => x.StartExperimentAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Experiment>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ExperimentsClient client = new ExperimentsClientImpl(mockGrpcClient.Object, null);
Experiment responseCallSettings = await client.StartExperimentAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Experiment responseCancellationToken = await client.StartExperimentAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void StartExperiment()
{
moq::Mock<Experiments.ExperimentsClient> mockGrpcClient = new moq::Mock<Experiments.ExperimentsClient>(moq::MockBehavior.Strict);
StartExperimentRequest request = new StartExperimentRequest
{
ExperimentName = ExperimentName.FromProjectLocationAgentEnvironmentExperiment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]", "[EXPERIMENT]"),
};
Experiment expectedResponse = new Experiment
{
ExperimentName = ExperimentName.FromProjectLocationAgentEnvironmentExperiment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]", "[EXPERIMENT]"),
DisplayName = "display_name137f65c2",
Description = "description2cf9da67",
State = Experiment.Types.State.Done,
Definition = new Experiment.Types.Definition(),
Result = new Experiment.Types.Result(),
CreateTime = new wkt::Timestamp(),
StartTime = new wkt::Timestamp(),
EndTime = new wkt::Timestamp(),
LastUpdateTime = new wkt::Timestamp(),
ExperimentLength = new wkt::Duration(),
VariantsHistory =
{
new VariantsHistory(),
},
RolloutConfig = new RolloutConfig(),
RolloutState = new RolloutState(),
RolloutFailureReason = "rollout_failure_reason2f2db6d3",
};
mockGrpcClient.Setup(x => x.StartExperiment(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ExperimentsClient client = new ExperimentsClientImpl(mockGrpcClient.Object, null);
Experiment response = client.StartExperiment(request.Name);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task StartExperimentAsync()
{
moq::Mock<Experiments.ExperimentsClient> mockGrpcClient = new moq::Mock<Experiments.ExperimentsClient>(moq::MockBehavior.Strict);
StartExperimentRequest request = new StartExperimentRequest
{
ExperimentName = ExperimentName.FromProjectLocationAgentEnvironmentExperiment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]", "[EXPERIMENT]"),
};
Experiment expectedResponse = new Experiment
{
ExperimentName = ExperimentName.FromProjectLocationAgentEnvironmentExperiment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]", "[EXPERIMENT]"),
DisplayName = "display_name137f65c2",
Description = "description2cf9da67",
State = Experiment.Types.State.Done,
Definition = new Experiment.Types.Definition(),
Result = new Experiment.Types.Result(),
CreateTime = new wkt::Timestamp(),
StartTime = new wkt::Timestamp(),
EndTime = new wkt::Timestamp(),
LastUpdateTime = new wkt::Timestamp(),
ExperimentLength = new wkt::Duration(),
VariantsHistory =
{
new VariantsHistory(),
},
RolloutConfig = new RolloutConfig(),
RolloutState = new RolloutState(),
RolloutFailureReason = "rollout_failure_reason2f2db6d3",
};
mockGrpcClient.Setup(x => x.StartExperimentAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Experiment>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ExperimentsClient client = new ExperimentsClientImpl(mockGrpcClient.Object, null);
Experiment responseCallSettings = await client.StartExperimentAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Experiment responseCancellationToken = await client.StartExperimentAsync(request.Name, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void StartExperimentResourceNames()
{
moq::Mock<Experiments.ExperimentsClient> mockGrpcClient = new moq::Mock<Experiments.ExperimentsClient>(moq::MockBehavior.Strict);
StartExperimentRequest request = new StartExperimentRequest
{
ExperimentName = ExperimentName.FromProjectLocationAgentEnvironmentExperiment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]", "[EXPERIMENT]"),
};
Experiment expectedResponse = new Experiment
{
ExperimentName = ExperimentName.FromProjectLocationAgentEnvironmentExperiment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]", "[EXPERIMENT]"),
DisplayName = "display_name137f65c2",
Description = "description2cf9da67",
State = Experiment.Types.State.Done,
Definition = new Experiment.Types.Definition(),
Result = new Experiment.Types.Result(),
CreateTime = new wkt::Timestamp(),
StartTime = new wkt::Timestamp(),
EndTime = new wkt::Timestamp(),
LastUpdateTime = new wkt::Timestamp(),
ExperimentLength = new wkt::Duration(),
VariantsHistory =
{
new VariantsHistory(),
},
RolloutConfig = new RolloutConfig(),
RolloutState = new RolloutState(),
RolloutFailureReason = "rollout_failure_reason2f2db6d3",
};
mockGrpcClient.Setup(x => x.StartExperiment(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ExperimentsClient client = new ExperimentsClientImpl(mockGrpcClient.Object, null);
Experiment response = client.StartExperiment(request.ExperimentName);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task StartExperimentResourceNamesAsync()
{
moq::Mock<Experiments.ExperimentsClient> mockGrpcClient = new moq::Mock<Experiments.ExperimentsClient>(moq::MockBehavior.Strict);
StartExperimentRequest request = new StartExperimentRequest
{
ExperimentName = ExperimentName.FromProjectLocationAgentEnvironmentExperiment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]", "[EXPERIMENT]"),
};
Experiment expectedResponse = new Experiment
{
ExperimentName = ExperimentName.FromProjectLocationAgentEnvironmentExperiment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]", "[EXPERIMENT]"),
DisplayName = "display_name137f65c2",
Description = "description2cf9da67",
State = Experiment.Types.State.Done,
Definition = new Experiment.Types.Definition(),
Result = new Experiment.Types.Result(),
CreateTime = new wkt::Timestamp(),
StartTime = new wkt::Timestamp(),
EndTime = new wkt::Timestamp(),
LastUpdateTime = new wkt::Timestamp(),
ExperimentLength = new wkt::Duration(),
VariantsHistory =
{
new VariantsHistory(),
},
RolloutConfig = new RolloutConfig(),
RolloutState = new RolloutState(),
RolloutFailureReason = "rollout_failure_reason2f2db6d3",
};
mockGrpcClient.Setup(x => x.StartExperimentAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Experiment>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ExperimentsClient client = new ExperimentsClientImpl(mockGrpcClient.Object, null);
Experiment responseCallSettings = await client.StartExperimentAsync(request.ExperimentName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Experiment responseCancellationToken = await client.StartExperimentAsync(request.ExperimentName, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void StopExperimentRequestObject()
{
moq::Mock<Experiments.ExperimentsClient> mockGrpcClient = new moq::Mock<Experiments.ExperimentsClient>(moq::MockBehavior.Strict);
StopExperimentRequest request = new StopExperimentRequest
{
ExperimentName = ExperimentName.FromProjectLocationAgentEnvironmentExperiment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]", "[EXPERIMENT]"),
};
Experiment expectedResponse = new Experiment
{
ExperimentName = ExperimentName.FromProjectLocationAgentEnvironmentExperiment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]", "[EXPERIMENT]"),
DisplayName = "display_name137f65c2",
Description = "description2cf9da67",
State = Experiment.Types.State.Done,
Definition = new Experiment.Types.Definition(),
Result = new Experiment.Types.Result(),
CreateTime = new wkt::Timestamp(),
StartTime = new wkt::Timestamp(),
EndTime = new wkt::Timestamp(),
LastUpdateTime = new wkt::Timestamp(),
ExperimentLength = new wkt::Duration(),
VariantsHistory =
{
new VariantsHistory(),
},
RolloutConfig = new RolloutConfig(),
RolloutState = new RolloutState(),
RolloutFailureReason = "rollout_failure_reason2f2db6d3",
};
mockGrpcClient.Setup(x => x.StopExperiment(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ExperimentsClient client = new ExperimentsClientImpl(mockGrpcClient.Object, null);
Experiment response = client.StopExperiment(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task StopExperimentRequestObjectAsync()
{
moq::Mock<Experiments.ExperimentsClient> mockGrpcClient = new moq::Mock<Experiments.ExperimentsClient>(moq::MockBehavior.Strict);
StopExperimentRequest request = new StopExperimentRequest
{
ExperimentName = ExperimentName.FromProjectLocationAgentEnvironmentExperiment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]", "[EXPERIMENT]"),
};
Experiment expectedResponse = new Experiment
{
ExperimentName = ExperimentName.FromProjectLocationAgentEnvironmentExperiment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]", "[EXPERIMENT]"),
DisplayName = "display_name137f65c2",
Description = "description2cf9da67",
State = Experiment.Types.State.Done,
Definition = new Experiment.Types.Definition(),
Result = new Experiment.Types.Result(),
CreateTime = new wkt::Timestamp(),
StartTime = new wkt::Timestamp(),
EndTime = new wkt::Timestamp(),
LastUpdateTime = new wkt::Timestamp(),
ExperimentLength = new wkt::Duration(),
VariantsHistory =
{
new VariantsHistory(),
},
RolloutConfig = new RolloutConfig(),
RolloutState = new RolloutState(),
RolloutFailureReason = "rollout_failure_reason2f2db6d3",
};
mockGrpcClient.Setup(x => x.StopExperimentAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Experiment>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ExperimentsClient client = new ExperimentsClientImpl(mockGrpcClient.Object, null);
Experiment responseCallSettings = await client.StopExperimentAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Experiment responseCancellationToken = await client.StopExperimentAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void StopExperiment()
{
moq::Mock<Experiments.ExperimentsClient> mockGrpcClient = new moq::Mock<Experiments.ExperimentsClient>(moq::MockBehavior.Strict);
StopExperimentRequest request = new StopExperimentRequest
{
ExperimentName = ExperimentName.FromProjectLocationAgentEnvironmentExperiment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]", "[EXPERIMENT]"),
};
Experiment expectedResponse = new Experiment
{
ExperimentName = ExperimentName.FromProjectLocationAgentEnvironmentExperiment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]", "[EXPERIMENT]"),
DisplayName = "display_name137f65c2",
Description = "description2cf9da67",
State = Experiment.Types.State.Done,
Definition = new Experiment.Types.Definition(),
Result = new Experiment.Types.Result(),
CreateTime = new wkt::Timestamp(),
StartTime = new wkt::Timestamp(),
EndTime = new wkt::Timestamp(),
LastUpdateTime = new wkt::Timestamp(),
ExperimentLength = new wkt::Duration(),
VariantsHistory =
{
new VariantsHistory(),
},
RolloutConfig = new RolloutConfig(),
RolloutState = new RolloutState(),
RolloutFailureReason = "rollout_failure_reason2f2db6d3",
};
mockGrpcClient.Setup(x => x.StopExperiment(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ExperimentsClient client = new ExperimentsClientImpl(mockGrpcClient.Object, null);
Experiment response = client.StopExperiment(request.Name);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task StopExperimentAsync()
{
moq::Mock<Experiments.ExperimentsClient> mockGrpcClient = new moq::Mock<Experiments.ExperimentsClient>(moq::MockBehavior.Strict);
StopExperimentRequest request = new StopExperimentRequest
{
ExperimentName = ExperimentName.FromProjectLocationAgentEnvironmentExperiment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]", "[EXPERIMENT]"),
};
Experiment expectedResponse = new Experiment
{
ExperimentName = ExperimentName.FromProjectLocationAgentEnvironmentExperiment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]", "[EXPERIMENT]"),
DisplayName = "display_name137f65c2",
Description = "description2cf9da67",
State = Experiment.Types.State.Done,
Definition = new Experiment.Types.Definition(),
Result = new Experiment.Types.Result(),
CreateTime = new wkt::Timestamp(),
StartTime = new wkt::Timestamp(),
EndTime = new wkt::Timestamp(),
LastUpdateTime = new wkt::Timestamp(),
ExperimentLength = new wkt::Duration(),
VariantsHistory =
{
new VariantsHistory(),
},
RolloutConfig = new RolloutConfig(),
RolloutState = new RolloutState(),
RolloutFailureReason = "rollout_failure_reason2f2db6d3",
};
mockGrpcClient.Setup(x => x.StopExperimentAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Experiment>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ExperimentsClient client = new ExperimentsClientImpl(mockGrpcClient.Object, null);
Experiment responseCallSettings = await client.StopExperimentAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Experiment responseCancellationToken = await client.StopExperimentAsync(request.Name, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void StopExperimentResourceNames()
{
moq::Mock<Experiments.ExperimentsClient> mockGrpcClient = new moq::Mock<Experiments.ExperimentsClient>(moq::MockBehavior.Strict);
StopExperimentRequest request = new StopExperimentRequest
{
ExperimentName = ExperimentName.FromProjectLocationAgentEnvironmentExperiment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]", "[EXPERIMENT]"),
};
Experiment expectedResponse = new Experiment
{
ExperimentName = ExperimentName.FromProjectLocationAgentEnvironmentExperiment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]", "[EXPERIMENT]"),
DisplayName = "display_name137f65c2",
Description = "description2cf9da67",
State = Experiment.Types.State.Done,
Definition = new Experiment.Types.Definition(),
Result = new Experiment.Types.Result(),
CreateTime = new wkt::Timestamp(),
StartTime = new wkt::Timestamp(),
EndTime = new wkt::Timestamp(),
LastUpdateTime = new wkt::Timestamp(),
ExperimentLength = new wkt::Duration(),
VariantsHistory =
{
new VariantsHistory(),
},
RolloutConfig = new RolloutConfig(),
RolloutState = new RolloutState(),
RolloutFailureReason = "rollout_failure_reason2f2db6d3",
};
mockGrpcClient.Setup(x => x.StopExperiment(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ExperimentsClient client = new ExperimentsClientImpl(mockGrpcClient.Object, null);
Experiment response = client.StopExperiment(request.ExperimentName);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task StopExperimentResourceNamesAsync()
{
moq::Mock<Experiments.ExperimentsClient> mockGrpcClient = new moq::Mock<Experiments.ExperimentsClient>(moq::MockBehavior.Strict);
StopExperimentRequest request = new StopExperimentRequest
{
ExperimentName = ExperimentName.FromProjectLocationAgentEnvironmentExperiment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]", "[EXPERIMENT]"),
};
Experiment expectedResponse = new Experiment
{
ExperimentName = ExperimentName.FromProjectLocationAgentEnvironmentExperiment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]", "[EXPERIMENT]"),
DisplayName = "display_name137f65c2",
Description = "description2cf9da67",
State = Experiment.Types.State.Done,
Definition = new Experiment.Types.Definition(),
Result = new Experiment.Types.Result(),
CreateTime = new wkt::Timestamp(),
StartTime = new wkt::Timestamp(),
EndTime = new wkt::Timestamp(),
LastUpdateTime = new wkt::Timestamp(),
ExperimentLength = new wkt::Duration(),
VariantsHistory =
{
new VariantsHistory(),
},
RolloutConfig = new RolloutConfig(),
RolloutState = new RolloutState(),
RolloutFailureReason = "rollout_failure_reason2f2db6d3",
};
mockGrpcClient.Setup(x => x.StopExperimentAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Experiment>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ExperimentsClient client = new ExperimentsClientImpl(mockGrpcClient.Object, null);
Experiment responseCallSettings = await client.StopExperimentAsync(request.ExperimentName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Experiment responseCancellationToken = await client.StopExperimentAsync(request.ExperimentName, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
}
}
| |
using Android.Content;
using Android.Content.Res;
using Android.Graphics;
using Android.Graphics.Drawables;
using Android.OS;
using Android.Runtime;
using Android.Util;
using Android.Views;
using Android.Widget;
using System;
using Codewisp.Xamarin.Android.CircularImageSample;
namespace Codewisp.Xamarin.Android.Controls
{
public class CircularImageView : ImageView
{
// Border & Selector configuration variables
private bool _hasBorder;
private bool _hasSelector;
private bool _isSelected;
private bool _shadowEnabled;
private int _borderWidth;
private int _canvasSize;
private int _selectorStrokeWidth;
// Objects used for the actual drawing
private BitmapShader _shader;
private Bitmap _image;
private Paint _paint;
private Paint _paintBorder;
private Paint _paintSelectorBorder;
private ColorFilter _selectorFilter;
private IAttributeSet _attrs;
private int _defStyle;
public CircularImageView(IntPtr intPtr, JniHandleOwnership jniHandleOwnership)
: base(intPtr, jniHandleOwnership)
{
Init();
}
public CircularImageView(Context context) : base(context, null) { }
public CircularImageView(Context context, IAttributeSet attrs)
: base(context, attrs, Resource.Attribute.CircularImageViewStyle)
{
this._attrs = attrs;
Init();
}
public CircularImageView(Context context, IAttributeSet attrs, int defStyle)
: base(context, attrs, defStyle)
{
this._attrs = attrs;
this._defStyle = defStyle;
Init();
}
/**
* Initializes paint objects and sets desired attributes.
* @param Context Context
* @param _attrs Attributes
* @param _defStyle Default Style
*/
private void Init()
{
// Initialize paint objects
_paint = new Paint();
_paint.AntiAlias = true;
_paintBorder = new Paint();
_paintBorder.AntiAlias = true;
_paintSelectorBorder = new Paint();
_paintSelectorBorder.AntiAlias = true;
// Disable this view's hardware acceleration on Honeycomb and up (Needed for shadow effect)
if (Build.VERSION.SdkInt >= BuildVersionCodes.Honeycomb)
{
//setLayerType(LAYER_TYPE_SOFTWARE, paint);
SetLayerType(LayerType.Software, _paintBorder);
SetLayerType(LayerType.Software, _paintSelectorBorder);
}
// load the styled attributes and set their properties
TypedArray attributes = Context.ObtainStyledAttributes(_attrs, Resource.Styleable.CircularImageView, _defStyle, 0);
// Check if border and/or border is enabled
_hasBorder = attributes.GetBoolean(Resource.Styleable.CircularImageView_border, false);
_hasSelector = attributes.GetBoolean(Resource.Styleable.CircularImageView_selector, false);
// Set border properties if enabled
if (_hasBorder)
{
int defaultBorderSize = (int)(2 * Context.Resources.DisplayMetrics.Density + 0.5f);
SetBorderWidth(attributes.GetDimensionPixelOffset(Resource.Styleable.CircularImageView_border_width, defaultBorderSize));
SetBorderColor(attributes.GetColor(Resource.Styleable.CircularImageView_border_color, Color.White));
}
// Set selector properties if enabled
if (_hasSelector)
{
int defaultSelectorSize = (int)(2 * Context.Resources.DisplayMetrics.Density + 0.5f);
SetSelectorColor(attributes.GetColor(
Resource.Styleable.CircularImageView_selector_color, Color.Transparent));
SetSelectorStrokeWidth(attributes.GetDimensionPixelOffset(Resource.Styleable.CircularImageView_selector_stroke_width, defaultSelectorSize));
SetSelectorStrokeColor(attributes.GetColor(Resource.Styleable.CircularImageView_selector_stroke_color, Color.Blue));
}
// Add shadow if enabled
if (attributes.GetBoolean(Resource.Styleable.CircularImageView_shadow, false))
SetShadow(true);
// We no longer need our attributes TypedArray, give it back to cache
attributes.Recycle();
}
/**
* Sets the CircularImageView's border width in pixels.
* @param borderWidth Width in pixels for the border.
*/
public void SetBorderWidth(int borderWidth)
{
this._borderWidth = borderWidth;
this.RequestLayout();
this.Invalidate();
}
/**
* Sets the CircularImageView's basic border color.
* @param borderColor The new color (including alpha) to set the border.
*/
public void SetBorderColor(Color borderColor)
{
if (_paintBorder != null)
_paintBorder.Color = borderColor;
this.Invalidate();
}
/**
* Sets the color of the selector to be draw over the
* CircularImageView. Be sure to provide some opacity.
* @param selectorColor The color (including alpha) to set for the selector overlay.
*/
public void SetSelectorColor(Color selectorColor)
{
this._selectorFilter = new PorterDuffColorFilter(selectorColor, PorterDuff.Mode.SrcAtop);
this.Invalidate();
}
/**
* Sets the stroke width to be drawn around the CircularImageView
* during click events when the selector is enabled.
* @param selectorStrokeWidth Width in pixels for the selector stroke.
*/
public void SetSelectorStrokeWidth(int selectorStrokeWidth)
{
this._selectorStrokeWidth = selectorStrokeWidth;
this.RequestLayout();
this.Invalidate();
}
/**
* Sets the stroke color to be drawn around the CircularImageView
* during click events when the selector is enabled.
* @param selectorStrokeColor The color (including alpha) to set for the selector stroke.
*/
public void SetSelectorStrokeColor(Color selectorStrokeColor)
{
if (_paintSelectorBorder != null)
_paintSelectorBorder.Color = selectorStrokeColor;
this.Invalidate();
}
/**
* Enables a dark shadow for this CircularImageView.
* @param shadowEnabled Set to true to render a shadow or false to disable it.
*/
public void SetShadow(bool shadowEnabled)
{
this._shadowEnabled = true;
if (shadowEnabled)
{
//paint.setShadowLayer(4.0f, 0.0f, 2.0f, Color.BLACK);
_paintBorder.SetShadowLayer(4.0f, 0.0f, 2.0f, Color.Black);
_paintSelectorBorder.SetShadowLayer(4.0f, 0.0f, 2.0f, Color.Black);
}
else
{
//paint.setShadowLayer(0, 0.0f, 2.0f, Color.BLACK);
_paintBorder.SetShadowLayer(0, 0.0f, 2.0f, Color.Black);
_paintSelectorBorder.SetShadowLayer(0, 0.0f, 2.0f, Color.Black);
}
}
/**
* Enables a dark shadow for this CircularImageView.
* If the radius is set to 0, the shadow is removed.
* @param radius
* @param dx
* @param dy
* @param color
*/
public void SetShadow(float radius, float dx, float dy, int color)
{
// TODO
}
protected override void OnDraw(Canvas canvas)
{
// Don't draw anything without an image
if (_image == null)
return;
// Nothing to draw (Empty bounds)
if (_image.Height == 0 || _image.Width == 0)
return;
// We'll need this later
int oldCanvasSize = _canvasSize;
// Compare canvas sizes
_canvasSize = canvas.Width;
if (canvas.Height < _canvasSize)
_canvasSize = canvas.Height;
// Reinitialize shader, if necessary
if (oldCanvasSize != _canvasSize)
RefreshBitmapShader();
// Apply shader to paint
_paint.SetShader(_shader);
// Keep track of selectorStroke/border width
int outerWidth = 0;
// Get the exact X/Y axis of the view
int center = _canvasSize / 2;
if (_hasSelector && _isSelected)
{ // Draw the selector stroke & apply the selector filter, if applicable
outerWidth = _selectorStrokeWidth;
center = (_canvasSize - (outerWidth * 2)) / 2;
_paint.SetColorFilter(_selectorFilter);
canvas.DrawCircle(center + outerWidth, center + outerWidth, ((_canvasSize - (outerWidth * 2)) / 2) + outerWidth - 4.0f, _paintSelectorBorder);
}
else if (_hasBorder)
{ // If no selector was drawn, draw a border and clear the filter instead... if enabled
outerWidth = _borderWidth;
center = (_canvasSize - (outerWidth * 2)) / 2;
_paint.SetColorFilter(null);
canvas.DrawCircle(center + outerWidth, center + outerWidth, ((_canvasSize - (outerWidth * 2)) / 2) + outerWidth - 4.0f, _paintBorder);
}
else // Clear the color filter if no selector nor border were drawn
_paint.SetColorFilter(null);
// Draw the circular image itself
canvas.DrawCircle(center + outerWidth, center + outerWidth, ((_canvasSize - (outerWidth * 2)) / 2) - 4.0f, _paint);
}
public override bool DispatchTouchEvent(MotionEvent motionEvent)
{
// Check for clickable state and do nothing if disabled
if (!this.Clickable)
{
this._isSelected = false;
return base.OnTouchEvent(motionEvent);
}
// Set selected state based on Motion Event
switch (motionEvent.Action)
{
case MotionEventActions.Down:
this._isSelected = true;
break;
case MotionEventActions.Up:
case MotionEventActions.Scroll:
case MotionEventActions.Outside:
case MotionEventActions.Cancel:
this._isSelected = false;
break;
}
// Redraw image and return super type
this.Invalidate();
return base.DispatchTouchEvent(motionEvent);
}
public override void Invalidate(Rect dirty)
{
base.Invalidate(dirty);
// Don't do anything without a valid drawable
if (Drawable == null)
return;
// Extract a Bitmap out of the drawable & set it as the main shader
_image = DrawableToBitmap(Drawable);
if (_shader != null || _canvasSize > 0)
RefreshBitmapShader();
}
public override void Invalidate(int l, int t, int r, int b)
{
base.Invalidate(l, t, r, b);
// Don't do anything without a valid drawable
if (Drawable == null)
return;
// Extract a Bitmap out of the drawable & set it as the main shader
_image = DrawableToBitmap(Drawable);
if (_shader != null || _canvasSize > 0)
RefreshBitmapShader();
}
public override void Invalidate()
{
base.Invalidate();
// Don't do anything without a valid drawable
if (Drawable == null)
return;
// Extract a Bitmap out of the drawable & set it as the main shader
_image = DrawableToBitmap(Drawable);
if (_shader != null || _canvasSize > 0)
RefreshBitmapShader();
}
protected override void OnMeasure(int widthMeasureSpec, int heightMeasureSpec)
{
int width = MeasureWidth(widthMeasureSpec);
int height = MeasureHeight(heightMeasureSpec);
SetMeasuredDimension(width, height);
}
private int MeasureWidth(int measureSpec)
{
int result;
MeasureSpecMode specMode = MeasureSpec.GetMode(measureSpec);
int specSize = MeasureSpec.GetSize(measureSpec);
if (specMode == MeasureSpecMode.Exactly)
{
// The parent has determined an exact size for the child.
result = specSize;
}
else if (specMode == MeasureSpecMode.AtMost)
{
// The child can be as large as it wants up to the specified size.
result = specSize;
}
else
{
// The parent has not imposed any constraint on the child.
result = _canvasSize;
}
return result;
}
private int MeasureHeight(int measureSpecHeight)
{
int result;
MeasureSpecMode specMode = MeasureSpec.GetMode(measureSpecHeight);
int specSize = MeasureSpec.GetSize(measureSpecHeight);
if (specMode == MeasureSpecMode.Exactly)
{
// We were told how big to be
result = specSize;
}
else if (specMode == MeasureSpecMode.AtMost)
{
// The child can be as large as it wants up to the specified size.
result = specSize;
}
else
{
// Measure the text (beware: ascent is a negative number)
result = _canvasSize;
}
return (result + 2);
}
/**
* Convert a drawable object into a Bitmap.
* @param drawable Drawable to extract a Bitmap from.
* @return A Bitmap created from the drawable parameter.
*/
public Bitmap DrawableToBitmap(Drawable drawable)
{
if (drawable == null) // Don't do anything without a proper drawable
return null;
else if (drawable.GetType() == typeof(BitmapDrawable)) // Use the getBitmap() method instead if BitmapDrawable
return ((BitmapDrawable)drawable).Bitmap;
// Create Bitmap object out of the drawable
Bitmap bitmap = Bitmap.CreateBitmap(drawable.IntrinsicWidth, drawable.IntrinsicHeight, Bitmap.Config.Argb8888);
Canvas canvas = new Canvas(bitmap);
drawable.SetBounds(0, 0, canvas.Width, canvas.Height);
drawable.Draw(canvas);
// Return the created Bitmap
return bitmap;
}
/**
* Reinitializes the shader texture used to fill in
* the Circle upon drawing.
*/
public void RefreshBitmapShader()
{
_shader = new BitmapShader(Bitmap.CreateScaledBitmap(_image, _canvasSize, _canvasSize, false), Shader.TileMode.Clamp, Shader.TileMode.Clamp);
}
}
}
| |
// 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 Microsoft.Build.BackEnd;
using Microsoft.Build.Construction;
using Microsoft.Build.Execution;
using Microsoft.Build.UnitTests;
using Xunit;
using EvaluatorData =
Microsoft.Build.Evaluation.IEvaluatorData<Microsoft.Build.Execution.ProjectPropertyInstance, Microsoft.Build.Execution.ProjectItemInstance,
Microsoft.Build.Execution.ProjectMetadataInstance, Microsoft.Build.Execution.ProjectItemDefinitionInstance>;
namespace Microsoft.Build.Engine.UnitTests.TestComparers
{
public static class ProjectInstanceModelTestComparers
{
public class ProjectInstanceComparer : IEqualityComparer<ProjectInstance>
{
public bool Equals(ProjectInstance x, ProjectInstance y)
{
Assert.Equal(x.TranslateEntireState, y.TranslateEntireState);
Assert.Equal(x.Properties, y.Properties, EqualityComparer<ProjectPropertyInstance>.Default);
Assert.Equal(x.TestEnvironmentalProperties, y.TestEnvironmentalProperties, EqualityComparer<ProjectPropertyInstance>.Default);
Helpers.AssertDictionariesEqual(x.GlobalProperties, y.GlobalProperties);
Assert.Equal(((EvaluatorData) x).GlobalPropertiesToTreatAsLocal, ((EvaluatorData) y).GlobalPropertiesToTreatAsLocal);
Assert.Equal(x.Items.ToArray(), y.Items.ToArray(), ProjectItemInstance.ProjectItemInstanceEqualityComparer.Default);
Helpers.AssertDictionariesEqual(
x.Targets,
y.Targets,
(xPair, yPair) =>
{
Assert.Equal(xPair.Key, yPair.Key);
Assert.Equal(xPair.Value, yPair.Value, new TargetComparer());
});
Helpers.AssertDictionariesEqual(((EvaluatorData)x).BeforeTargets, ((EvaluatorData)y).BeforeTargets, AssertTargetSpecificationPairsEqual);
Helpers.AssertDictionariesEqual(((EvaluatorData)x).AfterTargets, ((EvaluatorData)y).AfterTargets, AssertTargetSpecificationPairsEqual);
Assert.Equal(x.DefaultTargets, y.DefaultTargets);
Assert.Equal(x.InitialTargets, y.InitialTargets);
Assert.Equal(x.Toolset, y.Toolset, new TaskRegistryComparers.ToolsetComparer());
Assert.Equal(x.UsingDifferentToolsVersionFromProjectFile, y.UsingDifferentToolsVersionFromProjectFile);
Assert.Equal(x.ExplicitToolsVersionSpecified, y.ExplicitToolsVersionSpecified);
Assert.Equal(x.OriginalProjectToolsVersion, y.OriginalProjectToolsVersion);
Assert.Equal(x.SubToolsetVersion, y.SubToolsetVersion);
Assert.Equal(x.Directory, y.Directory);
Assert.Equal(x.ProjectFileLocation, y.ProjectFileLocation, new Helpers.ElementLocationComparerIgnoringType());
Assert.Equal(x.TaskRegistry, y.TaskRegistry, new TaskRegistryComparers.TaskRegistryComparer());
Assert.Equal(x.IsImmutable, y.IsImmutable);
Helpers.AssertDictionariesEqual(x.ItemDefinitions, y.ItemDefinitions,
(xPair, yPair) =>
{
Assert.Equal(xPair.Key, yPair.Key);
Assert.Equal(xPair.Value, yPair.Value, new ItemDefinitionComparer());
});
return true;
}
private void AssertTargetSpecificationPairsEqual(KeyValuePair<string, List<TargetSpecification>> xPair, KeyValuePair<string, List<TargetSpecification>> yPair)
{
Assert.Equal(xPair.Key, yPair.Key);
Assert.Equal(xPair.Value, yPair.Value, new TargetSpecificationComparer());
}
public int GetHashCode(ProjectInstance obj)
{
throw new NotImplementedException();
}
}
public class TargetComparer : IEqualityComparer<ProjectTargetInstance>
{
public bool Equals(ProjectTargetInstance x, ProjectTargetInstance y)
{
Assert.Equal(x.Name, y.Name);
Assert.Equal(x.Condition, y.Condition);
Assert.Equal(x.Inputs, y.Inputs);
Assert.Equal(x.Outputs, y.Outputs);
Assert.Equal(x.Returns, y.Returns);
Assert.Equal(x.KeepDuplicateOutputs, y.KeepDuplicateOutputs);
Assert.Equal(x.DependsOnTargets, y.DependsOnTargets);
Assert.Equal(x.BeforeTargets, y.BeforeTargets);
Assert.Equal(x.AfterTargets, y.AfterTargets);
Assert.Equal(x.ParentProjectSupportsReturnsAttribute, y.ParentProjectSupportsReturnsAttribute);
Assert.Equal(x.Location, y.Location, new Helpers.ElementLocationComparerIgnoringType());
Assert.Equal(x.ConditionLocation, y.ConditionLocation, new Helpers.ElementLocationComparerIgnoringType());
Assert.Equal(x.InputsLocation, y.InputsLocation, new Helpers.ElementLocationComparerIgnoringType());
Assert.Equal(x.OutputsLocation, y.OutputsLocation, new Helpers.ElementLocationComparerIgnoringType());
Assert.Equal(x.ReturnsLocation, y.ReturnsLocation, new Helpers.ElementLocationComparerIgnoringType());
Assert.Equal(x.KeepDuplicateOutputsLocation, y.KeepDuplicateOutputsLocation, new Helpers.ElementLocationComparerIgnoringType());
Assert.Equal(x.DependsOnTargetsLocation, y.DependsOnTargetsLocation, new Helpers.ElementLocationComparerIgnoringType());
Assert.Equal(x.BeforeTargetsLocation, y.BeforeTargetsLocation, new Helpers.ElementLocationComparerIgnoringType());
Assert.Equal(x.AfterTargetsLocation, y.AfterTargetsLocation, new Helpers.ElementLocationComparerIgnoringType());
Assert.Equal(x.Children, y.Children, new TargetChildComparer());
Assert.Equal(x.OnErrorChildren, y.OnErrorChildren, new TargetOnErrorComparer());
return true;
}
public int GetHashCode(ProjectTargetInstance obj)
{
throw new NotImplementedException();
}
}
public class TargetChildComparer : IEqualityComparer<ProjectTargetInstanceChild>
{
public bool Equals(ProjectTargetInstanceChild x, ProjectTargetInstanceChild y)
{
if (x is ProjectItemGroupTaskInstance)
{
return new TargetItemGroupComparer().Equals((ProjectItemGroupTaskInstance) x, (ProjectItemGroupTaskInstance) y);
}
if (x is ProjectPropertyGroupTaskInstance)
{
return new TargetPropertyGroupComparer().Equals((ProjectPropertyGroupTaskInstance) x, (ProjectPropertyGroupTaskInstance) y);
}
if (x is ProjectOnErrorInstance)
{
return new TargetOnErrorComparer().Equals((ProjectOnErrorInstance) x, (ProjectOnErrorInstance) y);
}
if (x is ProjectTaskInstance)
{
return new TargetTaskComparer().Equals((ProjectTaskInstance) x, (ProjectTaskInstance) y);
}
throw new NotImplementedException();
}
public int GetHashCode(ProjectTargetInstanceChild obj)
{
throw new NotImplementedException();
}
}
public class TargetItemGroupComparer : IEqualityComparer<ProjectItemGroupTaskInstance>
{
public bool Equals(ProjectItemGroupTaskInstance x, ProjectItemGroupTaskInstance y)
{
Assert.Equal(x.Condition, y.Condition);
Assert.Equal(x.Location, y.Location, new Helpers.ElementLocationComparerIgnoringType());
Assert.Equal(x.ConditionLocation, y.ConditionLocation, new Helpers.ElementLocationComparerIgnoringType());
Assert.Equal(x.Items, y.Items, new TargetItemComparer());
return true;
}
public int GetHashCode(ProjectItemGroupTaskInstance obj)
{
throw new NotImplementedException();
}
}
public class TargetItemComparer : IEqualityComparer<ProjectItemGroupTaskItemInstance>
{
public bool Equals(ProjectItemGroupTaskItemInstance x, ProjectItemGroupTaskItemInstance y)
{
Assert.Equal(x.ItemType, y.ItemType);
Assert.Equal(x.Include, y.Include);
Assert.Equal(x.Exclude, y.Exclude);
Assert.Equal(x.Remove, y.Remove);
Assert.Equal(x.KeepMetadata, y.KeepMetadata);
Assert.Equal(x.RemoveMetadata, y.RemoveMetadata);
Assert.Equal(x.KeepDuplicates, y.KeepDuplicates);
Assert.Equal(x.Condition, y.Condition);
Assert.Equal(x.Location, y.Location, new Helpers.ElementLocationComparerIgnoringType());
Assert.Equal(x.IncludeLocation, y.IncludeLocation, new Helpers.ElementLocationComparerIgnoringType());
Assert.Equal(x.ExcludeLocation, y.ExcludeLocation, new Helpers.ElementLocationComparerIgnoringType());
Assert.Equal(x.RemoveLocation, y.RemoveLocation, new Helpers.ElementLocationComparerIgnoringType());
Assert.Equal(x.KeepMetadataLocation, y.KeepMetadataLocation, new Helpers.ElementLocationComparerIgnoringType());
Assert.Equal(x.RemoveMetadataLocation, y.RemoveMetadataLocation, new Helpers.ElementLocationComparerIgnoringType());
Assert.Equal(x.ConditionLocation, y.ConditionLocation, new Helpers.ElementLocationComparerIgnoringType());
Assert.Equal(x.Metadata, y.Metadata, new TargetItemMetadataComparer());
return true;
}
public int GetHashCode(ProjectItemGroupTaskItemInstance obj)
{
throw new NotImplementedException();
}
}
public class TargetItemMetadataComparer : IEqualityComparer<ProjectItemGroupTaskMetadataInstance>
{
public bool Equals(ProjectItemGroupTaskMetadataInstance x, ProjectItemGroupTaskMetadataInstance y)
{
Assert.Equal(x.Name, y.Name);
Assert.Equal(x.Value, y.Value);
Assert.Equal(x.Condition, y.Condition);
Assert.Equal(x.Location, y.Location, new Helpers.ElementLocationComparerIgnoringType());
Assert.Equal(x.ConditionLocation, y.ConditionLocation, new Helpers.ElementLocationComparerIgnoringType());
return true;
}
public int GetHashCode(ProjectItemGroupTaskMetadataInstance obj)
{
throw new NotImplementedException();
}
}
public class TargetPropertyGroupComparer : IEqualityComparer<ProjectPropertyGroupTaskInstance>
{
public bool Equals(ProjectPropertyGroupTaskInstance x, ProjectPropertyGroupTaskInstance y)
{
Assert.Equal(x.Condition, y.Condition);
Assert.Equal(x.Location, y.Location, new Helpers.ElementLocationComparerIgnoringType());
Assert.Equal(x.ConditionLocation, y.ConditionLocation, new Helpers.ElementLocationComparerIgnoringType());
Assert.Equal(x.Properties, y.Properties, new TargetPropertyComparer());
return true;
}
public int GetHashCode(ProjectPropertyGroupTaskInstance obj)
{
throw new NotImplementedException();
}
}
}
public class ItemDefinitionComparer : IEqualityComparer<ProjectItemDefinitionInstance>
{
public bool Equals(ProjectItemDefinitionInstance x, ProjectItemDefinitionInstance y)
{
Assert.Equal(x.ItemType, y.ItemType);
Assert.Equal(x.Metadata, y.Metadata, EqualityComparer<ProjectMetadataInstance>.Default);
return true;
}
public int GetHashCode(ProjectItemDefinitionInstance obj)
{
throw new NotImplementedException();
}
}
internal class TargetSpecificationComparer : IEqualityComparer<TargetSpecification>
{
public bool Equals(TargetSpecification x, TargetSpecification y)
{
Assert.Equal(x.TargetName, y.TargetName);
Assert.Equal(x.ReferenceLocation, y.ReferenceLocation, new Helpers.ElementLocationComparerIgnoringType());
return true;
}
public int GetHashCode(TargetSpecification obj)
{
throw new NotImplementedException();
}
}
public class TargetPropertyComparer : IEqualityComparer<ProjectPropertyGroupTaskPropertyInstance>
{
public bool Equals(ProjectPropertyGroupTaskPropertyInstance x, ProjectPropertyGroupTaskPropertyInstance y)
{
Assert.Equal(x.Name, y.Name);
Assert.Equal(x.Value, y.Value);
Assert.Equal(x.Condition, y.Condition);
Assert.Equal(x.Location, y.Location, new Helpers.ElementLocationComparerIgnoringType());
Assert.Equal(x.ConditionLocation, y.ConditionLocation, new Helpers.ElementLocationComparerIgnoringType());
return true;
}
public int GetHashCode(ProjectPropertyGroupTaskPropertyInstance obj)
{
throw new NotImplementedException();
}
}
public class TargetOnErrorComparer : IEqualityComparer<ProjectOnErrorInstance>
{
public bool Equals(ProjectOnErrorInstance x, ProjectOnErrorInstance y)
{
Assert.Equal(x.ExecuteTargets, y.ExecuteTargets);
Assert.Equal(x.Condition, y.Condition);
Assert.Equal(x.Location, y.Location, new Helpers.ElementLocationComparerIgnoringType());
Assert.Equal(x.ConditionLocation, y.ConditionLocation, new Helpers.ElementLocationComparerIgnoringType());
Assert.Equal(x.ExecuteTargetsLocation, y.ExecuteTargetsLocation, new Helpers.ElementLocationComparerIgnoringType());
return true;
}
public int GetHashCode(ProjectOnErrorInstance obj)
{
throw new NotImplementedException();
}
}
public class TargetTaskComparer : IEqualityComparer<ProjectTaskInstance>
{
public bool Equals(ProjectTaskInstance x, ProjectTaskInstance y)
{
Assert.Equal(x.Name, y.Name);
Assert.Equal(x.Condition, y.Condition);
Assert.Equal(x.ContinueOnError, y.ContinueOnError);
Assert.Equal(x.MSBuildRuntime, y.MSBuildRuntime);
Assert.Equal(x.MSBuildArchitecture, y.MSBuildArchitecture);
Assert.Equal(x.Location, y.Location, new Helpers.ElementLocationComparerIgnoringType());
Assert.Equal(x.ConditionLocation, y.ConditionLocation, new Helpers.ElementLocationComparerIgnoringType());
Assert.Equal(x.ContinueOnErrorLocation, y.ContinueOnErrorLocation, new Helpers.ElementLocationComparerIgnoringType());
Assert.Equal(x.MSBuildRuntimeLocation, y.MSBuildRuntimeLocation, new Helpers.ElementLocationComparerIgnoringType());
Assert.Equal(x.MSBuildRuntimeLocation, y.MSBuildRuntimeLocation, new Helpers.ElementLocationComparerIgnoringType());
Assert.Equal(x.Outputs, y.Outputs, new ProjectTaskInstanceChildComparer());
AssertParametersEqual(x.TestGetParameters, y.TestGetParameters);
return true;
}
public int GetHashCode(ProjectTaskInstance obj)
{
throw new NotImplementedException();
}
private void AssertParametersEqual(IDictionary<string, (string, ElementLocation)> x, IDictionary<string, (string, ElementLocation)> y)
{
Assert.Equal(x.Count, y.Count);
for (var i = 0; i < x.Count; i++)
{
var xPair = x.ElementAt(i);
var yPair = y.ElementAt(i);
Assert.Equal(xPair.Key, yPair.Key);
Assert.Equal(xPair.Value.Item1, yPair.Value.Item1);
Assert.Equal(xPair.Value.Item2, yPair.Value.Item2, new Helpers.ElementLocationComparerIgnoringType());
}
}
public class ProjectTaskInstanceChildComparer : IEqualityComparer<ProjectTaskInstanceChild>
{
public bool Equals(ProjectTaskInstanceChild x, ProjectTaskInstanceChild y)
{
if (x is ProjectTaskOutputItemInstance)
{
return new ProjectTaskOutputItemComparer().Equals((ProjectTaskOutputItemInstance) x, (ProjectTaskOutputItemInstance) y);
}
if (x is ProjectTaskOutputPropertyInstance)
{
return new ProjectTaskOutputPropertyComparer().Equals((ProjectTaskOutputPropertyInstance) x, (ProjectTaskOutputPropertyInstance) y);
}
throw new NotImplementedException();
}
public int GetHashCode(ProjectTaskInstanceChild obj)
{
throw new NotImplementedException();
}
}
public class ProjectTaskOutputItemComparer : IEqualityComparer<ProjectTaskOutputItemInstance>
{
public bool Equals(ProjectTaskOutputItemInstance x, ProjectTaskOutputItemInstance y)
{
Assert.Equal(x.ItemType, y.ItemType);
Assert.Equal(x.TaskParameter, y.TaskParameter);
Assert.Equal(x.Condition, y.Condition);
Assert.Equal(x.ConditionLocation, y.ConditionLocation, new Helpers.ElementLocationComparerIgnoringType());
Assert.Equal(x.Location, y.Location, new Helpers.ElementLocationComparerIgnoringType());
Assert.Equal(x.TaskParameterLocation, y.TaskParameterLocation, new Helpers.ElementLocationComparerIgnoringType());
Assert.Equal(x.ItemTypeLocation, y.ItemTypeLocation, new Helpers.ElementLocationComparerIgnoringType());
return true;
}
public int GetHashCode(ProjectTaskOutputItemInstance obj)
{
throw new NotImplementedException();
}
}
public class ProjectTaskOutputPropertyComparer : IEqualityComparer<ProjectTaskOutputPropertyInstance>
{
public bool Equals(ProjectTaskOutputPropertyInstance x, ProjectTaskOutputPropertyInstance y)
{
Assert.Equal(x.PropertyName, y.PropertyName);
Assert.Equal(x.TaskParameter, y.TaskParameter);
Assert.Equal(x.Condition, y.Condition);
Assert.Equal(x.ConditionLocation, y.ConditionLocation, new Helpers.ElementLocationComparerIgnoringType());
Assert.Equal(x.Location, y.Location, new Helpers.ElementLocationComparerIgnoringType());
Assert.Equal(x.PropertyNameLocation, y.PropertyNameLocation, new Helpers.ElementLocationComparerIgnoringType());
Assert.Equal(x.TaskParameterLocation, y.TaskParameterLocation, new Helpers.ElementLocationComparerIgnoringType());
return true;
}
public int GetHashCode(ProjectTaskOutputPropertyInstance obj)
{
throw new NotImplementedException();
}
}
}
}
| |
//
// FullVisibilityGraphGenerator.cs
// MSAGL base class to create the visibility graph consisting of all ScanSegment intersections for Rectilinear Edge Routing.
//
// Copyright Microsoft Corporation.
using System.Diagnostics;
using Microsoft.Msagl.Core.DataStructures;
using Microsoft.Msagl.Core.Geometry;
using Microsoft.Msagl.Routing.Spline.ConeSpanner;
namespace Microsoft.Msagl.Routing.Rectilinear {
// Scan direction is parallel to the sweepline which moves in the perpendicular direction;
// i.e. scan direction is "sideways" along the sweepline. We also have lookahead scans
// that enqueue events along the scan-primary coordinate (in the direction of the scan, i.e.
// X for Hscan, Y for Vscan) to handle reflections from non-orthogonal obstacle sides,
// and lookback scans that have not had their reflections calculated because they reflect
// backward from the scanline and thus must be picked up on a subsequent perpendicular sweep.
internal class FullVisibilityGraphGenerator : VisibilityGraphGenerator {
internal FullVisibilityGraphGenerator() : base(wantReflections:true) {
}
// This tracks the last (usually) added ScanSegment for subsumption as an optimization to
// searching the tree for fully-internal subsumptions.
ScanSegment hintScanSegment;
/// <summary>
/// Generate the visibility graph along which edges will be routed.
/// </summary>
/// <returns></returns>
internal override void GenerateVisibilityGraph() {
if (null == ObstacleTree.Root) {
return;
}
// This will initialize events and call ProcessEvents which will call our specific functionality
// to create scan segments.
base.GenerateVisibilityGraph();
// Merge any ScanSegments that share intervals.
HorizontalScanSegments.MergeSegments();
VerticalScanSegments.MergeSegments();
// Done now with the ScanSegment generation; intersect them to create the VisibilityGraph.
IntersectScanSegments();
Debug_AssertGraphIsRectilinear(VisibilityGraph, ObstacleTree);
}
private void IntersectScanSegments()
{
var si = new SegmentIntersector();
this.VisibilityGraph = si.Generate(HorizontalScanSegments.Segments, VerticalScanSegments.Segments);
si.RemoveSegmentsWithNoVisibility(HorizontalScanSegments, VerticalScanSegments);
HorizontalScanSegments.DevTraceVerifyVisibility();
VerticalScanSegments.DevTraceVerifyVisibility();
}
internal override void InitializeEventQueue(ScanDirection scanDir) {
base.InitializeEventQueue(scanDir);
hintScanSegment = null;
}
internal override void Clear() {
base.Clear();
hintScanSegment = null;
}
protected override bool InsertPerpendicularReflectionSegment(Point start, Point end) {
// If we're on the Vertical pass, the Horizontal pass may have loaded a Lookahead perpendicular
// segment between two non-overlapped obstacles at a non-extremevertex point with exactly the
// same span we have here, -or- we may be adding the non-overlapped extension of an overlapped
// segment at exactly the same point that the horizontal pass added a reflection.
// See TestRectilinear.Reflection_Staircase_Stops_At_BoundingBox_Side*.
if (null != PerpendicularScanSegments.Find(start, end)) {
return false;
}
PerpendicularScanSegments.InsertUnique(new ScanSegment(start, end, ScanSegment.ReflectionWeight, gbcList: null));
return true;
}
protected override bool InsertParallelReflectionSegment(Point start, Point end, Obstacle eventObstacle,
BasicObstacleSide lowNborSide, BasicObstacleSide highNborSide, BasicReflectionEvent action) {
// See notes in InsertPerpendicularReflectionSegment for comments about an existing segment.
// Here, we call AddSegment which adds the segment and continues the reflection staircase.
if (null != ParallelScanSegments.Find(start, end)) {
return false;
}
return AddSegment(start, end, eventObstacle, lowNborSide, highNborSide, action, ScanSegment.ReflectionWeight);
}
// Return value is whether or not we added a new segment.
bool AddSegment(Point start, Point end, Obstacle eventObstacle
, BasicObstacleSide lowNborSide, BasicObstacleSide highNborSide
, SweepEvent action, double weight) {
DevTraceInfoVgGen(1, "Adding Segment [{0} -> {1} {2}] weight {3}", start, end, weight);
DevTraceInfoVgGen(2, " side {0}", lowNborSide);
DevTraceInfoVgGen(2, " -> side {0}", highNborSide);
if (PointComparer.Equal(start, end)) {
return false;
}
// See if the new segment subsumes or can be subsumed by the last one. gbcList may be null.
PointAndCrossingsList gbcList = CurrentGroupBoundaryCrossingMap.GetOrderedListBetween(start, end);
bool extendStart, extendEnd;
bool wasSubsumed = ScanSegment.Subsume(ref hintScanSegment, start, end, weight, gbcList, ScanDirection
, ParallelScanSegments, out extendStart, out extendEnd);
if (!wasSubsumed) {
Debug.Assert((weight != ScanSegment.ReflectionWeight) || (ParallelScanSegments.Find(start, end) == null),
"Reflection segments already in the ScanSegmentTree should should have been detected before calling AddSegment");
hintScanSegment = ParallelScanSegments.InsertUnique(new ScanSegment(start, end, weight, gbcList)).Item;
} else if (weight == ScanSegment.ReflectionWeight) {
// Do not continue this; it is probably a situation where a side is at a tiny angle from the axis,
// resulting in an initial reflection segment that is parallel and very close to the extreme-vertex-derived
// segment, so as the staircase progresses they eventually converge due to floating-point rounding.
// See RectilinearFilesTest.ReflectionStaircasesConverge.
return false;
}
// Do reflections only if the new segment is not overlapped.
if (ScanSegment.OverlappedWeight != weight) {
// If these fire, it's probably an indication that isOverlapped is not correctly set
// and one of the neighbors is an OverlapSide from CreateScanSegments.
Debug.Assert(lowNborSide is HighObstacleSide, "lowNbor is not HighObstacleSide");
Debug.Assert(highNborSide is LowObstacleSide, "highNbor is not LowObstacleSide");
// If we are closing the obstacle then the initial Obstacles of the reflections (the ones it
// will bounce between) are the opposite neighbors. Otherwise, the OpenVertexEvent obstacle
// is the ReflectionEvent initial obstacle.
if (action is CloseVertexEvent) {
// If both neighbor sides reflect upward, they can't intersect, so we don't need
// to store a lookahead site (if neither reflect upward, StoreLookaheadSite no-ops).
if (!SideReflectsUpward(lowNborSide) || !SideReflectsUpward(highNborSide)) {
// Try to store both; only one will "take" (for the upward-reflecting side).
// The initial Obstacle is the opposite neighbor.
if (extendStart) {
this.StoreLookaheadSite(highNborSide.Obstacle, lowNborSide, start, wantExtreme:false);
}
if (extendEnd) {
this.StoreLookaheadSite(lowNborSide.Obstacle, highNborSide, end, wantExtreme: false);
}
}
}
else {
if (extendStart) {
StoreLookaheadSite(eventObstacle, LowNeighborSides.GroupSideInterveningBeforeLowNeighbor, lowNborSide, start);
}
if (extendEnd) {
StoreLookaheadSite(eventObstacle, HighNeighborSides.GroupSideInterveningBeforeHighNeighbor, highNborSide, end);
}
}
}
DevTraceInfoVgGen(2, "HintScanSegment {0}{1}", hintScanSegment, wasSubsumed ? " (subsumed)" : "");
DevTrace_DumpScanSegmentsDuringAdd(3);
return true;
}
private void StoreLookaheadSite(Obstacle eventObstacle, BasicObstacleSide interveningGroupSide, BasicObstacleSide neighborSide, Point siteOnSide) {
// For reflections, NeighborSides won't be set, so there won't be an intervening group. Otherwise,
// this is on an OpenVertexEvent, so we'll either reflect of the intervening group if any, or neighborSide.
if (null == interveningGroupSide) {
this.StoreLookaheadSite(eventObstacle, neighborSide, siteOnSide, wantExtreme: false);
} else {
var siteOnGroup = ScanLineIntersectSide(siteOnSide, interveningGroupSide, this.ScanDirection);
this.StoreLookaheadSite(eventObstacle, interveningGroupSide, siteOnGroup, wantExtreme: false);
}
}
private bool IntersectionAtSideIsInsideAnotherObstacle(BasicObstacleSide side, BasicVertexEvent vertexEvent) {
Point intersect = ScanLineIntersectSide(vertexEvent.Site, side);
return IntersectionAtSideIsInsideAnotherObstacle(side, vertexEvent.Obstacle, intersect);
}
// obstacleToIgnore is the event obstacle if we're looking at intersections along its boundary.
private bool IntersectionAtSideIsInsideAnotherObstacle(BasicObstacleSide side, Obstacle eventObstacle, Point intersect) {
// See if the intersection with an obstacle side is inside another obstacle (that encloses
// at least the part of side.Obstacle containing the intersection). This will only happen
// if side.Obstacle is overlapped and in the same clump (if it's not the same clump, we must
// be hitting it from the outside).
if (!side.Obstacle.IsOverlapped) {
return false;
}
if (!side.Obstacle.IsGroup && !eventObstacle.IsGroup && (side.Obstacle.Clump != eventObstacle.Clump)) {
return false;
}
return ObstacleTree.IntersectionIsInsideAnotherObstacle(side.Obstacle, eventObstacle, intersect, ScanDirection);
}
// As described in the document, we currently don't create ScanSegments where a flat top/bottom boundary may have
// intervals that are embedded within overlapped segments:
// obstacle1 | |obstacle2 | obstacle3 | | obstacle4 | obstacle2| |
// | +-----------|===========|??????????|===========|----------+ | obstacle5
// ...__________| |___________| |___________| |__________...
// Here, there will be no ScanSegment created at ??? along the border of obstacle2 between obstacle3
// and obstacle4. This is not a concern because that segment is useless anyway; a path from outside
// obstacle2 will not be able to see it unless there is another obstacle in that gap, and then that
// obstacle's side-derived ScanSegments will create non-overlapped edges; and there are already edges
// from the upper/lower extreme vertices of obstacle 3 and obstacle4 to ensure a connected graph.
// If there is a routing from an obstacle outside obstacle2 to one embedded within obstacle2, the
// port visibility will create the necessary edges.
//
// We don't try to determine nesting depth and create different VisibilityEdge weights to prevent spurious
// nested-obstacle crossings; we just care about overlapped vs. not-overlapped.
// If this changes, we would have to: Find the overlap depth at the lowNborSide intersection,
// then increment/decrement according to side type as we move from low to high, then create a different
// ScanSegment at each obstacle-side crossing, making ScanSegment.IsOverlapped a depth instead of bool.
// Then pass that depth through to VisibilityEdge as an increased weight. (This would also automatically
// handle the foregoing situation of non-overlapped intervals in the middle of a flat top/bottom border,
// not that it would really gain anything).
void CreateScanSegments(Obstacle obstacle, HighObstacleSide lowNborSide, BasicObstacleSide lowOverlapSide,
BasicObstacleSide highOverlapSide, LowObstacleSide highNborSide, BasicVertexEvent vertexEvent) {
// If we have either of the high/low OverlapSides, we'll need to see if they're inside
// another obstacle. If not, they end the overlap.
if ((null == highOverlapSide) || IntersectionAtSideIsInsideAnotherObstacle(highOverlapSide, vertexEvent)) {
highOverlapSide = highNborSide;
}
if ((null == lowOverlapSide) || IntersectionAtSideIsInsideAnotherObstacle(lowOverlapSide, vertexEvent)) {
lowOverlapSide = lowNborSide;
}
// There may be up to 3 segments; for a simple diagram, |# means low-side border of
// obstacle '#' and #| means high-side, with 'v' meaning our event vertex. Here are
// the two cases where we create a single non-overlapped ScanSegment (from the Low
// side in the diagram, but the same logic works for the High side).
// - non-overlapped: 1| v |2
// ...---+ +---...
// - non-overlapped to an "inner" highNbor on a flat border: 1| vLow |2 vHigh
// ...---+ +-----+=========...
// This may be the low side of a flat bottom or top border, so lowNbor or highNbor
// may be in the middle of the border.
Point lowNborIntersect = ScanLineIntersectSide(vertexEvent.Site, lowNborSide);
Point highNborIntersect = ScanLineIntersectSide(vertexEvent.Site, highNborSide);
bool lowNborEndpointIsOverlapped = IntersectionAtSideIsInsideAnotherObstacle(lowNborSide,
vertexEvent.Obstacle /*obstacleToIgnore*/, lowNborIntersect);
if (!lowNborEndpointIsOverlapped && (lowNborSide == lowOverlapSide)) {
// Nothing is overlapped so create one segment.
AddSegment(lowNborIntersect, highNborIntersect, obstacle, lowNborSide, highNborSide, vertexEvent,
ScanSegment.NormalWeight);
return;
}
// Here are the different interval combinations for overlapped cases.
// - non-overlapped, overlapped: 1| |2 v |3
// ...---+ +------+===...
// - non-overlapped, overlapped, non-overlapped: 1| |2 v 2| |3
// ==+ +-------+ +--...
// - overlapped: |1 2| v |3 ...1|
// ...---+====+-----+===...-+
// - overlapped, non-overlapped: |1 2| v 1| |3
// ...---+====+------+ +---...
// We will not start overlapped and then go to non-overlapped and back to overlapped,
// because we would have found the overlap-ending/beginning sides as nearer neighbors.
// Get the other intersections we'll want.
Point highOverlapIntersect = (highOverlapSide == highNborSide) ? highNborIntersect
: ScanLineIntersectSide(vertexEvent.Site, highOverlapSide);
Point lowOverlapIntersect = (lowOverlapSide == lowNborSide) ? lowNborIntersect
: ScanLineIntersectSide(vertexEvent.Site, lowOverlapSide);
// Create the segments.
if (!lowNborEndpointIsOverlapped) {
// First interval is non-overlapped; there is a second overlapped interval, and may be a
// third non-overlapping interval if another obstacle surrounded this vertex.
AddSegment(lowNborIntersect, lowOverlapIntersect, obstacle, lowNborSide, lowOverlapSide, vertexEvent,
ScanSegment.NormalWeight);
AddSegment(lowOverlapIntersect, highOverlapIntersect, obstacle, lowOverlapSide, highOverlapSide, vertexEvent,
ScanSegment.OverlappedWeight);
if (highOverlapSide != highNborSide) {
AddSegment(highOverlapIntersect, highNborIntersect, obstacle, highOverlapSide, highNborSide, vertexEvent,
ScanSegment.NormalWeight);
}
}
else {
// Starts off overlapped so ignore lowOverlapSide.
AddSegment(lowNborIntersect, highOverlapIntersect, obstacle, lowNborSide, highOverlapSide, vertexEvent,
ScanSegment.OverlappedWeight);
if (highOverlapSide != highNborSide) {
AddSegment(highOverlapIntersect, highNborIntersect, obstacle, highOverlapSide, highNborSide, vertexEvent,
ScanSegment.NormalWeight);
}
}
}
void CreateScanSegments(Obstacle obstacle, NeighborSides neighborSides, BasicVertexEvent vertexEvent) {
this.CreateScanSegments(obstacle, (HighObstacleSide)neighborSides.LowNeighbor.Item
, (null == neighborSides.LowOverlapEnd) ? null : neighborSides.LowOverlapEnd.Item
, (null == neighborSides.HighOverlapEnd) ? null : neighborSides.HighOverlapEnd.Item
, (LowObstacleSide)neighborSides.HighNeighbor.Item, vertexEvent);
}
private void CreateScanSegmentFromLowSide(RBNode<BasicObstacleSide> lowSideNode, BasicVertexEvent vertexEvent) {
// Create one or more segments from low to high using the neighbors of the LowObstacleSide.
this.CreateScanSegments(lowSideNode.Item.Obstacle, this.LowNeighborSides, vertexEvent);
}
void CreateScanSegmentFromHighSide(RBNode<BasicObstacleSide> highSideNode, BasicVertexEvent vertexEvent) {
// Create one or more segments from low to high using the neighbors of the HighObstacleSide.
this.CreateScanSegments(highSideNode.Item.Obstacle, this.HighNeighborSides, vertexEvent);
}
protected override void ProcessVertexEvent(RBNode<BasicObstacleSide> lowSideNode,
RBNode<BasicObstacleSide> highSideNode, BasicVertexEvent vertexEvent) {
// Create the scan segment from the low side.
CreateScanSegmentFromLowSide(lowSideNode, vertexEvent);
// If the low segment covered up to our high neighbor, we're done. Otherwise, there were overlaps
// inside a flat boundary and now we need to come in from the high side. In this case there's a chance
// that we're redoing a single subsegment in the event of two obstacles' outside edges crossing
// the middle of a flat boundary of the event obstacle, but that should be sufficiently rare that
// we don't need to optimize it away as the segments will be merged by ScanSegmentTree.MergeSegments.
// TODOgroup TODOperf: currentGroupBoundaryCrossingMap still has the Low-side stuff in it but it shouldn't
// matter much - profile to see how much time GetOrderedIndexBetween takes.
if (LowNeighborSides.HighNeighbor.Item != HighNeighborSides.HighNeighbor.Item) {
CreateScanSegmentFromHighSide(highSideNode, vertexEvent);
}
}
}
}
| |
// 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.IO;
using System.Reflection;
using System.Collections;
using NUnit.Framework;
using Microsoft.Build.Framework;
using Microsoft.Build.BuildEngine;
namespace Microsoft.Build.UnitTests
{
internal class MockTaskBase
{
private bool myBoolParam = false;
private bool[] myBoolArrayParam = null;
private int myIntParam = 0;
private int[] myIntArrayParam = null;
private string myStringParam = null;
private string[] myStringArrayParam = null;
private ITaskItem myITaskItemParam = null;
private ITaskItem[] myITaskItemArrayParam = null;
private bool myRequiredBoolParam = false;
private bool[] myRequiredBoolArrayParam = null;
private int myRequiredIntParam = 0;
private int[] myRequiredIntArrayParam = null;
private string myRequiredStringParam = null;
private string[] myRequiredStringArrayParam = null;
private ITaskItem myRequiredITaskItemParam = null;
private ITaskItem[] myRequiredITaskItemArrayParam = null;
internal bool myBoolParamWasSet = false;
internal bool myBoolArrayParamWasSet = false;
internal bool myIntParamWasSet = false;
internal bool myIntArrayParamWasSet = false;
internal bool myStringParamWasSet = false;
internal bool myStringArrayParamWasSet = false;
internal bool myITaskItemParamWasSet = false;
internal bool myITaskItemArrayParamWasSet = false;
// disable csharp compiler warning #0414: field assigned unused value
#pragma warning disable 0414
internal bool myRequiredBoolParamWasSet = false;
internal bool myRequiredBoolArrayParamWasSet = false;
internal bool myRequiredIntParamWasSet = false;
internal bool myRequiredIntArrayParamWasSet = false;
internal bool myRequiredStringParamWasSet = false;
internal bool myRequiredStringArrayParamWasSet = false;
internal bool myRequiredITaskItemParamWasSet = false;
internal bool myRequiredITaskItemArrayParamWasSet = false;
#pragma warning restore 0414
/// <summary>
/// Single bool parameter.
/// </summary>
/// <owner>RGoel</owner>
public bool MyBoolParam
{
get { return this.myBoolParam; }
set { this.myBoolParam = value; this.myBoolParamWasSet = true; }
}
/// <summary>
/// bool[] parameter.
/// </summary>
/// <owner>RGoel</owner>
public bool[] MyBoolArrayParam
{
get { return this.myBoolArrayParam; }
set { this.myBoolArrayParam = value; this.myBoolArrayParamWasSet = true; }
}
/// <summary>
/// Single int parameter.
/// </summary>
/// <owner>RGoel</owner>
public int MyIntParam
{
get { return this.myIntParam; }
set { this.myIntParam = value; this.myIntParamWasSet = true; }
}
/// <summary>
/// int[] parameter.
/// </summary>
/// <owner>RGoel</owner>
public int[] MyIntArrayParam
{
get { return this.myIntArrayParam; }
set { this.myIntArrayParam = value; this.myIntArrayParamWasSet = true; }
}
/// <summary>
/// Single string parameter
/// </summary>
/// <owner>RGoel</owner>
public string MyStringParam
{
get { return this.myStringParam; }
set { this.myStringParam = value; this.myStringParamWasSet = true; }
}
/// <summary>
/// A string array parameter.
/// </summary>
/// <owner>JomoF</owner>
public string[] MyStringArrayParam
{
get { return this.myStringArrayParam; }
set { this.myStringArrayParam = value; this.myStringArrayParamWasSet = true; }
}
/// <summary>
/// Single ITaskItem parameter.
/// </summary>
/// <owner>RGoel</owner>
public ITaskItem MyITaskItemParam
{
get { return this.myITaskItemParam; }
set { this.myITaskItemParam = value; this.myITaskItemParamWasSet = true; }
}
/// <summary>
/// ITaskItem[] parameter.
/// </summary>
/// <owner>RGoel</owner>
public ITaskItem[] MyITaskItemArrayParam
{
get { return this.myITaskItemArrayParam; }
set { this.myITaskItemArrayParam = value; this.myITaskItemArrayParamWasSet = true; }
}
/// <summary>
/// Single bool parameter.
/// </summary>
/// <owner>RGoel</owner>
[Required]
public bool MyRequiredBoolParam
{
get { return this.myRequiredBoolParam; }
set { this.myRequiredBoolParam = value; this.myRequiredBoolParamWasSet = true; }
}
/// <summary>
/// bool[] parameter.
/// </summary>
/// <owner>RGoel</owner>
[Required]
public bool[] MyRequiredBoolArrayParam
{
get { return this.myRequiredBoolArrayParam; }
set { this.myRequiredBoolArrayParam = value; this.myRequiredBoolArrayParamWasSet = true; }
}
/// <summary>
/// Single int parameter.
/// </summary>
/// <owner>RGoel</owner>
[Required]
public int MyRequiredIntParam
{
get { return this.myRequiredIntParam; }
set { this.myRequiredIntParam = value; this.myRequiredIntParamWasSet = true; }
}
/// <summary>
/// int[] parameter.
/// </summary>
/// <owner>RGoel</owner>
[Required]
public int[] MyRequiredIntArrayParam
{
get { return this.myRequiredIntArrayParam; }
set { this.myRequiredIntArrayParam = value; this.myRequiredIntArrayParamWasSet = true; }
}
/// <summary>
/// Single string parameter
/// </summary>
/// <owner>RGoel</owner>
[Required]
public string MyRequiredStringParam
{
get { return this.myRequiredStringParam; }
set { this.myRequiredStringParam = value; this.myRequiredStringParamWasSet = true; }
}
/// <summary>
/// A string array parameter.
/// </summary>
/// <owner>JomoF</owner>
[Required]
public string[] MyRequiredStringArrayParam
{
get { return this.myRequiredStringArrayParam; }
set { this.myRequiredStringArrayParam = value; this.myRequiredStringArrayParamWasSet = true; }
}
/// <summary>
/// Single ITaskItem parameter.
/// </summary>
/// <owner>RGoel</owner>
[Required]
public ITaskItem MyRequiredITaskItemParam
{
get { return this.myRequiredITaskItemParam; }
set { this.myRequiredITaskItemParam = value; this.myRequiredITaskItemParamWasSet = true; }
}
/// <summary>
/// ITaskItem[] parameter.
/// </summary>
/// <owner>RGoel</owner>
[Required]
public ITaskItem[] MyRequiredITaskItemArrayParam
{
get { return this.myRequiredITaskItemArrayParam; }
set { this.myRequiredITaskItemArrayParam = value; this.myRequiredITaskItemArrayParamWasSet = true; }
}
/// <summary>
/// ArrayList output parameter. (This is not supported by MSBuild.)
/// </summary>
/// <owner>RGoel</owner>
[Output]
public ArrayList MyArrayListOutputParam
{
get { return null; }
}
/// <summary>
/// Null ITaskItem[] output parameter.
/// </summary>
/// <owner>danmose</owner>
[Output]
public ITaskItem[] NullITaskItemArrayOutputParameter
{
get
{
ITaskItem[] myNullITaskItemArrayOutputParameter = null;
return myNullITaskItemArrayOutputParameter;
}
}
/// <summary>
/// Empty string output parameter.
/// </summary>
/// <owner>danmose</owner>
[Output]
public string EmptyStringOutputParameter
{
get
{
return String.Empty;
}
}
/// <summary>
/// Empty string output parameter.
/// </summary>
/// <owner>danmose</owner>
[Output]
public string[] EmptyStringInStringArrayOutputParameter
{
get
{
string[] myArray = new string[] { "" };
return myArray;
}
}
/// <summary>
/// ITaskItem output parameter.
/// </summary>
/// <owner>danmose</owner>
[Output]
public ITaskItem ITaskItemOutputParameter
{
get
{
ITaskItem myITaskItem = null;
return myITaskItem;
}
}
/// <summary>
/// string output parameter.
/// </summary>
/// <owner>danmose</owner>
[Output]
public string StringOutputParameter
{
get
{
return "foo";
}
}
/// <summary>
/// string array output parameter.
/// </summary>
/// <owner>danmose</owner>
[Output]
public string[] StringArrayOutputParameter
{
get
{
return new string[] { "foo", "bar" };
}
}
/// <summary>
/// int output parameter.
/// </summary>
/// <owner>danmose</owner>
[Output]
public int IntOutputParameter
{
get
{
return 1;
}
}
/// <summary>
/// int array output parameter.
/// </summary>
/// <owner>danmose</owner>
[Output]
public int[] IntArrayOutputParameter
{
get
{
return new int[] { 1, 2 };
}
}
/// <summary>
/// object array output parameter.
/// </summary>
/// <owner>danmose</owner>
[Output]
public object[] ObjectArrayOutputParameter
{
get
{
return new object[] { new Object() };
}
}
/// <summary>
/// itaskitem implementation output parameter
/// </summary>
[Output]
public MyTaskItem MyTaskItemOutputParameter
{
get
{
return new MyTaskItem();
}
}
/// <summary>
/// itaskitem implementation array output parameter
/// </summary>
[Output]
public MyTaskItem[] MyTaskItemArrayOutputParameter
{
get
{
return new MyTaskItem[] { new MyTaskItem() };
}
}
/// <summary>
/// taskitem output parameter
/// </summary>
[Output]
public TaskItem TaskItemOutputParameter
{
get
{
return new TaskItem("foo");
}
}
/// <summary>
/// taskitem array output parameter
/// </summary>
[Output]
public TaskItem[] TaskItemArrayOutputParameter
{
get
{
return new TaskItem[] { new TaskItem("foo") };
}
}
}
/// <summary>
/// A simple mock task for use with Unit Testing.
/// </summary>
/// <owner>JomoF</owner>
sealed internal class MockTask : MockTaskBase,ITask
{
private IBuildEngine e = null;
/// <summary>
/// Task constructor.
/// </summary>
/// <param name="e"></param>
/// <owner>JomoF</owner>
public MockTask(IBuildEngine e)
{
this.e = e;
}
/// <summary>
/// Access the engine.
/// </summary>
/// <owner>JomoF</owner>
public IBuildEngine BuildEngine
{
get {return this.e;}
set {this.e = value;}
}
/// <summary>
/// Access the host object.
/// </summary>
/// <owner>RGoel</owner>
public ITaskHost HostObject
{
get {return null;}
set {}
}
/// <summary>
/// Main Execute method of the task does nothing.
/// </summary>
/// <returns>true if successful</returns>
/// <owner>JomoF</owner>
public bool Execute()
{
return true;
}
}
/// <summary>
/// Custom implementation of ITaskItem for unit testing
/// Just TaskItem would work fine, but why not test a custom type as well
/// </summary>
internal class MyTaskItem : ITaskItem
{
#region ITaskItem Members
public string ItemSpec
{
get
{
return "foo";
}
set
{
// do nothing
}
}
public ICollection MetadataNames
{
get
{
return new ArrayList();
}
}
public int MetadataCount
{
get { return 1; }
}
public string GetMetadata(string attributeName)
{
return "foo";
}
public void SetMetadata(string attributeName, string attributeValue)
{
// do nothing
}
public void RemoveMetadata(string attributeName)
{
// do nothing
}
public void CopyMetadataTo(ITaskItem destinationItem)
{
// do nothing
}
public IDictionary CloneCustomMetadata()
{
return new Hashtable();
}
#endregion
}
}
| |
#region Copyright
//=======================================================================================
// Microsoft Azure Customer Advisory Team
//
// This sample is supplemental to the technical guidance published on my personal
// blog at http://blogs.msdn.com/b/paolos/.
//
// Author: Paolo Salvatori
//=======================================================================================
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// LICENSED UNDER THE APACHE LICENSE, VERSION 2.0 (THE "LICENSE"); YOU MAY NOT USE THESE
// FILES EXCEPT IN COMPLIANCE WITH THE LICENSE. YOU MAY OBTAIN A COPY OF THE LICENSE AT
// http://www.apache.org/licenses/LICENSE-2.0
// UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING, SOFTWARE DISTRIBUTED UNDER THE
// LICENSE IS DISTRIBUTED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, EITHER EXPRESS OR IMPLIED. SEE THE LICENSE FOR THE SPECIFIC LANGUAGE GOVERNING
// PERMISSIONS AND LIMITATIONS UNDER THE LICENSE.
//=======================================================================================
#endregion
#region Using Directives
using System;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
using System.Windows.Forms.Design;
using Microsoft.Azure.ServiceBusExplorer.Helpers;
#endregion
namespace Microsoft.Azure.ServiceBusExplorer.Controls
{
internal partial class StandardValueEditorUI : UserControl
{
private class TagItem
{
public bool SetByCode = false;
public StandardValueAttribute Item = null;
public TagItem(StandardValueAttribute item)
{
Item = item;
}
}
private Type m_PropertyType = Type.Missing.GetType();
private Type m_EnumDataType = Type.Missing.GetType();
private object m_Value = null;
IWindowsFormsEditorService m_editorService = null;
private bool m_bFlag = false;
public StandardValueEditorUI()
{
InitializeComponent();
}
public void SetData(ITypeDescriptorContext context, IWindowsFormsEditorService editorService, object value)
{
m_editorService = editorService;
m_PropertyType = context.PropertyDescriptor.PropertyType;
if (m_PropertyType.IsEnum)
{
m_EnumDataType = Enum.GetUnderlyingType(m_PropertyType);
m_bFlag = (m_PropertyType.GetCustomAttributes(typeof(FlagsAttribute), false).Length > 0);
}
m_Value = value;
listViewEnum.Items.Clear();
listViewEnum.CheckBoxes = m_bFlag;
if (!(context.PropertyDescriptor is CustomPropertyDescriptor))
{
throw new Exception("PropertyDescriptorManager has not been installed on this instance.");
}
var customPropertyDescriptor = context.PropertyDescriptor as CustomPropertyDescriptor;
// create list view items for the visible Enum items
foreach (var standardValueAttribute in customPropertyDescriptor.StandardValues)
{
if (standardValueAttribute.Visible)
{
var lvi = new ListViewItem();
lvi.Text = standardValueAttribute.DisplayName;
lvi.ForeColor = (standardValueAttribute.Enabled ? lvi.ForeColor : Color.FromKnownColor(KnownColor.GrayText));
lvi.Tag = new TagItem(standardValueAttribute);
listViewEnum.Items.Add(lvi);
}
}
UpdateCheckState();
// make initial selection
if (m_bFlag)
{
// select the first checked one
foreach (ListViewItem lvi in listViewEnum.CheckedItems)
{
lvi.Selected = true;
lvi.EnsureVisible();
break;
}
}
else
{
foreach (ListViewItem lvi in listViewEnum.Items)
{
var ti = lvi.Tag as TagItem;
if (ti != null && ti.Item.Value.Equals(m_Value))
{
lvi.Selected = true;
lvi.EnsureVisible();
break;
}
}
}
}
public object GetValue()
{
if (m_PropertyType.IsEnum)
{
return Enum.ToObject(m_PropertyType, m_Value);
}
if (m_PropertyType == typeof(bool))
{
return Convert.ToBoolean(m_Value);
}
return m_Value;
}
private void listViewEnum_ItemCheck(object sender, ItemCheckEventArgs e)
{
var ti = listViewEnum.Items[e.Index].Tag as TagItem;
if (ti.SetByCode)
{
ti.SetByCode = false;
return;
}
if (!ti.Item.Enabled)
{
e.NewValue = e.CurrentValue;
return;
}
if (e.NewValue == CheckState.Checked)
{
if (IsZero(m_EnumDataType, ti.Item.Value)) // user is chekcing the item with zero value ( None )
{
m_Value = 0;
}
else
{
AddBits(m_EnumDataType, ref m_Value, ti.Item.Value);
}
}
else
{
var _copyValue = m_Value;
RemoveBits(m_EnumDataType, ref m_Value, ti.Item.Value);
if (IsZeroValueSituation())
{
m_Value = _copyValue;
}
}
e.NewValue = e.CurrentValue;
UpdateCheckState(); // this will change the check box on the list view item
}
private bool IsZeroValueSituation()
{
if (IsZero(m_EnumDataType, m_Value))
{
if (!Enum.IsDefined(m_PropertyType, m_Value))
{
return true;
}
}
return false;
}
private void listViewEnum_SelectedIndexChanged(object sender, EventArgs e)
{
if (listViewEnum.SelectedItems.Count > 0)
{
var listView = (ListView)sender;
var ti = listView.SelectedItems[0].Tag as TagItem;
lblDispName.Text = ti.Item.DisplayName;
lblDesc.Text = ti.Item.Description;
if (!m_bFlag)
{
if (!ti.Item.Enabled)
{
return;
}
m_Value = ti.Item.Value;
}
}
}
private void listViewEnum_MouseDoubleClick(object sender, MouseEventArgs e)
{
m_editorService.CloseDropDown();
}
private void listViewEnum_SizeChanged(object sender, EventArgs e)
{
listViewEnum.Columns[0].Width = listViewEnum.Width - 20;
listViewEnum.Invalidate();
lblDesc.Invalidate();
this.Invalidate();
}
void UpdateCheckState()
{
if (!m_bFlag)
{
return;
}
foreach (ListViewItem lvi in listViewEnum.Items)
{
var ti = lvi.Tag as TagItem;
var bitExist = DoBitsExist(Enum.GetUnderlyingType(m_PropertyType), m_Value, ti.Item.Value);
if (lvi.Checked != DoBitsExist(Enum.GetUnderlyingType(m_PropertyType), m_Value, ti.Item.Value))
{
ti.SetByCode = true;
lvi.Checked = bitExist;
}
}
}
private bool DoBitsExist(Type enumDataType, object value, object bits)
{
// zero needs special treatment, because you cannot do bitwise operations using zeros
var valueIsZero = IsZero(enumDataType, value);
var bitsIsZero = IsZero(enumDataType, bits);
if (valueIsZero && bitsIsZero)
return true;
if (valueIsZero)
return false;
if (bitsIsZero)
return false;
// otherwise (!valueIsZero && !bitsIsZero)
if (enumDataType == typeof(short))
{
var _value = Convert.ToInt16(value);
var _bits = Convert.ToInt16(bits);
return (_value & _bits) == _bits;
}
if (enumDataType == typeof(ushort))
{
var _value = Convert.ToUInt16(value);
var _bits = Convert.ToUInt16(bits);
return (_value & _bits) == _bits;
}
if (enumDataType == typeof(int))
{
var _value = Convert.ToInt32(value);
var _bits = Convert.ToInt32(bits);
return (_value & _bits) == _bits;
}
if (enumDataType == typeof(uint))
{
var _value = Convert.ToUInt32(value);
var _bits = Convert.ToUInt32(bits);
return (_value & _bits) == _bits;
}
if (enumDataType == typeof(long))
{
var _value = Convert.ToInt64(value);
var _bits = Convert.ToInt64(bits);
return (_value & _bits) == _bits;
}
if (enumDataType == typeof(ulong))
{
var _value = Convert.ToUInt64(value);
var _bits = Convert.ToUInt64(bits);
return (_value & _bits) == _bits;
}
if (enumDataType == typeof(sbyte))
{
var _value = Convert.ToSByte(value);
var _bits = Convert.ToSByte(bits);
return (_value & _bits) == _bits;
}
if (enumDataType == typeof(byte))
{
var _value = Convert.ToByte(value);
var _bits = Convert.ToByte(bits);
return (_value & _bits) == _bits;
}
return false;
}
private void RemoveBits(Type enumDataType, ref object value, object bits)
{
if (enumDataType == typeof(short))
{
var _value = Convert.ToInt32(value);
var _bits = Convert.ToInt32(bits);
_value &= ~_bits;
value = _value;
}
else if (enumDataType == typeof(ushort))
{
var _value = Convert.ToUInt32(value);
var _bits = Convert.ToUInt32(bits);
_value &= ~_bits;
value = _value;
}
else if (enumDataType == typeof(int))
{
var _value = Convert.ToInt32(value);
var _bits = Convert.ToInt32(bits);
_value &= ~_bits;
value = _value;
}
else if (enumDataType == typeof(uint))
{
var _value = Convert.ToUInt32(value);
var _bits = Convert.ToUInt32(bits);
_value &= ~_bits;
value = _value;
}
else if (enumDataType == typeof(long))
{
var _value = Convert.ToInt64(value);
var _bits = Convert.ToInt64(bits);
_value &= ~_bits;
value = _value;
}
else if (enumDataType == typeof(ulong))
{
var _value = Convert.ToUInt64(value);
var _bits = Convert.ToUInt64(bits);
_value &= ~_bits;
value = _value;
}
else if (enumDataType == typeof(sbyte))
{
var _value = Convert.ToInt32(value);
var _bits = Convert.ToInt32(bits);
_value &= ~_bits;
value = _value;
}
else if (enumDataType == typeof(byte))
{
var _value = Convert.ToInt32(value);
var _bits = Convert.ToInt32(bits);
_value &= ~_bits;
value = _value;
}
}
private void AddBits(Type enumDataType, ref object value, object bits)
{
if (enumDataType == typeof(short))
{
var _value = Convert.ToInt32(value);
var _bits = Convert.ToInt32(bits);
_value |= _bits;
value = _value;
}
else if (enumDataType == typeof(ushort))
{
var _value = Convert.ToUInt32(value);
var _bits = Convert.ToUInt32(bits);
_value |= _bits;
value = _value;
}
else if (enumDataType == typeof(int))
{
var _value = Convert.ToInt32(value);
var _bits = Convert.ToInt32(bits);
_value |= _bits;
value = _value;
}
else if (enumDataType == typeof(uint))
{
var _value = Convert.ToUInt32(value);
var _bits = Convert.ToUInt32(bits);
_value |= _bits;
value = _value;
}
else if (enumDataType == typeof(long))
{
var _value = Convert.ToInt64(value);
var _bits = Convert.ToInt64(bits);
_value |= _bits;
value = _value;
}
else if (enumDataType == typeof(ulong))
{
var _value = Convert.ToUInt64(value);
var _bits = Convert.ToUInt64(bits);
_value |= _bits;
value = _value;
}
else if (enumDataType == typeof(sbyte))
{
var _value = Convert.ToInt32(value);
var _bits = Convert.ToInt32(bits);
_value |= _bits;
value = _value;
}
else if (enumDataType == typeof(byte))
{
var _value = Convert.ToInt32(value);
var _bits = Convert.ToInt32(bits);
_value |= _bits;
value = _value;
}
}
private bool IsZero(Type enumDataType, object value)
{
if (enumDataType == typeof(Int16))
{
var _value = Convert.ToInt16(value);
return (_value == 0);
}
if (enumDataType == typeof(UInt16))
{
var _value = Convert.ToUInt16(value);
return (_value == 0);
}
if (enumDataType == typeof(Int32))
{
var _value = Convert.ToInt32(value);
return (_value == 0);
}
if (enumDataType == typeof(UInt32))
{
var _value = Convert.ToUInt32(value);
return (_value == 0);
}
if (enumDataType == typeof(Int64))
{
var _value = Convert.ToInt64(value);
return (_value == 0);
}
if (enumDataType == typeof(UInt64))
{
var _value = Convert.ToUInt64(value);
return (_value == 0);
}
if (enumDataType == typeof(SByte))
{
var _value = Convert.ToSByte(value);
return (_value == 0);
}
if (enumDataType == typeof(Byte))
{
var _value = Convert.ToByte(value);
return (_value == 0);
}
return false;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// See the LICENSE file in the project root for more information.
// (C) Copyright 2002 Franklin Wise
// (C) Copyright 2003 Martin Willemoes Hansen
//
//
// Copyright (C) 2004 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using Xunit;
namespace System.Data.Tests
{
public class DataRowCollectionTest
{
private DataTable _tbl;
public DataRowCollectionTest()
{
_tbl = new DataTable();
}
[Fact]
public void AutoIncrement()
{
DataColumn col = new DataColumn("Auto");
col.AutoIncrement = true;
col.AutoIncrementSeed = 0;
col.AutoIncrementStep = 1;
_tbl.Columns.Add(col);
_tbl.Rows.Add(_tbl.NewRow());
Assert.Equal(0, Convert.ToInt32(_tbl.Rows[0]["Auto"]));
_tbl.Rows.Add(_tbl.NewRow());
Assert.Equal(1, Convert.ToInt32(_tbl.Rows[1]["Auto"]));
col.AutoIncrement = false;
Assert.Equal(1, Convert.ToInt32(_tbl.Rows[1]["Auto"]));
_tbl.Rows.Add(_tbl.NewRow());
Assert.Equal(DBNull.Value, _tbl.Rows[2]["Auto"]);
col.AutoIncrement = true;
col.AutoIncrementSeed = 10;
col.AutoIncrementStep = 2;
_tbl.Rows.Add(_tbl.NewRow());
Assert.Equal(10, Convert.ToInt32(_tbl.Rows[3]["Auto"]));
_tbl.Rows.Add(_tbl.NewRow());
Assert.Equal(12, Convert.ToInt32(_tbl.Rows[4]["Auto"]));
col = new DataColumn("Auto2");
col.DataType = typeof(string);
col.AutoIncrement = true;
col.AutoIncrementSeed = 0;
col.AutoIncrementStep = 1;
_tbl.Columns.Add(col);
_tbl.Rows.Add(_tbl.NewRow());
Assert.Equal(typeof(int), _tbl.Columns[1].DataType);
Assert.Equal(typeof(int), _tbl.Rows[5]["Auto2"].GetType());
col = new DataColumn("Auto3");
col.AutoIncrement = true;
col.AutoIncrementSeed = 0;
col.AutoIncrementStep = 1;
col.DataType = typeof(string);
Assert.Equal(typeof(string), col.DataType);
Assert.False(col.AutoIncrement);
}
[Fact]
public void Add()
{
_tbl.Columns.Add();
_tbl.Columns.Add();
DataRow Row = _tbl.NewRow();
DataRowCollection Rows = _tbl.Rows;
Rows.Add(Row);
Assert.Equal(1, Rows.Count);
Assert.False(Rows.IsReadOnly);
Assert.False(Rows.IsSynchronized);
Assert.Equal("System.Data.DataRowCollection", Rows.ToString());
string[] cols = new string[2];
cols[0] = "first";
cols[1] = "second";
Rows.Add(cols);
cols[0] = "something";
cols[1] = "else";
Rows.Add(cols);
Assert.Equal(3, Rows.Count);
Assert.Equal("System.Data.DataRow", Rows[0].ToString());
Assert.Equal(DBNull.Value, Rows[0][0]);
Assert.Equal(DBNull.Value, Rows[0][1]);
Assert.Equal("first", Rows[1][0]);
Assert.Equal("something", Rows[2][0]);
Assert.Equal("second", Rows[1][1]);
Assert.Equal("else", Rows[2][1]);
try
{
Rows.Add(Row);
Assert.False(true);
}
catch (Exception e)
{
Assert.Equal(typeof(ArgumentException), e.GetType());
// Never premise English.
//Assert.Equal ("This row already belongs to this table.", e.Message);
}
try
{
Row = null;
Rows.Add(Row);
Assert.False(true);
}
catch (Exception e)
{
Assert.Equal(typeof(ArgumentNullException), e.GetType());
//Assert.Equal ("'row' argument cannot be null.\r\nParameter name: row", e.Message);
}
DataColumn Column = new DataColumn("not_null");
Column.AllowDBNull = false;
_tbl.Columns.Add(Column);
cols = new string[3];
cols[0] = "first";
cols[1] = "second";
cols[2] = null;
try
{
Rows.Add(cols);
Assert.False(true);
}
catch (Exception e)
{
Assert.Equal(typeof(NoNullAllowedException), e.GetType());
//Assert.Equal ("Column 'not_null' does not allow nulls.", e.Message);
}
Column = _tbl.Columns[0];
Column.Unique = true;
cols = new string[3];
cols[0] = "first";
cols[1] = "second";
cols[2] = "blabal";
try
{
Rows.Add(cols);
Assert.False(true);
}
catch (Exception e)
{
Assert.Equal(typeof(ConstraintException), e.GetType());
// Never premise English.
//Assert.Equal ("Column 'Column1' is constrained to be unique. Value 'first' is already present.", e.Message);
}
Column = new DataColumn("integer");
Column.DataType = typeof(short);
_tbl.Columns.Add(Column);
object[] obs = new object[4];
obs[0] = "_first";
obs[1] = "second";
obs[2] = "blabal";
obs[3] = "ads";
try
{
Rows.Add(obs);
Assert.False(true);
}
catch (ArgumentException e)
{
// MSDN says this exception is InvalidCastException
// Assert.Equal (typeof (ArgumentException), e.GetType ());
}
object[] obs1 = new object[5];
obs1[0] = "A";
obs1[1] = "B";
obs1[2] = "C";
obs1[3] = 38;
obs1[4] = "Extra";
try
{
Rows.Add(obs1);
Assert.False(true);
}
catch (Exception e)
{
Assert.Equal(typeof(ArgumentException), e.GetType());
}
}
[Fact]
public void Add_ByValuesNullTest()
{
DataTable t = new DataTable("test");
t.Columns.Add("id", typeof(int));
t.Columns.Add("name", typeof(string));
t.Columns.Add("nullable", typeof(string));
t.Columns[0].AutoIncrement = true;
t.Columns[0].AutoIncrementSeed = 10;
t.Columns[0].AutoIncrementStep = 5;
t.Columns[1].DefaultValue = "testme";
// null test & missing columns
DataRow r = t.Rows.Add(new object[] { null, null });
Assert.Equal(10, (int)r[0]);
Assert.Equal("testme", (string)r[1]);
Assert.Equal(DBNull.Value, r[2]);
// dbNull test
r = t.Rows.Add(new object[] { DBNull.Value, DBNull.Value, DBNull.Value });
Assert.Equal(DBNull.Value, r[0]);
Assert.Equal(DBNull.Value, r[1]);
Assert.Equal(DBNull.Value, r[2]);
// ai test & no default value test
r = t.Rows.Add(new object[] { null, null, null });
Assert.Equal(15, (int)r[0]);
Assert.Equal("testme", (string)r[1]);
Assert.Equal(DBNull.Value, r[2]);
}
[Fact]
public void Clear()
{
DataRowCollection Rows = _tbl.Rows;
DataTable Table = new DataTable("child");
Table.Columns.Add("first", typeof(int));
Table.Columns.Add("second", typeof(string));
_tbl.Columns.Add("first", typeof(int));
_tbl.Columns.Add("second", typeof(float));
string[] cols = new string[2];
cols[0] = "1";
cols[1] = "1,1";
Rows.Add(cols);
cols[0] = "2";
cols[1] = "2,1";
Rows.Add(cols);
cols[0] = "3";
cols[1] = "3,1";
Rows.Add(cols);
Assert.Equal(3, Rows.Count);
Rows.Clear();
Assert.Equal(0, Rows.Count);
cols[0] = "1";
cols[1] = "1,1";
Rows.Add(cols);
cols[0] = "2";
cols[1] = "2,1";
Rows.Add(cols);
cols[0] = "3";
cols[1] = "3,1";
Rows.Add(cols);
cols[0] = "1";
cols[1] = "test";
Table.Rows.Add(cols);
cols[0] = "2";
cols[1] = "test2";
Table.Rows.Add(cols);
cols[0] = "3";
cols[1] = "test3";
Table.Rows.Add(cols);
DataSet Set = new DataSet();
Set.Tables.Add(_tbl);
Set.Tables.Add(Table);
DataRelation Rel = new DataRelation("REL", _tbl.Columns[0], Table.Columns[0]);
Set.Relations.Add(Rel);
try
{
Rows.Clear();
Assert.False(true);
}
catch (InvalidConstraintException)
{
}
Assert.Equal(3, Table.Rows.Count);
Table.Rows.Clear();
Assert.Equal(0, Table.Rows.Count);
}
[Fact]
public void Contains()
{
DataColumn C = new DataColumn("key");
C.Unique = true;
C.DataType = typeof(int);
C.AutoIncrement = true;
C.AutoIncrementSeed = 0;
C.AutoIncrementStep = 1;
_tbl.Columns.Add(C);
_tbl.Columns.Add("first", typeof(string));
_tbl.Columns.Add("second", typeof(decimal));
DataRowCollection Rows = _tbl.Rows;
DataRow Row = _tbl.NewRow();
_tbl.Rows.Add(Row);
Row = _tbl.NewRow();
_tbl.Rows.Add(Row);
Row = _tbl.NewRow();
_tbl.Rows.Add(Row);
Row = _tbl.NewRow();
_tbl.Rows.Add(Row);
Rows[0][1] = "test0";
Rows[0][2] = 0;
Rows[1][1] = "test1";
Rows[1][2] = 1;
Rows[2][1] = "test2";
Rows[2][2] = 2;
Rows[3][1] = "test3";
Rows[3][2] = 3;
Assert.Equal(3, _tbl.Columns.Count);
Assert.Equal(4, _tbl.Rows.Count);
Assert.Equal(0, _tbl.Rows[0][0]);
Assert.Equal(1, _tbl.Rows[1][0]);
Assert.Equal(2, _tbl.Rows[2][0]);
Assert.Equal(3, _tbl.Rows[3][0]);
try
{
Rows.Contains(1);
Assert.False(true);
}
catch (Exception e)
{
Assert.Equal(typeof(MissingPrimaryKeyException), e.GetType());
// Never premise English.
//Assert.Equal ("Table doesn't have a primary key.", e.Message);
}
_tbl.PrimaryKey = new DataColumn[] { _tbl.Columns[0] };
Assert.True(Rows.Contains(1));
Assert.True(Rows.Contains(2));
Assert.False(Rows.Contains(4));
try
{
Rows.Contains(new object[] { 64, "test0" });
Assert.False(true);
}
catch (Exception e)
{
Assert.Equal(typeof(ArgumentException), e.GetType());
// Never premise English.
//Assert.Equal ("Expecting 1 value(s) for the key being indexed, but received 2 value(s).", e.Message);
}
_tbl.PrimaryKey = new DataColumn[] { _tbl.Columns[0], _tbl.Columns[1] };
Assert.False(Rows.Contains(new object[] { 64, "test0" }));
Assert.False(Rows.Contains(new object[] { 0, "test1" }));
Assert.True(Rows.Contains(new object[] { 1, "test1" }));
Assert.True(Rows.Contains(new object[] { 2, "test2" }));
try
{
Rows.Contains(new object[] { 2 });
Assert.False(true);
}
catch (Exception e)
{
Assert.Equal(typeof(ArgumentException), e.GetType());
// Never premise English.
//Assert.Equal ("Expecting 2 value(s) for the key being indexed, but received 1 value(s).", e.Message);
}
}
[Fact]
public void CopyTo()
{
_tbl.Columns.Add();
_tbl.Columns.Add();
_tbl.Columns.Add();
DataRowCollection Rows = _tbl.Rows;
Rows.Add(new object[] { "1", "1", "1" });
Rows.Add(new object[] { "2", "2", "2" });
Rows.Add(new object[] { "3", "3", "3" });
Rows.Add(new object[] { "4", "4", "4" });
Rows.Add(new object[] { "5", "5", "5" });
Rows.Add(new object[] { "6", "6", "6" });
Rows.Add(new object[] { "7", "7", "7" });
DataRow[] dr = new DataRow[10];
try
{
Rows.CopyTo(dr, 4);
Assert.False(true);
}
catch (Exception e)
{
Assert.Equal(typeof(ArgumentException), e.GetType());
//Assert.Equal ("Destination array was not long enough. Check destIndex and length, and the array's lower bounds.", e.Message);
}
dr = new DataRow[11];
Rows.CopyTo(dr, 4);
Assert.Null(dr[0]);
Assert.Null(dr[1]);
Assert.Null(dr[2]);
Assert.Null(dr[3]);
Assert.Equal("1", dr[4][0]);
Assert.Equal("2", dr[5][0]);
Assert.Equal("3", dr[6][0]);
Assert.Equal("4", dr[7][0]);
Assert.Equal("5", dr[8][0]);
Assert.Equal("6", dr[9][0]);
}
[Fact]
public void Equals()
{
_tbl.Columns.Add();
_tbl.Columns.Add();
_tbl.Columns.Add();
DataRowCollection Rows1 = _tbl.Rows;
Rows1.Add(new object[] { "1", "1", "1" });
Rows1.Add(new object[] { "2", "2", "2" });
Rows1.Add(new object[] { "3", "3", "3" });
Rows1.Add(new object[] { "4", "4", "4" });
Rows1.Add(new object[] { "5", "5", "5" });
Rows1.Add(new object[] { "6", "6", "6" });
Rows1.Add(new object[] { "7", "7", "7" });
DataRowCollection Rows2 = _tbl.Rows;
Assert.True(Rows2.Equals(Rows1));
Assert.True(Rows1.Equals(Rows2));
Assert.True(Rows1.Equals(Rows1));
DataTable Table = new DataTable();
Table.Columns.Add();
Table.Columns.Add();
Table.Columns.Add();
DataRowCollection Rows3 = Table.Rows;
Rows3.Add(new object[] { "1", "1", "1" });
Rows3.Add(new object[] { "2", "2", "2" });
Rows3.Add(new object[] { "3", "3", "3" });
Rows3.Add(new object[] { "4", "4", "4" });
Rows3.Add(new object[] { "5", "5", "5" });
Rows3.Add(new object[] { "6", "6", "6" });
Rows3.Add(new object[] { "7", "7", "7" });
Assert.False(Rows3.Equals(Rows1));
Assert.False(Rows3.Equals(Rows2));
Assert.False(Rows1.Equals(Rows3));
Assert.False(Rows2.Equals(Rows3));
}
[Fact]
public void Find()
{
DataColumn Col = new DataColumn("test_1");
Col.AllowDBNull = false;
Col.Unique = true;
Col.DataType = typeof(long);
_tbl.Columns.Add(Col);
Col = new DataColumn("test_2");
Col.DataType = typeof(string);
_tbl.Columns.Add(Col);
DataRowCollection Rows = _tbl.Rows;
Rows.Add(new object[] { 1, "first" });
Rows.Add(new object[] { 2, "second" });
Rows.Add(new object[] { 3, "third" });
Rows.Add(new object[] { 4, "fourth" });
Rows.Add(new object[] { 5, "fifth" });
try
{
Rows.Find(1);
Assert.False(true);
}
catch (Exception e)
{
Assert.Equal(typeof(MissingPrimaryKeyException), e.GetType());
// Never premise English.
//Assert.Equal ("Table doesn't have a primary key.", e.Message);
}
_tbl.PrimaryKey = new DataColumn[] { _tbl.Columns[0] };
DataRow row = Rows.Find(1);
Assert.Equal(1L, row[0]);
row = Rows.Find(2);
Assert.Equal(2L, row[0]);
row = Rows.Find("2");
Assert.Equal(2L, row[0]);
try
{
row = Rows.Find("test");
Assert.False(true);
}
catch (Exception e)
{
Assert.Equal(typeof(FormatException), e.GetType());
//Assert.Equal ("Input string was not in a correct format.", e.Message);
}
string tes = null;
row = Rows.Find(tes);
Assert.Null(row);
_tbl.PrimaryKey = null;
try
{
Rows.Find(new object[] { 1, "fir" });
Assert.False(true);
}
catch (Exception e)
{
Assert.Equal(typeof(MissingPrimaryKeyException), e.GetType());
// Never premise English.
//Assert.Equal ("Table doesn't have a primary key.", e.Message);
}
_tbl.PrimaryKey = new DataColumn[] { _tbl.Columns[0], _tbl.Columns[1] };
try
{
Rows.Find(1);
Assert.False(true);
}
catch (Exception e)
{
Assert.Equal(typeof(ArgumentException), e.GetType());
// Never premise English.
//Assert.Equal ("Expecting 2 value(s) for the key being indexed, but received 1 value(s).", e.Message);
}
row = Rows.Find(new object[] { 1, "fir" });
Assert.Null(row);
row = Rows.Find(new object[] { 1, "first" });
Assert.Equal(1L, row[0]);
}
[Fact]
public void Find2()
{
DataSet ds = new DataSet();
ds.EnforceConstraints = false;
DataTable dt = new DataTable();
ds.Tables.Add(dt);
DataColumn dc = new DataColumn("Column A");
dt.Columns.Add(dc);
dt.PrimaryKey = new DataColumn[] { dc };
DataRow dr = dt.NewRow();
dr[0] = "a";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr[0] = "b";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr[0] = "c";
dt.Rows.Add(dr);
DataRow row = ds.Tables[0].Rows.Find(new object[] { "a" });
Assert.NotNull(row);
}
[Fact]
public void InsertAt()
{
_tbl.Columns.Add();
_tbl.Columns.Add();
_tbl.Columns.Add();
DataRowCollection Rows = _tbl.Rows;
Rows.Add(new object[] { "a", "aa", "aaa" });
Rows.Add(new object[] { "b", "bb", "bbb" });
Rows.Add(new object[] { "c", "cc", "ccc" });
Rows.Add(new object[] { "d", "dd", "ddd" });
DataRow Row = _tbl.NewRow();
Row[0] = "e";
Row[1] = "ee";
Row[2] = "eee";
try
{
Rows.InsertAt(Row, -1);
Assert.False(true);
}
catch (Exception e)
{
Assert.Equal(typeof(IndexOutOfRangeException), e.GetType());
// Never premise English.
//Assert.Equal ("The row insert position -1 is invalid.", e.Message);
}
Rows.InsertAt(Row, 0);
Assert.Equal("e", Rows[0][0]);
Assert.Equal("a", Rows[1][0]);
Row = _tbl.NewRow();
Row[0] = "f";
Row[1] = "ff";
Row[2] = "fff";
Rows.InsertAt(Row, 5);
Assert.Equal("f", Rows[5][0]);
Row = _tbl.NewRow();
Row[0] = "g";
Row[1] = "gg";
Row[2] = "ggg";
Rows.InsertAt(Row, 500);
Assert.Equal("g", Rows[6][0]);
try
{
Rows.InsertAt(Row, 6); //Row already belongs to the table
Assert.False(true);
}
catch (Exception e)
{
Assert.Equal(typeof(ArgumentException), e.GetType());
// Never premise English.
//Assert.Equal ("This row already belongs to this table.", e.Message);
}
DataTable table = new DataTable();
DataColumn col = new DataColumn("Name");
table.Columns.Add(col);
Row = table.NewRow();
Row["Name"] = "Abc";
table.Rows.Add(Row);
try
{
Rows.InsertAt(Row, 6);
Assert.False(true);
}
catch (Exception e)
{
Assert.Equal(typeof(ArgumentException), e.GetType());
// Never premise English.
//Assert.Equal ("This row already belongs to another table.", e.Message);
}
table = new DataTable();
col = new DataColumn("Name");
col.DataType = typeof(string);
table.Columns.Add(col);
UniqueConstraint uk = new UniqueConstraint(col);
table.Constraints.Add(uk);
Row = table.NewRow();
Row["Name"] = "aaa";
table.Rows.InsertAt(Row, 0);
Row = table.NewRow();
Row["Name"] = "aaa";
try
{
table.Rows.InsertAt(Row, 1);
Assert.False(true);
}
catch (Exception e)
{
Assert.Equal(typeof(ConstraintException), e.GetType());
}
try
{
table.Rows.InsertAt(null, 1);
}
catch (Exception e)
{
Assert.Equal(typeof(ArgumentNullException), e.GetType());
}
}
[Fact]
public void Remove()
{
_tbl.Columns.Add();
_tbl.Columns.Add();
_tbl.Columns.Add();
DataRowCollection Rows = _tbl.Rows;
Rows.Add(new object[] { "a", "aa", "aaa" });
Rows.Add(new object[] { "b", "bb", "bbb" });
Rows.Add(new object[] { "c", "cc", "ccc" });
Rows.Add(new object[] { "d", "dd", "ddd" });
Assert.Equal(4, _tbl.Rows.Count);
Rows.Remove(_tbl.Rows[1]);
Assert.Equal(3, _tbl.Rows.Count);
Assert.Equal("a", _tbl.Rows[0][0]);
Assert.Equal("c", _tbl.Rows[1][0]);
Assert.Equal("d", _tbl.Rows[2][0]);
try
{
Rows.Remove(null);
Assert.False(true);
}
catch (Exception e)
{
Assert.Equal(typeof(IndexOutOfRangeException), e.GetType());
// Never premise English.
//Assert.Equal ("The given datarow is not in the current DataRowCollection.", e.Message);
}
DataRow Row = new DataTable().NewRow();
try
{
Rows.Remove(Row);
Assert.False(true);
}
catch (Exception e)
{
Assert.Equal(typeof(IndexOutOfRangeException), e.GetType());
// Never premise English.
//Assert.Equal ("The given datarow is not in the current DataRowCollection.", e.Message);
}
try
{
Rows.RemoveAt(-1);
Assert.False(true);
}
catch (Exception e)
{
Assert.Equal(typeof(IndexOutOfRangeException), e.GetType());
// Never premise English.
//Assert.Equal ("There is no row at position -1.", e.Message);
}
try
{
Rows.RemoveAt(64);
Assert.False(true);
}
catch (Exception e)
{
Assert.Equal(typeof(IndexOutOfRangeException), e.GetType());
// Never premise English.
//Assert.Equal ("There is no row at position 64.", e.Message);
}
Rows.RemoveAt(0);
Rows.RemoveAt(1);
Assert.Equal(1, Rows.Count);
Assert.Equal("c", Rows[0][0]);
}
[Fact]
public void IndexOf()
{
DataSet ds = new DataSet();
DataTable dt = new DataTable();
ds.Tables.Add(dt);
DataColumn dc = new DataColumn("Column A");
dt.Columns.Add(dc);
dt.PrimaryKey = new DataColumn[] { dc };
DataRow dr1 = dt.NewRow();
dr1[0] = "a";
dt.Rows.Add(dr1);
DataRow dr2 = dt.NewRow();
dr2[0] = "b";
dt.Rows.Add(dr2);
DataRow dr3 = dt.NewRow();
dr3[0] = "c";
dt.Rows.Add(dr3);
DataRow dr4 = dt.NewRow();
dr4[0] = "d";
dt.Rows.Add(dr4);
DataRow dr5 = dt.NewRow();
dr5[0] = "e";
int index = ds.Tables[0].Rows.IndexOf(dr3);
Assert.Equal(2, index);
index = ds.Tables[0].Rows.IndexOf(dr5);
Assert.Equal(-1, index);
}
[Fact]
public void IndexOfTest()
{
DataTable dt = new DataTable("TestWriteXmlSchema");
dt.Columns.Add("Col1", typeof(int));
dt.Columns.Add("Col2", typeof(int));
DataRow dr = dt.NewRow();
dr[0] = 10;
dr[1] = 20;
dt.Rows.Add(dr);
DataRow dr1 = dt.NewRow();
dr1[0] = 10;
dr1[1] = 20;
dt.Rows.Add(dr1);
DataRow dr2 = dt.NewRow();
dr2[0] = 10;
dr2[1] = 20;
dt.Rows.Add(dr2);
Assert.Equal(1, dt.Rows.IndexOf(dr1));
DataTable dt1 = new DataTable("HelloWorld");
dt1.Columns.Add("T1", typeof(int));
dt1.Columns.Add("T2", typeof(int));
DataRow dr3 = dt1.NewRow();
dr3[0] = 10;
dr3[1] = 20;
dt1.Rows.Add(dr3);
Assert.Equal(-1, dt.Rows.IndexOf(dr3));
Assert.Equal(-1, dt.Rows.IndexOf(null));
}
[Fact]
public void Find_DoesntThrowWithNullObjectInArray()
{
var dt = new DataTable("datatable");
var column = new DataColumn();
dt.Columns.Add(column);
var columns = new DataColumn[] { column };
dt.PrimaryKey = columns;
try
{
Assert.Null(dt.Rows.Find(new object[] { null }));
}
catch (IndexOutOfRangeException)
{
Assert.False(true);
}
}
[Fact]
public void Find_DoesntThrowWithNullObject()
{
var dt = new DataTable("datatable");
var column = new DataColumn();
dt.Columns.Add(column);
var columns = new DataColumn[] { column };
dt.PrimaryKey = columns;
try
{
Assert.Null(dt.Rows.Find((object)null));
}
catch (IndexOutOfRangeException)
{
Assert.False(true);
}
}
}
}
| |
/*
* 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.IO;
using System.Net;
using System.Reflection;
using log4net;
using log4net.Config;
using Nini.Config;
using OpenSim.Framework;
using OpenSim.Framework.Console;
namespace OpenSim
{
/// <summary>
/// Starting class for the OpenSimulator Region
/// </summary>
public class Application
{
/// <summary>
/// Text Console Logger
/// </summary>
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
/// <summary>
/// Path to the main ini Configuration file
/// </summary>
public static string iniFilePath = "";
/// <summary>
/// Save Crashes in the bin/crashes folder. Configurable with m_crashDir
/// </summary>
public static bool m_saveCrashDumps = false;
/// <summary>
/// Directory to save crash reports to. Relative to bin/
/// </summary>
public static string m_crashDir = "crashes";
/// <summary>
/// Instance of the OpenSim class. This could be OpenSim or OpenSimBackground depending on the configuration
/// </summary>
protected static OpenSimBase m_sim = null;
//could move our main function into OpenSimMain and kill this class
public static void Main(string[] args)
{
// First line, hook the appdomain to the crash reporter
AppDomain.CurrentDomain.UnhandledException +=
new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
ServicePointManager.DefaultConnectionLimit = 12;
// Add the arguments supplied when running the application to the configuration
ArgvConfigSource configSource = new ArgvConfigSource(args);
// Configure Log4Net
configSource.AddSwitch("Startup", "logconfig");
string logConfigFile = configSource.Configs["Startup"].GetString("logconfig", String.Empty);
if (logConfigFile != String.Empty)
{
XmlConfigurator.Configure(new System.IO.FileInfo(logConfigFile));
m_log.InfoFormat("[OPENSIM MAIN]: configured log4net using \"{0}\" as configuration file",
logConfigFile);
}
else
{
XmlConfigurator.Configure();
m_log.Info("[OPENSIM MAIN]: configured log4net using default OpenSim.exe.config");
}
m_log.InfoFormat(
"[OPENSIM MAIN]: System Locale is {0}", System.Threading.Thread.CurrentThread.CurrentCulture);
string monoThreadsPerCpu = System.Environment.GetEnvironmentVariable("MONO_THREADS_PER_CPU");
m_log.InfoFormat(
"[OPENSIM MAIN]: Environment variable MONO_THREADS_PER_CPU is {0}", monoThreadsPerCpu ?? "unset");
// Verify the Threadpool allocates or uses enough worker and IO completion threads
// .NET 2.0, workerthreads default to 50 * numcores
// .NET 3.0, workerthreads defaults to 250 * numcores
// .NET 4.0, workerthreads are dynamic based on bitness and OS resources
// Max IO Completion threads are 1000 on all 3 CLRs
//
// Mono 2.10.9 to at least Mono 3.1, workerthreads default to 100 * numcores, iocp threads to 4 * numcores
int workerThreadsMin = 500;
int workerThreadsMax = 1000; // may need further adjustment to match other CLR
int iocpThreadsMin = 1000;
int iocpThreadsMax = 2000; // may need further adjustment to match other CLR
{
int currentMinWorkerThreads, currentMinIocpThreads;
System.Threading.ThreadPool.GetMinThreads(out currentMinWorkerThreads, out currentMinIocpThreads);
m_log.InfoFormat(
"[OPENSIM MAIN]: Runtime gave us {0} min worker threads and {1} min IOCP threads",
currentMinWorkerThreads, currentMinIocpThreads);
}
int workerThreads, iocpThreads;
System.Threading.ThreadPool.GetMaxThreads(out workerThreads, out iocpThreads);
m_log.InfoFormat("[OPENSIM MAIN]: Runtime gave us {0} max worker threads and {1} max IOCP threads", workerThreads, iocpThreads);
if (workerThreads < workerThreadsMin)
{
workerThreads = workerThreadsMin;
m_log.InfoFormat("[OPENSIM MAIN]: Bumping up to max worker threads to {0}",workerThreads);
}
if (workerThreads > workerThreadsMax)
{
workerThreads = workerThreadsMax;
m_log.InfoFormat("[OPENSIM MAIN]: Limiting max worker threads to {0}",workerThreads);
}
// Increase the number of IOCP threads available.
// Mono defaults to a tragically low number (24 on 6-core / 8GB Fedora 17)
if (iocpThreads < iocpThreadsMin)
{
iocpThreads = iocpThreadsMin;
m_log.InfoFormat("[OPENSIM MAIN]: Bumping up max IOCP threads to {0}",iocpThreads);
}
// Make sure we don't overallocate IOCP threads and thrash system resources
if ( iocpThreads > iocpThreadsMax )
{
iocpThreads = iocpThreadsMax;
m_log.InfoFormat("[OPENSIM MAIN]: Limiting max IOCP completion threads to {0}",iocpThreads);
}
// set the resulting worker and IO completion thread counts back to ThreadPool
if ( System.Threading.ThreadPool.SetMaxThreads(workerThreads, iocpThreads) )
{
m_log.InfoFormat(
"[OPENSIM MAIN]: Threadpool set to {0} max worker threads and {1} max IOCP threads",
workerThreads, iocpThreads);
}
else
{
m_log.Warn("[OPENSIM MAIN]: Threadpool reconfiguration failed, runtime defaults still in effect.");
}
// Check if the system is compatible with OpenSimulator.
// Ensures that the minimum system requirements are met
string supported = String.Empty;
if (Util.IsEnvironmentSupported(ref supported))
{
m_log.Info("[OPENSIM MAIN]: Environment is supported by OpenSimulator.");
}
else
{
m_log.Warn("[OPENSIM MAIN]: Environment is not supported by OpenSimulator (" + supported + ")\n");
}
// Configure nIni aliases and localles
Culture.SetCurrentCulture();
// Validate that the user has the most basic configuration done
// If not, offer to do the most basic configuration for them warning them along the way of the importance of
// reading these files.
/*
m_log.Info("Checking for reguired configuration...\n");
bool OpenSim_Ini = (File.Exists(Path.Combine(Util.configDir(), "OpenSim.ini")))
|| (File.Exists(Path.Combine(Util.configDir(), "opensim.ini")))
|| (File.Exists(Path.Combine(Util.configDir(), "openSim.ini")))
|| (File.Exists(Path.Combine(Util.configDir(), "Opensim.ini")));
bool StanaloneCommon_ProperCased = File.Exists(Path.Combine(Path.Combine(Util.configDir(), "config-include"), "StandaloneCommon.ini"));
bool StanaloneCommon_lowercased = File.Exists(Path.Combine(Path.Combine(Util.configDir(), "config-include"), "standalonecommon.ini"));
bool GridCommon_ProperCased = File.Exists(Path.Combine(Path.Combine(Util.configDir(), "config-include"), "GridCommon.ini"));
bool GridCommon_lowerCased = File.Exists(Path.Combine(Path.Combine(Util.configDir(), "config-include"), "gridcommon.ini"));
if ((OpenSim_Ini)
&& (
(StanaloneCommon_ProperCased
|| StanaloneCommon_lowercased
|| GridCommon_ProperCased
|| GridCommon_lowerCased
)))
{
m_log.Info("Required Configuration Files Found\n");
}
else
{
MainConsole.Instance = new LocalConsole("Region");
string resp = MainConsole.Instance.CmdPrompt(
"\n\n*************Required Configuration files not found.*************\n\n OpenSimulator will not run without these files.\n\nRemember, these file names are Case Sensitive in Linux and Proper Cased.\n1. ./OpenSim.ini\nand\n2. ./config-include/StandaloneCommon.ini \nor\n3. ./config-include/GridCommon.ini\n\nAlso, you will want to examine these files in great detail because only the basic system will load by default. OpenSimulator can do a LOT more if you spend a little time going through these files.\n\n" + ": " + "Do you want to copy the most basic Defaults from standalone?",
"yes");
if (resp == "yes")
{
if (!(OpenSim_Ini))
{
try
{
File.Copy(Path.Combine(Util.configDir(), "OpenSim.ini.example"),
Path.Combine(Util.configDir(), "OpenSim.ini"));
} catch (UnauthorizedAccessException)
{
MainConsole.Instance.Output("Unable to Copy OpenSim.ini.example to OpenSim.ini, Make sure OpenSim has have the required permissions\n");
} catch (ArgumentException)
{
MainConsole.Instance.Output("Unable to Copy OpenSim.ini.example to OpenSim.ini, The current directory is invalid.\n");
} catch (System.IO.PathTooLongException)
{
MainConsole.Instance.Output("Unable to Copy OpenSim.ini.example to OpenSim.ini, the Path to these files is too long.\n");
} catch (System.IO.DirectoryNotFoundException)
{
MainConsole.Instance.Output("Unable to Copy OpenSim.ini.example to OpenSim.ini, the current directory is reporting as not found.\n");
} catch (System.IO.FileNotFoundException)
{
MainConsole.Instance.Output("Unable to Copy OpenSim.ini.example to OpenSim.ini, the example is not found, please make sure that the example files exist.\n");
} catch (System.IO.IOException)
{
// Destination file exists already or a hard drive failure... .. so we can just drop this one
//MainConsole.Instance.Output("Unable to Copy OpenSim.ini.example to OpenSim.ini, the example is not found, please make sure that the example files exist.\n");
} catch (System.NotSupportedException)
{
MainConsole.Instance.Output("Unable to Copy OpenSim.ini.example to OpenSim.ini, The current directory is invalid.\n");
}
}
if (!(StanaloneCommon_ProperCased || StanaloneCommon_lowercased))
{
try
{
File.Copy(Path.Combine(Path.Combine(Util.configDir(), "config-include"), "StandaloneCommon.ini.example"),
Path.Combine(Path.Combine(Util.configDir(), "config-include"), "StandaloneCommon.ini"));
}
catch (UnauthorizedAccessException)
{
MainConsole.Instance.Output("Unable to Copy StandaloneCommon.ini.example to StandaloneCommon.ini, Make sure OpenSim has the required permissions\n");
}
catch (ArgumentException)
{
MainConsole.Instance.Output("Unable to Copy StandaloneCommon.ini.example to StandaloneCommon.ini, The current directory is invalid.\n");
}
catch (System.IO.PathTooLongException)
{
MainConsole.Instance.Output("Unable to Copy StandaloneCommon.ini.example to StandaloneCommon.ini, the Path to these files is too long.\n");
}
catch (System.IO.DirectoryNotFoundException)
{
MainConsole.Instance.Output("Unable to Copy StandaloneCommon.ini.example to StandaloneCommon.ini, the current directory is reporting as not found.\n");
}
catch (System.IO.FileNotFoundException)
{
MainConsole.Instance.Output("Unable to Copy StandaloneCommon.ini.example to StandaloneCommon.ini, the example is not found, please make sure that the example files exist.\n");
}
catch (System.IO.IOException)
{
// Destination file exists already or a hard drive failure... .. so we can just drop this one
//MainConsole.Instance.Output("Unable to Copy OpenSim.ini.example to OpenSim.ini, the example is not found, please make sure that the example files exist.\n");
}
catch (System.NotSupportedException)
{
MainConsole.Instance.Output("Unable to Copy StandaloneCommon.ini.example to StandaloneCommon.ini, The current directory is invalid.\n");
}
}
}
MainConsole.Instance = null;
}
*/
configSource.Alias.AddAlias("On", true);
configSource.Alias.AddAlias("Off", false);
configSource.Alias.AddAlias("True", true);
configSource.Alias.AddAlias("False", false);
configSource.Alias.AddAlias("Yes", true);
configSource.Alias.AddAlias("No", false);
configSource.AddSwitch("Startup", "background");
configSource.AddSwitch("Startup", "inifile");
configSource.AddSwitch("Startup", "inimaster");
configSource.AddSwitch("Startup", "inidirectory");
configSource.AddSwitch("Startup", "physics");
configSource.AddSwitch("Startup", "gui");
configSource.AddSwitch("Startup", "console");
configSource.AddSwitch("Startup", "save_crashes");
configSource.AddSwitch("Startup", "crash_dir");
configSource.AddConfig("StandAlone");
configSource.AddConfig("Network");
// Check if we're running in the background or not
bool background = configSource.Configs["Startup"].GetBoolean("background", false);
// Check if we're saving crashes
m_saveCrashDumps = configSource.Configs["Startup"].GetBoolean("save_crashes", false);
// load Crash directory config
m_crashDir = configSource.Configs["Startup"].GetString("crash_dir", m_crashDir);
if (background)
{
m_sim = new OpenSimBackground(configSource);
m_sim.Startup();
}
else
{
m_sim = new OpenSim(configSource);
m_sim.Startup();
while (true)
{
try
{
// Block thread here for input
MainConsole.Instance.Prompt();
}
catch (Exception e)
{
m_log.ErrorFormat("Command error: {0}", e);
}
}
}
}
private static bool _IsHandlingException = false; // Make sure we don't go recursive on ourself
/// <summary>
/// Global exception handler -- all unhandlet exceptions end up here :)
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
if (_IsHandlingException)
{
return;
}
_IsHandlingException = true;
// TODO: Add config option to allow users to turn off error reporting
// TODO: Post error report (disabled for now)
string msg = String.Empty;
msg += "\r\n";
msg += "APPLICATION EXCEPTION DETECTED: " + e.ToString() + "\r\n";
msg += "\r\n";
msg += "Exception: " + e.ExceptionObject.ToString() + "\r\n";
Exception ex = (Exception) e.ExceptionObject;
if (ex.InnerException != null)
{
msg += "InnerException: " + ex.InnerException.ToString() + "\r\n";
}
msg += "\r\n";
msg += "Application is terminating: " + e.IsTerminating.ToString() + "\r\n";
m_log.ErrorFormat("[APPLICATION]: {0}", msg);
if (m_saveCrashDumps)
{
// Log exception to disk
try
{
if (!Directory.Exists(m_crashDir))
{
Directory.CreateDirectory(m_crashDir);
}
string log = Util.GetUniqueFilename(ex.GetType() + ".txt");
using (StreamWriter m_crashLog = new StreamWriter(Path.Combine(m_crashDir, log)))
{
m_crashLog.WriteLine(msg);
}
File.Copy("OpenSim.ini", Path.Combine(m_crashDir, log + "_OpenSim.ini"), true);
}
catch (Exception e2)
{
m_log.ErrorFormat("[CRASH LOGGER CRASHED]: {0}", e2);
}
}
_IsHandlingException = false;
}
}
}
| |
/*
* Copyright (c) 2005 Poderosa Project, All Rights Reserved.
* $Id: SocketWithTimeout.cs,v 1.2 2005/04/20 08:45:46 okajima Exp $
*/
using System;
using System.Collections.Specialized;
using System.Diagnostics;
using System.Threading;
using System.Net;
using System.Net.Sockets;
using Poderosa.Connection;
namespace Poderosa.Communication
{
public interface ISocketWithTimeoutClient
{
void SuccessfullyExit(object result);
void ConnectionFailed(string message);
void CancelTimer();
System.Windows.Forms.IWin32Window GetWindow();
}
/// <summary>
/// SocketWithTimeout
/// </summary>
public abstract class SocketWithTimeout
{
public void AsyncConnect(ISocketWithTimeoutClient client, string host, int port)
{
_async = true;
_client = client;
_event = null;
_host = host;
_port = port;
_socks = null;
UI.UILibUtil.CreateThread(new ThreadStart(this.Run)).Start();
}
public void AsyncConnect(ISocketWithTimeoutClient client, string host, int port, Action<ConnectionTag, string> connectResultProcess)
{
_async = true;
_client = client;
_event = null;
_host = host;
_port = port;
_socks = null;
_connectResultProcess = connectResultProcess;
UI.UILibUtil.CreateThread(new ThreadStart(this.Run)).Start();
}
public void AsyncConnect(ISocketWithTimeoutClient client, Socks socks)
{
_async = true;
_client = client;
_event = null;
_socks = socks;
UI.UILibUtil.CreateThread(new ThreadStart(this.Run)).Start();
}
private void ExitProcess()
{
if (!_interrupted)
{
if (_succeeded)
{
_client.SuccessfullyExit(this.Result);
if (_connectResultProcess != null)
{
_connectResultProcess.Invoke((ConnectionTag)this.Result, null);
}
}
else
{
_client.ConnectionFailed(_errorMessage);
if (_connectResultProcess != null)
{
_connectResultProcess.Invoke(null, _errorMessage);
}
}
}
}
protected void SetIgnoreTimeout()
{
_ignoreTimeout = true;
_client.CancelTimer();
}
public void Interrupt()
{
_interrupted = true;
if (!_async)
_event.Set();
if (_tcpConnected)
_socket.Close();
}
protected Socks _socks;
protected ISocketWithTimeoutClient _client;
protected IPAddressSet _addressSet;
protected IPAddress _connectedAddress;
protected AutoResetEvent _event;
protected Socket _socket;
protected string _host;
protected int _port;
protected Action<ConnectionTag, string> _connectResultProcess;
protected bool _async;
protected bool _succeeded;
protected bool _interrupted;
protected bool _ignoreTimeout;
protected bool _tcpConnected;
protected string _errorMessage;
private void Run()
{
_tcpConnected = false;
_ignoreTimeout = false;
_succeeded = false;
try
{
_addressSet = null;
_errorMessage = null;
MakeConnection();
_errorMessage = null;
Negotiate();
_succeeded = true;
}
catch (Exception ex)
{
if (_errorMessage == null)
_errorMessage = ex.Message;
else
_errorMessage += ex.Message;
}
finally
{
if (_async)
{
ExitProcess();
}
else
{
_event.Set();
_event.Close();
}
if (_tcpConnected && !_interrupted && _errorMessage != null)
{
try
{
_socket.Close();
}
catch (Exception)
{
}
}
}
}
protected virtual void MakeConnection()
{
if (_socks != null)
{
IPAddressSet a = null;
try
{
a = new IPAddressSet(IPAddress.Parse(_socks.DestName));
}
catch (FormatException)
{
try
{
a = new IPAddressSet(_socks.DestName);
}
catch (Exception)
{
}
}
if (a != null && !SocksApplicapable(_socks.ExcludingNetworks, a))
{
_addressSet = a;
_host = _socks.DestName;
_port = _socks.DestPort;
_socks = null;
}
}
string dest = _socks == null ? _host : _socks.ServerName;
int port = _socks == null ? _port : _socks.ServerPort;
string msg = _socks == null ? GetHostDescription() : "SOCKS Server";
if (_addressSet == null)
{
try
{
_addressSet = new IPAddressSet(IPAddress.Parse(dest));
}
catch (FormatException)
{
_errorMessage = String.Format("The {0} {1} was not found.", msg, dest);
_addressSet = new IPAddressSet(dest);
}
}
_errorMessage = String.Format("Failed to connect {0} {1}. Please check the address and the port.", msg, dest);
_socket = NetUtil.ConnectTCPSocket(_addressSet, port);
_connectedAddress = ((IPEndPoint)_socket.RemoteEndPoint).Address;
if (_socks != null)
{
_errorMessage = "An error occurred while SOCKS negotiation.";
_socks.Connect(_socket);
_host = _socks.DestName;
_port = _socks.DestPort;
}
_tcpConnected = true;
}
protected abstract void Negotiate();
protected virtual string GetHostDescription()
{
return "";
}
protected abstract object Result
{
get;
}
public Socks Socks
{
get
{
return _socks;
}
set
{
_socks = value;
}
}
public bool Succeeded
{
get
{
return _succeeded;
}
}
public bool Interrupted
{
get
{
return _interrupted;
}
}
public string ErrorMessage
{
get
{
return _errorMessage;
}
}
public IPAddress IPAddress
{
get
{
return _connectedAddress;
}
}
private static bool SocksApplicapable(string nss, IPAddressSet address)
{
foreach (string netaddress in nss.Split(';'))
{
if (netaddress.Length == 0) continue;
if (!NetUtil.IsNetworkAddress(netaddress))
{
throw new FormatException(String.Format("{0} is not suitable as a network address.", netaddress));
}
if (NetUtil.NetAddressIncludesIPAddress(netaddress, address.Primary))
return false;
else if (address.Secondary != null && NetUtil.NetAddressIncludesIPAddress(netaddress, address.Secondary))
return false;
}
return true;
}
}
}
| |
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Globalization;
using System.Linq;
using System.Text;
namespace EduHub.Data.Entities
{
/// <summary>
/// General Ledger Programs Data Set
/// </summary>
[GeneratedCode("EduHub Data", "0.9")]
public sealed partial class KGLPROGDataSet : EduHubDataSet<KGLPROG>
{
/// <inheritdoc />
public override string Name { get { return "KGLPROG"; } }
/// <inheritdoc />
public override bool SupportsEntityLastModified { get { return true; } }
internal KGLPROGDataSet(EduHubContext Context)
: base(Context)
{
Index_GLPROGRAM = new Lazy<Dictionary<string, KGLPROG>>(() => this.ToDictionary(i => i.GLPROGRAM));
}
/// <summary>
/// Matches CSV file headers to actions, used to deserialize <see cref="KGLPROG" />
/// </summary>
/// <param name="Headers">The CSV column headers</param>
/// <returns>An array of actions which deserialize <see cref="KGLPROG" /> fields for each CSV column header</returns>
internal override Action<KGLPROG, string>[] BuildMapper(IReadOnlyList<string> Headers)
{
var mapper = new Action<KGLPROG, string>[Headers.Count];
for (var i = 0; i < Headers.Count; i++) {
switch (Headers[i]) {
case "GLPROGRAM":
mapper[i] = (e, v) => e.GLPROGRAM = v;
break;
case "TITLE":
mapper[i] = (e, v) => e.TITLE = v;
break;
case "ACTIVE":
mapper[i] = (e, v) => e.ACTIVE = v;
break;
case "LW_DATE":
mapper[i] = (e, v) => e.LW_DATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);
break;
case "LW_TIME":
mapper[i] = (e, v) => e.LW_TIME = v == null ? (short?)null : short.Parse(v);
break;
case "LW_USER":
mapper[i] = (e, v) => e.LW_USER = v;
break;
default:
mapper[i] = MapperNoOp;
break;
}
}
return mapper;
}
/// <summary>
/// Merges <see cref="KGLPROG" /> delta entities
/// </summary>
/// <param name="Entities">Iterator for base <see cref="KGLPROG" /> entities</param>
/// <param name="DeltaEntities">List of delta <see cref="KGLPROG" /> entities</param>
/// <returns>A merged <see cref="IEnumerable{KGLPROG}"/> of entities</returns>
internal override IEnumerable<KGLPROG> ApplyDeltaEntities(IEnumerable<KGLPROG> Entities, List<KGLPROG> DeltaEntities)
{
HashSet<string> Index_GLPROGRAM = new HashSet<string>(DeltaEntities.Select(i => i.GLPROGRAM));
using (var deltaIterator = DeltaEntities.GetEnumerator())
{
using (var entityIterator = Entities.GetEnumerator())
{
while (deltaIterator.MoveNext())
{
var deltaClusteredKey = deltaIterator.Current.GLPROGRAM;
bool yieldEntity = false;
while (entityIterator.MoveNext())
{
var entity = entityIterator.Current;
bool overwritten = Index_GLPROGRAM.Remove(entity.GLPROGRAM);
if (entity.GLPROGRAM.CompareTo(deltaClusteredKey) <= 0)
{
if (!overwritten)
{
yield return entity;
}
}
else
{
yieldEntity = !overwritten;
break;
}
}
yield return deltaIterator.Current;
if (yieldEntity)
{
yield return entityIterator.Current;
}
}
while (entityIterator.MoveNext())
{
yield return entityIterator.Current;
}
}
}
}
#region Index Fields
private Lazy<Dictionary<string, KGLPROG>> Index_GLPROGRAM;
#endregion
#region Index Methods
/// <summary>
/// Find KGLPROG by GLPROGRAM field
/// </summary>
/// <param name="GLPROGRAM">GLPROGRAM value used to find KGLPROG</param>
/// <returns>Related KGLPROG entity</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public KGLPROG FindByGLPROGRAM(string GLPROGRAM)
{
return Index_GLPROGRAM.Value[GLPROGRAM];
}
/// <summary>
/// Attempt to find KGLPROG by GLPROGRAM field
/// </summary>
/// <param name="GLPROGRAM">GLPROGRAM value used to find KGLPROG</param>
/// <param name="Value">Related KGLPROG entity</param>
/// <returns>True if the related KGLPROG entity is found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public bool TryFindByGLPROGRAM(string GLPROGRAM, out KGLPROG Value)
{
return Index_GLPROGRAM.Value.TryGetValue(GLPROGRAM, out Value);
}
/// <summary>
/// Attempt to find KGLPROG by GLPROGRAM field
/// </summary>
/// <param name="GLPROGRAM">GLPROGRAM value used to find KGLPROG</param>
/// <returns>Related KGLPROG entity, or null if not found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public KGLPROG TryFindByGLPROGRAM(string GLPROGRAM)
{
KGLPROG value;
if (Index_GLPROGRAM.Value.TryGetValue(GLPROGRAM, out value))
{
return value;
}
else
{
return null;
}
}
#endregion
#region SQL Integration
/// <summary>
/// Returns a <see cref="SqlCommand"/> which checks for the existence of a KGLPROG table, and if not found, creates the table and associated indexes.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
public override SqlCommand GetSqlCreateTableCommand(SqlConnection SqlConnection)
{
return new SqlCommand(
connection: SqlConnection,
cmdText:
@"IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[KGLPROG]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[KGLPROG](
[GLPROGRAM] varchar(3) NOT NULL,
[TITLE] varchar(30) NULL,
[ACTIVE] varchar(1) NULL,
[LW_DATE] datetime NULL,
[LW_TIME] smallint NULL,
[LW_USER] varchar(128) NULL,
CONSTRAINT [KGLPROG_Index_GLPROGRAM] PRIMARY KEY CLUSTERED (
[GLPROGRAM] ASC
)
);
END");
}
/// <summary>
/// Returns null as <see cref="KGLPROGDataSet"/> has no non-clustered indexes.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <returns>null</returns>
public override SqlCommand GetSqlDisableIndexesCommand(SqlConnection SqlConnection)
{
return null;
}
/// <summary>
/// Returns null as <see cref="KGLPROGDataSet"/> has no non-clustered indexes.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <returns>null</returns>
public override SqlCommand GetSqlRebuildIndexesCommand(SqlConnection SqlConnection)
{
return null;
}
/// <summary>
/// Returns a <see cref="SqlCommand"/> which deletes the <see cref="KGLPROG"/> entities passed
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <param name="Entities">The <see cref="KGLPROG"/> entities to be deleted</param>
public override SqlCommand GetSqlDeleteCommand(SqlConnection SqlConnection, IEnumerable<KGLPROG> Entities)
{
SqlCommand command = new SqlCommand();
int parameterIndex = 0;
StringBuilder builder = new StringBuilder();
List<string> Index_GLPROGRAM = new List<string>();
foreach (var entity in Entities)
{
Index_GLPROGRAM.Add(entity.GLPROGRAM);
}
builder.AppendLine("DELETE [dbo].[KGLPROG] WHERE");
// Index_GLPROGRAM
builder.Append("[GLPROGRAM] IN (");
for (int index = 0; index < Index_GLPROGRAM.Count; index++)
{
if (index != 0)
builder.Append(", ");
// GLPROGRAM
var parameterGLPROGRAM = $"@p{parameterIndex++}";
builder.Append(parameterGLPROGRAM);
command.Parameters.Add(parameterGLPROGRAM, SqlDbType.VarChar, 3).Value = Index_GLPROGRAM[index];
}
builder.Append(");");
command.Connection = SqlConnection;
command.CommandText = builder.ToString();
return command;
}
/// <summary>
/// Provides a <see cref="IDataReader"/> for the KGLPROG data set
/// </summary>
/// <returns>A <see cref="IDataReader"/> for the KGLPROG data set</returns>
public override EduHubDataSetDataReader<KGLPROG> GetDataSetDataReader()
{
return new KGLPROGDataReader(Load());
}
/// <summary>
/// Provides a <see cref="IDataReader"/> for the KGLPROG data set
/// </summary>
/// <returns>A <see cref="IDataReader"/> for the KGLPROG data set</returns>
public override EduHubDataSetDataReader<KGLPROG> GetDataSetDataReader(List<KGLPROG> Entities)
{
return new KGLPROGDataReader(new EduHubDataSetLoadedReader<KGLPROG>(this, Entities));
}
// Modest implementation to primarily support SqlBulkCopy
private class KGLPROGDataReader : EduHubDataSetDataReader<KGLPROG>
{
public KGLPROGDataReader(IEduHubDataSetReader<KGLPROG> Reader)
: base (Reader)
{
}
public override int FieldCount { get { return 6; } }
public override object GetValue(int i)
{
switch (i)
{
case 0: // GLPROGRAM
return Current.GLPROGRAM;
case 1: // TITLE
return Current.TITLE;
case 2: // ACTIVE
return Current.ACTIVE;
case 3: // LW_DATE
return Current.LW_DATE;
case 4: // LW_TIME
return Current.LW_TIME;
case 5: // LW_USER
return Current.LW_USER;
default:
throw new ArgumentOutOfRangeException(nameof(i));
}
}
public override bool IsDBNull(int i)
{
switch (i)
{
case 1: // TITLE
return Current.TITLE == null;
case 2: // ACTIVE
return Current.ACTIVE == null;
case 3: // LW_DATE
return Current.LW_DATE == null;
case 4: // LW_TIME
return Current.LW_TIME == null;
case 5: // LW_USER
return Current.LW_USER == null;
default:
return false;
}
}
public override string GetName(int ordinal)
{
switch (ordinal)
{
case 0: // GLPROGRAM
return "GLPROGRAM";
case 1: // TITLE
return "TITLE";
case 2: // ACTIVE
return "ACTIVE";
case 3: // LW_DATE
return "LW_DATE";
case 4: // LW_TIME
return "LW_TIME";
case 5: // LW_USER
return "LW_USER";
default:
throw new ArgumentOutOfRangeException(nameof(ordinal));
}
}
public override int GetOrdinal(string name)
{
switch (name)
{
case "GLPROGRAM":
return 0;
case "TITLE":
return 1;
case "ACTIVE":
return 2;
case "LW_DATE":
return 3;
case "LW_TIME":
return 4;
case "LW_USER":
return 5;
default:
throw new ArgumentOutOfRangeException(nameof(name));
}
}
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using XplatChat.Service.Endpoint.Areas.HelpPage.ModelDescriptions;
using XplatChat.Service.Endpoint.Areas.HelpPage.Models;
namespace XplatChat.Service.Endpoint.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
if (complexTypeDescription != null)
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture,
"An exception has occurred while generating the sample. Exception message: {0}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
// Copyright (c) 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.Composition;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using Microsoft.CodeAnalysis.Collections;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.FindSymbols;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp
{
[ExportLanguageService(typeof(ISyntaxFactsService), LanguageNames.CSharp), Shared]
internal class CSharpSyntaxFactsService : ISyntaxFactsService
{
public bool IsAwaitKeyword(SyntaxToken token)
{
return token.IsKind(SyntaxKind.AwaitKeyword);
}
public bool IsIdentifier(SyntaxToken token)
{
return token.IsKind(SyntaxKind.IdentifierToken);
}
public bool IsGlobalNamespaceKeyword(SyntaxToken token)
{
return token.IsKind(SyntaxKind.GlobalKeyword);
}
public bool IsVerbatimIdentifier(SyntaxToken token)
{
return token.IsVerbatimIdentifier();
}
public bool IsOperator(SyntaxToken token)
{
var kind = token.Kind();
return
(SyntaxFacts.IsAnyUnaryExpression(kind) &&
(token.Parent is PrefixUnaryExpressionSyntax || token.Parent is PostfixUnaryExpressionSyntax || token.Parent is OperatorDeclarationSyntax)) ||
(SyntaxFacts.IsBinaryExpression(kind) && (token.Parent is BinaryExpressionSyntax || token.Parent is OperatorDeclarationSyntax)) ||
(SyntaxFacts.IsAssignmentExpressionOperatorToken(kind) && token.Parent is AssignmentExpressionSyntax);
}
public bool IsKeyword(SyntaxToken token)
{
var kind = (SyntaxKind)token.RawKind;
return
SyntaxFacts.IsKeywordKind(kind); // both contextual and reserved keywords
}
public bool IsContextualKeyword(SyntaxToken token)
{
var kind = (SyntaxKind)token.RawKind;
return
SyntaxFacts.IsContextualKeyword(kind);
}
public bool IsPreprocessorKeyword(SyntaxToken token)
{
var kind = (SyntaxKind)token.RawKind;
return
SyntaxFacts.IsPreprocessorKeyword(kind);
}
public bool IsHashToken(SyntaxToken token)
{
return (SyntaxKind)token.RawKind == SyntaxKind.HashToken;
}
public bool IsInInactiveRegion(SyntaxTree syntaxTree, int position, CancellationToken cancellationToken)
{
var csharpTree = syntaxTree as SyntaxTree;
if (csharpTree == null)
{
return false;
}
return csharpTree.IsInInactiveRegion(position, cancellationToken);
}
public bool IsInNonUserCode(SyntaxTree syntaxTree, int position, CancellationToken cancellationToken)
{
var csharpTree = syntaxTree as SyntaxTree;
if (csharpTree == null)
{
return false;
}
return csharpTree.IsInNonUserCode(position, cancellationToken);
}
public bool IsEntirelyWithinStringOrCharOrNumericLiteral(SyntaxTree syntaxTree, int position, CancellationToken cancellationToken)
{
var csharpTree = syntaxTree as SyntaxTree;
if (csharpTree == null)
{
return false;
}
return csharpTree.IsEntirelyWithinStringOrCharLiteral(position, cancellationToken);
}
public bool IsDirective(SyntaxNode node)
{
return node is DirectiveTriviaSyntax;
}
public bool TryGetExternalSourceInfo(SyntaxNode node, out ExternalSourceInfo info)
{
var lineDirective = node as LineDirectiveTriviaSyntax;
if (lineDirective != null)
{
if (lineDirective.Line.Kind() == SyntaxKind.DefaultKeyword)
{
info = new ExternalSourceInfo(null, ends: true);
return true;
}
else if (lineDirective.Line.Kind() == SyntaxKind.NumericLiteralToken &&
lineDirective.Line.Value is int)
{
info = new ExternalSourceInfo((int)lineDirective.Line.Value, false);
return true;
}
}
info = default(ExternalSourceInfo);
return false;
}
public bool IsRightSideOfQualifiedName(SyntaxNode node)
{
var name = node as SimpleNameSyntax;
return name.IsRightSideOfQualifiedName();
}
public bool IsMemberAccessExpressionName(SyntaxNode node)
{
var name = node as SimpleNameSyntax;
return name.IsMemberAccessExpressionName();
}
public bool IsObjectCreationExpressionType(SyntaxNode node)
{
return node.IsParentKind(SyntaxKind.ObjectCreationExpression) &&
((ObjectCreationExpressionSyntax)node.Parent).Type == node;
}
public bool IsAttributeName(SyntaxNode node)
{
return SyntaxFacts.IsAttributeName(node);
}
public bool IsInvocationExpression(SyntaxNode node)
{
return node is InvocationExpressionSyntax;
}
public bool IsAnonymousFunction(SyntaxNode node)
{
return node is ParenthesizedLambdaExpressionSyntax ||
node is SimpleLambdaExpressionSyntax ||
node is AnonymousMethodExpressionSyntax;
}
public bool IsGenericName(SyntaxNode node)
{
return node is GenericNameSyntax;
}
public bool IsNamedParameter(SyntaxNode node)
{
return node.CheckParent<NameColonSyntax>(p => p.Name == node);
}
public bool IsSkippedTokensTrivia(SyntaxNode node)
{
return node is SkippedTokensTriviaSyntax;
}
public bool HasIncompleteParentMember(SyntaxNode node)
{
return node.IsParentKind(SyntaxKind.IncompleteMember);
}
public SyntaxToken GetIdentifierOfGenericName(SyntaxNode genericName)
{
var csharpGenericName = genericName as GenericNameSyntax;
return csharpGenericName != null
? csharpGenericName.Identifier
: default(SyntaxToken);
}
public bool IsCaseSensitive
{
get
{
return true;
}
}
public bool IsUsingDirectiveName(SyntaxNode node)
{
return
node.IsParentKind(SyntaxKind.UsingDirective) &&
((UsingDirectiveSyntax)node.Parent).Name == node;
}
public bool IsForEachStatement(SyntaxNode node)
{
return node is ForEachStatementSyntax;
}
public bool IsLockStatement(SyntaxNode node)
{
return node is LockStatementSyntax;
}
public bool IsUsingStatement(SyntaxNode node)
{
return node is UsingStatementSyntax;
}
public bool IsThisConstructorInitializer(SyntaxToken token)
{
return token.Parent.IsKind(SyntaxKind.ThisConstructorInitializer) &&
((ConstructorInitializerSyntax)token.Parent).ThisOrBaseKeyword == token;
}
public bool IsBaseConstructorInitializer(SyntaxToken token)
{
return token.Parent.IsKind(SyntaxKind.BaseConstructorInitializer) &&
((ConstructorInitializerSyntax)token.Parent).ThisOrBaseKeyword == token;
}
public bool IsQueryExpression(SyntaxNode node)
{
return node is QueryExpressionSyntax;
}
public bool IsPredefinedType(SyntaxToken token)
{
PredefinedType actualType;
return TryGetPredefinedType(token, out actualType) && actualType != PredefinedType.None;
}
public bool IsPredefinedType(SyntaxToken token, PredefinedType type)
{
PredefinedType actualType;
return TryGetPredefinedType(token, out actualType) && actualType == type;
}
public bool TryGetPredefinedType(SyntaxToken token, out PredefinedType type)
{
type = GetPredefinedType(token);
return type != PredefinedType.None;
}
private PredefinedType GetPredefinedType(SyntaxToken token)
{
switch ((SyntaxKind)token.RawKind)
{
case SyntaxKind.BoolKeyword:
return PredefinedType.Boolean;
case SyntaxKind.ByteKeyword:
return PredefinedType.Byte;
case SyntaxKind.SByteKeyword:
return PredefinedType.SByte;
case SyntaxKind.IntKeyword:
return PredefinedType.Int32;
case SyntaxKind.UIntKeyword:
return PredefinedType.UInt32;
case SyntaxKind.ShortKeyword:
return PredefinedType.Int16;
case SyntaxKind.UShortKeyword:
return PredefinedType.UInt16;
case SyntaxKind.LongKeyword:
return PredefinedType.Int64;
case SyntaxKind.ULongKeyword:
return PredefinedType.UInt64;
case SyntaxKind.FloatKeyword:
return PredefinedType.Single;
case SyntaxKind.DoubleKeyword:
return PredefinedType.Double;
case SyntaxKind.DecimalKeyword:
return PredefinedType.Decimal;
case SyntaxKind.StringKeyword:
return PredefinedType.String;
case SyntaxKind.CharKeyword:
return PredefinedType.Char;
case SyntaxKind.ObjectKeyword:
return PredefinedType.Object;
case SyntaxKind.VoidKeyword:
return PredefinedType.Void;
default:
return PredefinedType.None;
}
}
public bool IsPredefinedOperator(SyntaxToken token)
{
PredefinedOperator actualOperator;
return TryGetPredefinedOperator(token, out actualOperator) && actualOperator != PredefinedOperator.None;
}
public bool IsPredefinedOperator(SyntaxToken token, PredefinedOperator op)
{
PredefinedOperator actualOperator;
return TryGetPredefinedOperator(token, out actualOperator) && actualOperator == op;
}
public bool TryGetPredefinedOperator(SyntaxToken token, out PredefinedOperator op)
{
op = GetPredefinedOperator(token);
return op != PredefinedOperator.None;
}
private PredefinedOperator GetPredefinedOperator(SyntaxToken token)
{
switch ((SyntaxKind)token.RawKind)
{
case SyntaxKind.PlusToken:
case SyntaxKind.PlusEqualsToken:
return PredefinedOperator.Addition;
case SyntaxKind.MinusToken:
case SyntaxKind.MinusEqualsToken:
return PredefinedOperator.Subtraction;
case SyntaxKind.AmpersandToken:
case SyntaxKind.AmpersandEqualsToken:
return PredefinedOperator.BitwiseAnd;
case SyntaxKind.BarToken:
case SyntaxKind.BarEqualsToken:
return PredefinedOperator.BitwiseOr;
case SyntaxKind.MinusMinusToken:
return PredefinedOperator.Decrement;
case SyntaxKind.PlusPlusToken:
return PredefinedOperator.Increment;
case SyntaxKind.SlashToken:
case SyntaxKind.SlashEqualsToken:
return PredefinedOperator.Division;
case SyntaxKind.EqualsEqualsToken:
return PredefinedOperator.Equality;
case SyntaxKind.CaretToken:
case SyntaxKind.CaretEqualsToken:
return PredefinedOperator.ExclusiveOr;
case SyntaxKind.GreaterThanToken:
return PredefinedOperator.GreaterThan;
case SyntaxKind.GreaterThanEqualsToken:
return PredefinedOperator.GreaterThanOrEqual;
case SyntaxKind.ExclamationEqualsToken:
return PredefinedOperator.Inequality;
case SyntaxKind.LessThanLessThanToken:
case SyntaxKind.LessThanLessThanEqualsToken:
return PredefinedOperator.LeftShift;
case SyntaxKind.LessThanEqualsToken:
return PredefinedOperator.LessThanOrEqual;
case SyntaxKind.AsteriskToken:
case SyntaxKind.AsteriskEqualsToken:
return PredefinedOperator.Multiplication;
case SyntaxKind.PercentToken:
case SyntaxKind.PercentEqualsToken:
return PredefinedOperator.Modulus;
case SyntaxKind.ExclamationToken:
case SyntaxKind.TildeToken:
return PredefinedOperator.Complement;
case SyntaxKind.GreaterThanGreaterThanToken:
case SyntaxKind.GreaterThanGreaterThanEqualsToken:
return PredefinedOperator.RightShift;
}
return PredefinedOperator.None;
}
public string GetText(int kind)
{
return SyntaxFacts.GetText((SyntaxKind)kind);
}
public bool IsIdentifierStartCharacter(char c)
{
return SyntaxFacts.IsIdentifierStartCharacter(c);
}
public bool IsIdentifierPartCharacter(char c)
{
return SyntaxFacts.IsIdentifierPartCharacter(c);
}
public bool IsIdentifierEscapeCharacter(char c)
{
return c == '@';
}
public bool IsValidIdentifier(string identifier)
{
var token = SyntaxFactory.ParseToken(identifier);
return IsIdentifier(token) && !token.ContainsDiagnostics && token.ToString().Length == identifier.Length;
}
public bool IsVerbatimIdentifier(string identifier)
{
var token = SyntaxFactory.ParseToken(identifier);
return IsIdentifier(token) && !token.ContainsDiagnostics && token.ToString().Length == identifier.Length && token.IsVerbatimIdentifier();
}
public bool IsTypeCharacter(char c)
{
return false;
}
public bool IsStartOfUnicodeEscapeSequence(char c)
{
return c == '\\';
}
public bool IsLiteral(SyntaxToken token)
{
switch (token.Kind())
{
case SyntaxKind.NumericLiteralToken:
case SyntaxKind.CharacterLiteralToken:
case SyntaxKind.StringLiteralToken:
case SyntaxKind.NullKeyword:
case SyntaxKind.TrueKeyword:
case SyntaxKind.FalseKeyword:
case SyntaxKind.InterpolatedStringStartToken:
case SyntaxKind.InterpolatedStringEndToken:
case SyntaxKind.InterpolatedVerbatimStringStartToken:
case SyntaxKind.InterpolatedStringTextToken:
return true;
}
return false;
}
public bool IsStringLiteral(SyntaxToken token)
{
return token.IsKind(SyntaxKind.StringLiteralToken, SyntaxKind.InterpolatedStringTextToken);
}
public bool IsTypeNamedVarInVariableOrFieldDeclaration(SyntaxToken token, SyntaxNode parent)
{
var typedToken = token;
var typedParent = parent;
if (typedParent.IsKind(SyntaxKind.IdentifierName))
{
TypeSyntax declaredType = null;
if (typedParent.IsParentKind(SyntaxKind.VariableDeclaration))
{
declaredType = ((VariableDeclarationSyntax)typedParent.Parent).Type;
}
else if (typedParent.IsParentKind(SyntaxKind.FieldDeclaration))
{
declaredType = ((FieldDeclarationSyntax)typedParent.Parent).Declaration.Type;
}
return declaredType == typedParent && typedToken.ValueText == "var";
}
return false;
}
public bool IsTypeNamedDynamic(SyntaxToken token, SyntaxNode parent)
{
var typedParent = parent as ExpressionSyntax;
if (typedParent != null)
{
if (SyntaxFacts.IsInTypeOnlyContext(typedParent) &&
typedParent.IsKind(SyntaxKind.IdentifierName) &&
token.ValueText == "dynamic")
{
return true;
}
}
return false;
}
public bool IsBindableToken(SyntaxToken token)
{
if (this.IsWord(token) || this.IsLiteral(token) || this.IsOperator(token))
{
switch ((SyntaxKind)token.RawKind)
{
case SyntaxKind.DelegateKeyword:
case SyntaxKind.VoidKeyword:
return false;
}
return true;
}
return false;
}
public bool IsMemberAccessExpression(SyntaxNode node)
{
return node is MemberAccessExpressionSyntax &&
((MemberAccessExpressionSyntax)node).Kind() == SyntaxKind.SimpleMemberAccessExpression;
}
public bool IsConditionalMemberAccessExpression(SyntaxNode node)
{
return node is ConditionalAccessExpressionSyntax;
}
public bool IsPointerMemberAccessExpression(SyntaxNode node)
{
return node is MemberAccessExpressionSyntax &&
((MemberAccessExpressionSyntax)node).Kind() == SyntaxKind.PointerMemberAccessExpression;
}
public void GetNameAndArityOfSimpleName(SyntaxNode node, out string name, out int arity)
{
name = null;
arity = 0;
var simpleName = node as SimpleNameSyntax;
if (simpleName != null)
{
name = simpleName.Identifier.ValueText;
arity = simpleName.Arity;
}
}
public SyntaxNode GetExpressionOfMemberAccessExpression(SyntaxNode node)
{
return node.IsKind(SyntaxKind.MemberBindingExpression)
? GetExpressionOfConditionalMemberAccessExpression(node.GetParentConditionalAccessExpression())
: (node as MemberAccessExpressionSyntax)?.Expression;
}
public SyntaxNode GetExpressionOfConditionalMemberAccessExpression(SyntaxNode node)
{
return (node as ConditionalAccessExpressionSyntax)?.Expression;
}
public bool IsInStaticContext(SyntaxNode node)
{
return node.IsInStaticContext();
}
public bool IsInNamespaceOrTypeContext(SyntaxNode node)
{
return SyntaxFacts.IsInNamespaceOrTypeContext(node as ExpressionSyntax);
}
public SyntaxNode GetExpressionOfArgument(SyntaxNode node)
{
return ((ArgumentSyntax)node).Expression;
}
public RefKind GetRefKindOfArgument(SyntaxNode node)
{
return (node as ArgumentSyntax).GetRefKind();
}
public bool IsInConstantContext(SyntaxNode node)
{
return (node as ExpressionSyntax).IsInConstantContext();
}
public bool IsInConstructor(SyntaxNode node)
{
return node.GetAncestor<ConstructorDeclarationSyntax>() != null;
}
public bool IsUnsafeContext(SyntaxNode node)
{
return node.IsUnsafeContext();
}
public SyntaxNode GetNameOfAttribute(SyntaxNode node)
{
return ((AttributeSyntax)node).Name;
}
public bool IsAttribute(SyntaxNode node)
{
return node is AttributeSyntax;
}
public bool IsAttributeNamedArgumentIdentifier(SyntaxNode node)
{
var identifier = node as IdentifierNameSyntax;
return
identifier != null &&
identifier.IsParentKind(SyntaxKind.NameEquals) &&
identifier.Parent.IsParentKind(SyntaxKind.AttributeArgument);
}
public SyntaxNode GetContainingTypeDeclaration(SyntaxNode root, int position)
{
if (root == null)
{
throw new ArgumentNullException(nameof(root));
}
if (position < 0 || position > root.Span.End)
{
throw new ArgumentOutOfRangeException(nameof(position));
}
return root
.FindToken(position)
.GetAncestors<SyntaxNode>()
.FirstOrDefault(n => n is BaseTypeDeclarationSyntax || n is DelegateDeclarationSyntax);
}
public SyntaxNode GetContainingVariableDeclaratorOfFieldDeclaration(SyntaxNode node)
{
throw ExceptionUtilities.Unreachable;
}
public SyntaxToken FindTokenOnLeftOfPosition(
SyntaxNode node, int position, bool includeSkipped, bool includeDirectives, bool includeDocumentationComments)
{
return node.FindTokenOnLeftOfPosition(position, includeSkipped, includeDirectives, includeDocumentationComments);
}
public SyntaxToken FindTokenOnRightOfPosition(
SyntaxNode node, int position, bool includeSkipped, bool includeDirectives, bool includeDocumentationComments)
{
return node.FindTokenOnRightOfPosition(position, includeSkipped, includeDirectives, includeDocumentationComments);
}
public bool IsObjectCreationExpression(SyntaxNode node)
{
return node is ObjectCreationExpressionSyntax;
}
public bool IsObjectInitializerNamedAssignmentIdentifier(SyntaxNode node)
{
var identifier = node as IdentifierNameSyntax;
return
identifier != null &&
identifier.IsLeftSideOfAssignExpression() &&
identifier.Parent.IsParentKind(SyntaxKind.ObjectInitializerExpression);
}
public bool IsElementAccessExpression(SyntaxNode node)
{
return node.Kind() == SyntaxKind.ElementAccessExpression;
}
public SyntaxNode ConvertToSingleLine(SyntaxNode node)
{
return node.ConvertToSingleLine();
}
public SyntaxToken ToIdentifierToken(string name)
{
return name.ToIdentifierToken();
}
public SyntaxNode Parenthesize(SyntaxNode expression, bool includeElasticTrivia)
{
return ((ExpressionSyntax)expression).Parenthesize(includeElasticTrivia);
}
public bool IsIndexerMemberCRef(SyntaxNode node)
{
return node.Kind() == SyntaxKind.IndexerMemberCref;
}
public SyntaxNode GetContainingMemberDeclaration(SyntaxNode root, int position, bool useFullSpan = true)
{
Contract.ThrowIfNull(root, "root");
Contract.ThrowIfTrue(position < 0 || position > root.FullSpan.End, "position");
var end = root.FullSpan.End;
if (end == 0)
{
// empty file
return null;
}
// make sure position doesn't touch end of root
position = Math.Min(position, end - 1);
var node = root.FindToken(position).Parent;
while (node != null)
{
if (useFullSpan || node.Span.Contains(position))
{
if ((node.Kind() != SyntaxKind.GlobalStatement) && (node is MemberDeclarationSyntax))
{
return node;
}
}
node = node.Parent;
}
return null;
}
public bool IsMethodLevelMember(SyntaxNode node)
{
return node is BaseMethodDeclarationSyntax || node is BasePropertyDeclarationSyntax || node is EnumMemberDeclarationSyntax || node is BaseFieldDeclarationSyntax;
}
public bool IsTopLevelNodeWithMembers(SyntaxNode node)
{
return node is NamespaceDeclarationSyntax ||
node is TypeDeclarationSyntax ||
node is EnumDeclarationSyntax;
}
public bool TryGetDeclaredSymbolInfo(SyntaxNode node, out DeclaredSymbolInfo declaredSymbolInfo)
{
switch (node.Kind())
{
case SyntaxKind.ClassDeclaration:
var classDecl = (ClassDeclarationSyntax)node;
declaredSymbolInfo = new DeclaredSymbolInfo(classDecl.Identifier.ValueText,
GetContainerDisplayName(node.Parent),
GetFullyQualifiedContainerName(node.Parent),
DeclaredSymbolInfoKind.Class, classDecl.Identifier.Span);
return true;
case SyntaxKind.ConstructorDeclaration:
var ctorDecl = (ConstructorDeclarationSyntax)node;
declaredSymbolInfo = new DeclaredSymbolInfo(
ctorDecl.Identifier.ValueText,
GetContainerDisplayName(node.Parent),
GetFullyQualifiedContainerName(node.Parent),
DeclaredSymbolInfoKind.Constructor,
ctorDecl.Identifier.Span,
parameterCount: (ushort)(ctorDecl.ParameterList?.Parameters.Count ?? 0));
return true;
case SyntaxKind.DelegateDeclaration:
var delegateDecl = (DelegateDeclarationSyntax)node;
declaredSymbolInfo = new DeclaredSymbolInfo(delegateDecl.Identifier.ValueText,
GetContainerDisplayName(node.Parent),
GetFullyQualifiedContainerName(node.Parent),
DeclaredSymbolInfoKind.Delegate, delegateDecl.Identifier.Span);
return true;
case SyntaxKind.EnumDeclaration:
var enumDecl = (EnumDeclarationSyntax)node;
declaredSymbolInfo = new DeclaredSymbolInfo(enumDecl.Identifier.ValueText,
GetContainerDisplayName(node.Parent),
GetFullyQualifiedContainerName(node.Parent),
DeclaredSymbolInfoKind.Enum, enumDecl.Identifier.Span);
return true;
case SyntaxKind.EnumMemberDeclaration:
var enumMember = (EnumMemberDeclarationSyntax)node;
declaredSymbolInfo = new DeclaredSymbolInfo(enumMember.Identifier.ValueText,
GetContainerDisplayName(node.Parent),
GetFullyQualifiedContainerName(node.Parent),
DeclaredSymbolInfoKind.EnumMember, enumMember.Identifier.Span);
return true;
case SyntaxKind.EventDeclaration:
var eventDecl = (EventDeclarationSyntax)node;
declaredSymbolInfo = new DeclaredSymbolInfo(ExpandExplicitInterfaceName(eventDecl.Identifier.ValueText, eventDecl.ExplicitInterfaceSpecifier),
GetContainerDisplayName(node.Parent),
GetFullyQualifiedContainerName(node.Parent),
DeclaredSymbolInfoKind.Event, eventDecl.Identifier.Span);
return true;
case SyntaxKind.IndexerDeclaration:
var indexerDecl = (IndexerDeclarationSyntax)node;
declaredSymbolInfo = new DeclaredSymbolInfo(WellKnownMemberNames.Indexer,
GetContainerDisplayName(node.Parent),
GetFullyQualifiedContainerName(node.Parent),
DeclaredSymbolInfoKind.Indexer, indexerDecl.ThisKeyword.Span);
return true;
case SyntaxKind.InterfaceDeclaration:
var interfaceDecl = (InterfaceDeclarationSyntax)node;
declaredSymbolInfo = new DeclaredSymbolInfo(interfaceDecl.Identifier.ValueText,
GetContainerDisplayName(node.Parent),
GetFullyQualifiedContainerName(node.Parent),
DeclaredSymbolInfoKind.Interface, interfaceDecl.Identifier.Span);
return true;
case SyntaxKind.MethodDeclaration:
var method = (MethodDeclarationSyntax)node;
declaredSymbolInfo = new DeclaredSymbolInfo(
ExpandExplicitInterfaceName(method.Identifier.ValueText, method.ExplicitInterfaceSpecifier),
GetContainerDisplayName(node.Parent),
GetFullyQualifiedContainerName(node.Parent),
DeclaredSymbolInfoKind.Method,
method.Identifier.Span,
parameterCount: (ushort)(method.ParameterList?.Parameters.Count ?? 0),
typeParameterCount: (ushort)(method.TypeParameterList?.Parameters.Count ?? 0));
return true;
case SyntaxKind.PropertyDeclaration:
var property = (PropertyDeclarationSyntax)node;
declaredSymbolInfo = new DeclaredSymbolInfo(ExpandExplicitInterfaceName(property.Identifier.ValueText, property.ExplicitInterfaceSpecifier),
GetContainerDisplayName(node.Parent),
GetFullyQualifiedContainerName(node.Parent),
DeclaredSymbolInfoKind.Property, property.Identifier.Span);
return true;
case SyntaxKind.StructDeclaration:
var structDecl = (StructDeclarationSyntax)node;
declaredSymbolInfo = new DeclaredSymbolInfo(structDecl.Identifier.ValueText,
GetContainerDisplayName(node.Parent),
GetFullyQualifiedContainerName(node.Parent),
DeclaredSymbolInfoKind.Struct, structDecl.Identifier.Span);
return true;
case SyntaxKind.VariableDeclarator:
// could either be part of a field declaration or an event field declaration
var variableDeclarator = (VariableDeclaratorSyntax)node;
var variableDeclaration = variableDeclarator.Parent as VariableDeclarationSyntax;
var fieldDeclaration = variableDeclaration?.Parent as BaseFieldDeclarationSyntax;
if (fieldDeclaration != null)
{
var kind = fieldDeclaration is EventFieldDeclarationSyntax
? DeclaredSymbolInfoKind.Event
: fieldDeclaration.Modifiers.Any(m => m.Kind() == SyntaxKind.ConstKeyword)
? DeclaredSymbolInfoKind.Constant
: DeclaredSymbolInfoKind.Field;
declaredSymbolInfo = new DeclaredSymbolInfo(variableDeclarator.Identifier.ValueText,
GetContainerDisplayName(fieldDeclaration.Parent),
GetFullyQualifiedContainerName(fieldDeclaration.Parent),
kind, variableDeclarator.Identifier.Span);
return true;
}
break;
}
declaredSymbolInfo = default(DeclaredSymbolInfo);
return false;
}
private static string ExpandExplicitInterfaceName(string identifier, ExplicitInterfaceSpecifierSyntax explicitInterfaceSpecifier)
{
if (explicitInterfaceSpecifier == null)
{
return identifier;
}
else
{
var builder = new StringBuilder();
ExpandTypeName(explicitInterfaceSpecifier.Name, builder);
builder.Append('.');
builder.Append(identifier);
return builder.ToString();
}
}
private static void ExpandTypeName(TypeSyntax type, StringBuilder builder)
{
switch (type.Kind())
{
case SyntaxKind.AliasQualifiedName:
var alias = (AliasQualifiedNameSyntax)type;
builder.Append(alias.Alias.Identifier.ValueText);
break;
case SyntaxKind.ArrayType:
var array = (ArrayTypeSyntax)type;
ExpandTypeName(array.ElementType, builder);
for (int i = 0; i < array.RankSpecifiers.Count; i++)
{
var rankSpecifier = array.RankSpecifiers[i];
builder.Append(rankSpecifier.OpenBracketToken.Text);
for (int j = 1; j < rankSpecifier.Sizes.Count; j++)
{
builder.Append(',');
}
builder.Append(rankSpecifier.CloseBracketToken.Text);
}
break;
case SyntaxKind.GenericName:
var generic = (GenericNameSyntax)type;
builder.Append(generic.Identifier.ValueText);
if (generic.TypeArgumentList != null)
{
var arguments = generic.TypeArgumentList.Arguments;
builder.Append(generic.TypeArgumentList.LessThanToken.Text);
for (int i = 0; i < arguments.Count; i++)
{
if (i != 0)
{
builder.Append(',');
}
ExpandTypeName(arguments[i], builder);
}
builder.Append(generic.TypeArgumentList.GreaterThanToken.Text);
}
break;
case SyntaxKind.IdentifierName:
var identifierName = (IdentifierNameSyntax)type;
builder.Append(identifierName.Identifier.ValueText);
break;
case SyntaxKind.NullableType:
var nullable = (NullableTypeSyntax)type;
ExpandTypeName(nullable.ElementType, builder);
builder.Append(nullable.QuestionToken.Text);
break;
case SyntaxKind.OmittedTypeArgument:
// do nothing since it was omitted, but don't reach the default block
break;
case SyntaxKind.PointerType:
var pointer = (PointerTypeSyntax)type;
ExpandTypeName(pointer.ElementType, builder);
builder.Append(pointer.AsteriskToken.Text);
break;
case SyntaxKind.PredefinedType:
var predefined = (PredefinedTypeSyntax)type;
builder.Append(predefined.Keyword.Text);
break;
case SyntaxKind.QualifiedName:
var qualified = (QualifiedNameSyntax)type;
ExpandTypeName(qualified.Left, builder);
builder.Append(qualified.DotToken.Text);
ExpandTypeName(qualified.Right, builder);
break;
default:
Debug.Assert(false, "Unexpected type syntax " + type.Kind());
break;
}
}
private string GetContainerDisplayName(SyntaxNode node)
{
return GetDisplayName(node, DisplayNameOptions.IncludeTypeParameters);
}
private string GetFullyQualifiedContainerName(SyntaxNode node)
{
return GetDisplayName(node, DisplayNameOptions.IncludeNamespaces);
}
private const string dotToken = ".";
public string GetDisplayName(SyntaxNode node, DisplayNameOptions options, string rootNamespace = null)
{
if (node == null)
{
return string.Empty;
}
var pooled = PooledStringBuilder.GetInstance();
var builder = pooled.Builder;
// return type
var memberDeclaration = node as MemberDeclarationSyntax;
if ((options & DisplayNameOptions.IncludeType) != 0)
{
var type = memberDeclaration.GetMemberType();
if (type != null && !type.IsMissing)
{
builder.Append(type);
builder.Append(' ');
}
}
var names = ArrayBuilder<string>.GetInstance();
// containing type(s)
var parent = node.GetAncestor<TypeDeclarationSyntax>() ?? node.Parent;
while (parent is TypeDeclarationSyntax)
{
names.Push(GetName(parent, options));
parent = parent.Parent;
}
// containing namespace(s) in source (if any)
if ((options & DisplayNameOptions.IncludeNamespaces) != 0)
{
while (parent != null && parent.Kind() == SyntaxKind.NamespaceDeclaration)
{
names.Add(GetName(parent, options));
parent = parent.Parent;
}
}
while (!names.IsEmpty())
{
var name = names.Pop();
if (name != null)
{
builder.Append(name);
builder.Append(dotToken);
}
}
// name (including generic type parameters)
builder.Append(GetName(node, options));
// parameter list (if any)
if ((options & DisplayNameOptions.IncludeParameters) != 0)
{
builder.Append(memberDeclaration.GetParameterList());
}
return pooled.ToStringAndFree();
}
private static string GetName(SyntaxNode node, DisplayNameOptions options)
{
const string missingTokenPlaceholder = "?";
switch (node.Kind())
{
case SyntaxKind.CompilationUnit:
return null;
case SyntaxKind.IdentifierName:
var identifier = ((IdentifierNameSyntax)node).Identifier;
return identifier.IsMissing ? missingTokenPlaceholder : identifier.Text;
case SyntaxKind.NamespaceDeclaration:
return GetName(((NamespaceDeclarationSyntax)node).Name, options);
case SyntaxKind.QualifiedName:
var qualified = (QualifiedNameSyntax)node;
return GetName(qualified.Left, options) + dotToken + GetName(qualified.Right, options);
}
string name = null;
var memberDeclaration = node as MemberDeclarationSyntax;
if (memberDeclaration != null)
{
var nameToken = memberDeclaration.GetNameToken();
if (nameToken == default(SyntaxToken))
{
Debug.Assert(memberDeclaration.Kind() == SyntaxKind.ConversionOperatorDeclaration);
name = (memberDeclaration as ConversionOperatorDeclarationSyntax)?.Type.ToString();
}
else
{
name = nameToken.IsMissing ? missingTokenPlaceholder : nameToken.Text;
if (memberDeclaration.Kind() == SyntaxKind.DestructorDeclaration)
{
name = "~" + name;
}
if ((options & DisplayNameOptions.IncludeTypeParameters) != 0)
{
var pooled = PooledStringBuilder.GetInstance();
var builder = pooled.Builder;
builder.Append(name);
AppendTypeParameterList(builder, memberDeclaration.GetTypeParameterList());
name = pooled.ToStringAndFree();
}
}
}
else
{
var fieldDeclarator = node as VariableDeclaratorSyntax;
if (fieldDeclarator != null)
{
var nameToken = fieldDeclarator.Identifier;
if (nameToken != default(SyntaxToken))
{
name = nameToken.IsMissing ? missingTokenPlaceholder : nameToken.Text;
}
}
}
Debug.Assert(name != null, "Unexpected node type " + node.Kind());
return name;
}
private static void AppendTypeParameterList(StringBuilder builder, TypeParameterListSyntax typeParameterList)
{
if (typeParameterList != null && typeParameterList.Parameters.Count > 0)
{
builder.Append('<');
builder.Append(typeParameterList.Parameters[0].Identifier.ValueText);
for (int i = 1; i < typeParameterList.Parameters.Count; i++)
{
builder.Append(", ");
builder.Append(typeParameterList.Parameters[i].Identifier.ValueText);
}
builder.Append('>');
}
}
public List<SyntaxNode> GetMethodLevelMembers(SyntaxNode root)
{
var list = new List<SyntaxNode>();
AppendMethodLevelMembers(root, list);
return list;
}
private void AppendMethodLevelMembers(SyntaxNode node, List<SyntaxNode> list)
{
foreach (var member in node.GetMembers())
{
if (IsTopLevelNodeWithMembers(member))
{
AppendMethodLevelMembers(member, list);
continue;
}
if (IsMethodLevelMember(member))
{
list.Add(member);
}
}
}
public TextSpan GetMemberBodySpanForSpeculativeBinding(SyntaxNode node)
{
if (node.Span.IsEmpty)
{
return default(TextSpan);
}
var member = GetContainingMemberDeclaration(node, node.SpanStart);
if (member == null)
{
return default(TextSpan);
}
// TODO: currently we only support method for now
var method = member as BaseMethodDeclarationSyntax;
if (method != null)
{
if (method.Body == null)
{
return default(TextSpan);
}
return GetBlockBodySpan(method.Body);
}
return default(TextSpan);
}
public bool ContainsInMemberBody(SyntaxNode node, TextSpan span)
{
var constructor = node as ConstructorDeclarationSyntax;
if (constructor != null)
{
return (constructor.Body != null && GetBlockBodySpan(constructor.Body).Contains(span)) ||
(constructor.Initializer != null && constructor.Initializer.Span.Contains(span));
}
var method = node as BaseMethodDeclarationSyntax;
if (method != null)
{
return method.Body != null && GetBlockBodySpan(method.Body).Contains(span);
}
var property = node as BasePropertyDeclarationSyntax;
if (property != null)
{
return property.AccessorList != null && property.AccessorList.Span.Contains(span);
}
var @enum = node as EnumMemberDeclarationSyntax;
if (@enum != null)
{
return @enum.EqualsValue != null && @enum.EqualsValue.Span.Contains(span);
}
var field = node as BaseFieldDeclarationSyntax;
if (field != null)
{
return field.Declaration != null && field.Declaration.Span.Contains(span);
}
return false;
}
private TextSpan GetBlockBodySpan(BlockSyntax body)
{
return TextSpan.FromBounds(body.OpenBraceToken.Span.End, body.CloseBraceToken.SpanStart);
}
public int GetMethodLevelMemberId(SyntaxNode root, SyntaxNode node)
{
Contract.Requires(root.SyntaxTree == node.SyntaxTree);
int currentId = 0;
SyntaxNode currentNode;
Contract.ThrowIfFalse(TryGetMethodLevelMember(root, (n, i) => n == node, ref currentId, out currentNode));
Contract.ThrowIfFalse(currentId >= 0);
CheckMemberId(root, node, currentId);
return currentId;
}
public SyntaxNode GetMethodLevelMember(SyntaxNode root, int memberId)
{
int currentId = 0;
SyntaxNode currentNode;
if (!TryGetMethodLevelMember(root, (n, i) => i == memberId, ref currentId, out currentNode))
{
return null;
}
Contract.ThrowIfNull(currentNode);
CheckMemberId(root, currentNode, memberId);
return currentNode;
}
private bool TryGetMethodLevelMember(
SyntaxNode node, Func<SyntaxNode, int, bool> predicate, ref int currentId, out SyntaxNode currentNode)
{
foreach (var member in node.GetMembers())
{
if (IsTopLevelNodeWithMembers(member))
{
if (TryGetMethodLevelMember(member, predicate, ref currentId, out currentNode))
{
return true;
}
continue;
}
if (IsMethodLevelMember(member))
{
if (predicate(member, currentId))
{
currentNode = member;
return true;
}
currentId++;
}
}
currentNode = null;
return false;
}
[Conditional("DEBUG")]
private void CheckMemberId(SyntaxNode root, SyntaxNode node, int memberId)
{
var list = GetMethodLevelMembers(root);
var index = list.IndexOf(node);
Contract.ThrowIfFalse(index == memberId);
}
public SyntaxNode GetBindableParent(SyntaxToken token)
{
var node = token.Parent;
while (node != null)
{
var parent = node.Parent;
// If this node is on the left side of a member access expression, don't ascend
// further or we'll end up binding to something else.
var memberAccess = parent as MemberAccessExpressionSyntax;
if (memberAccess != null)
{
if (memberAccess.Expression == node)
{
break;
}
}
// If this node is on the left side of a qualified name, don't ascend
// further or we'll end up binding to something else.
var qualifiedName = parent as QualifiedNameSyntax;
if (qualifiedName != null)
{
if (qualifiedName.Left == node)
{
break;
}
}
// If this node is on the left side of a alias-qualified name, don't ascend
// further or we'll end up binding to something else.
var aliasQualifiedName = parent as AliasQualifiedNameSyntax;
if (aliasQualifiedName != null)
{
if (aliasQualifiedName.Alias == node)
{
break;
}
}
// If this node is the type of an object creation expression, return the
// object creation expression.
var objectCreation = parent as ObjectCreationExpressionSyntax;
if (objectCreation != null)
{
if (objectCreation.Type == node)
{
node = parent;
break;
}
}
// The inside of an interpolated string is treated as its own token so we
// need to force navigation to the parent expression syntax.
if (node is InterpolatedStringTextSyntax && parent is InterpolatedStringExpressionSyntax)
{
node = parent;
break;
}
// If this node is not parented by a name, we're done.
var name = parent as NameSyntax;
if (name == null)
{
break;
}
node = parent;
}
return node;
}
public IEnumerable<SyntaxNode> GetConstructors(SyntaxNode root, CancellationToken cancellationToken)
{
var compilationUnit = root as CompilationUnitSyntax;
if (compilationUnit == null)
{
return SpecializedCollections.EmptyEnumerable<SyntaxNode>();
}
var constructors = new List<SyntaxNode>();
AppendConstructors(compilationUnit.Members, constructors, cancellationToken);
return constructors;
}
private void AppendConstructors(SyntaxList<MemberDeclarationSyntax> members, List<SyntaxNode> constructors, CancellationToken cancellationToken)
{
foreach (var member in members)
{
cancellationToken.ThrowIfCancellationRequested();
var constructor = member as ConstructorDeclarationSyntax;
if (constructor != null)
{
constructors.Add(constructor);
continue;
}
var @namespace = member as NamespaceDeclarationSyntax;
if (@namespace != null)
{
AppendConstructors(@namespace.Members, constructors, cancellationToken);
}
var @class = member as ClassDeclarationSyntax;
if (@class != null)
{
AppendConstructors(@class.Members, constructors, cancellationToken);
}
var @struct = member as StructDeclarationSyntax;
if (@struct != null)
{
AppendConstructors(@struct.Members, constructors, cancellationToken);
}
}
}
public bool TryGetCorrespondingOpenBrace(SyntaxToken token, out SyntaxToken openBrace)
{
if (token.Kind() == SyntaxKind.CloseBraceToken)
{
var tuple = token.Parent.GetBraces();
openBrace = tuple.Item1;
return openBrace.Kind() == SyntaxKind.OpenBraceToken;
}
openBrace = default(SyntaxToken);
return false;
}
}
}
| |
using System;
namespace Daemaged.NTP
{
/// <summary>
/// Represents a NTP packet.
/// </summary>
/// <remarks>
/// See RFC 1305 for the packet specification. Note that
/// this implementation does not use any optional fields.
/// </remarks>
public class NtpPacket
{
readonly byte[] _data;
NtpTimestamp _destinationTimestamp;
const int INDEX_BITFIELD = 0;
const int INDEX_ORIGINATE_TIMESTAMP = 0x18;
const int INDEX_POLL = 2;
const int INDEX_PRECISION = 3;
const int INDEX_RECEIVE_TIMESTAMP = 32;
const int INDEX_REFERENCE_IDENTIFIER = 12;
const int INDEX_REFERENCE_TIMESTAMP = 16;
const int INDEX_ROOT_DELAY = 4;
const int INDEX_ROOT_DISPERSION = 8;
const int INDEX_STRATUM = 1;
const int INDEX_TRANSMIT_TIMESTAMP = 40;
const int LENGTH_LI = 2;
const int LENGTH_MODE = 3;
const int LENGTH_VN = 3;
const int OFFSET_LI = 6;
const int OFFSET_MODE = 0;
const int OFFSET_VN = 3;
/// <summary>
/// Minimal size of an NTP packet (they can be larger,
/// but the optional fields are at the end and this
/// class ignores them).
/// </summary>
internal const int MinPacketSize = 0x30;
/// <summary>
/// Constructs an empty (i.e. with all bits set to 0) packet.
/// </summary>
internal NtpPacket()
{
_data = new byte[MinPacketSize];
_destinationTimestamp = NtpTimestamp.Now;
}
/// <summary>
/// Constructs a client packet.
/// </summary>
internal NtpPacket(NtpMode mode, byte versionNumber, NtpTimestamp transmitTimestamp)
: this()
{
_data[0] = SetBits(_data[0], OFFSET_VN, LENGTH_MODE, versionNumber);
_data[0] = SetBits(_data[0], INDEX_BITFIELD, LENGTH_MODE, (byte)mode);
CopyTimestampToData(transmitTimestamp, INDEX_TRANSMIT_TIMESTAMP);
}
void CheckPlacement(int offset, int length)
{
if (offset < 0)
throw new ArgumentException($"Invalid offset {offset} - cannot be negative.");
if (length <= 0)
throw new ArgumentException($"Invalid length {length} - must be positive.");
if ((offset + length) > 8)
throw new ArgumentException("Invalid offset/length.");
}
void CopyTimestampToData(NtpTimestamp ts, int index)
{
UpdateData(ts.ToArray(), index, 8);
}
byte[] DuplicateData(int index, int length)
{
var destinationArray = new byte[length];
Array.Copy(_data, index, destinationArray, 0, length);
return destinationArray;
}
byte GetBits(byte field, int offset, int length)
{
CheckPlacement(offset, length);
return (byte)((field >> offset) & GetMask(length));
}
int GetMask(int length)
{
return ((1 << length) - 1);
}
/// <summary>
/// Reference Identifier.
/// </summary>
/// <value>4 bytes - see RFC 2030 for their interpretation.</value>
public byte[] GetReferenceIdentifier()
{ return DuplicateData(INDEX_REFERENCE_IDENTIFIER, 4); }
/// <summary>
/// Root Delay.
/// </summary>
/// <value>4 bytes - see RFC 2030 for their interpretation.</value>
public byte[] GetRootDelay()
{ return DuplicateData(INDEX_ROOT_DELAY, 4); }
/// <summary>
/// Root Dispersion.
/// </summary>
/// <value>4 bytes - see RFC 2030 for their interpretation.</value>
public byte[] GetRootDispersion()
{ return DuplicateData(INDEX_ROOT_DISPERSION, 4); }
byte SetBits(byte field, int offset, int length, byte v)
{
CheckPlacement(offset, length);
var mask = GetMask(length);
if (v > mask)
throw new ArgumentException($"Value {v} won't fit into {length} bits - maximum is {mask}.", "v");
mask = mask << offset;
return (byte)((field & ~mask) | (v << offset));
}
internal void SetDestinationTimestamp(NtpTimestamp timestamp)
{ _destinationTimestamp = timestamp; }
/// <summary>
/// Accessor for the raw packet _data.
/// </summary>
/// <value>The array size is <see cref="F:Daemaged.NTP.NtpPacket.MinPacketSize" /> bytes.</value>
public byte[] ToArray()
{
return (byte[])_data.Clone();
}
void UpdateData(byte[] d, int index, int length)
{
if (d.Length != length)
throw new ArgumentException($"Data length ({d.Length}) must be equal to the length parameter value ({length}).");
d.CopyTo(_data, index);
}
internal byte[] Data => _data;
/// <summary>
/// Destination Timestamp: the time at which the reply arrived at the client.
/// </summary>
/// <value>Timestamp in <see cref="T:Daemaged.NTP.NtpTimestamp">NTP format</see>.</value>
public NtpTimestamp DestinationTimestamp => _destinationTimestamp;
/// <summary>
/// Returns the leap second indicator.
/// </summary>
/// <value>Leap indicator.</value>
public NtpLeapIndicator LeapIndicator {
get {
switch (GetBits(_data[0], OFFSET_LI, LENGTH_LI))
{
case 0: return NtpLeapIndicator.NoLeap;
case 1: return NtpLeapIndicator.OneSecondMore;
case 2: return NtpLeapIndicator.OneSecondLess;
}
return NtpLeapIndicator.AlarmCondition;
}
}
/// <summary>
/// NTP packet mode.
/// </summary>
/// <value>3 bits. Possible values are described in <see cref="T:Daemaged.NTP.NtpMode" />.</value>
public NtpMode Mode => (NtpMode)GetBits(_data[0], OFFSET_MODE, LENGTH_MODE);
/// <summary>
/// Originate Timestamp: the time at which the request departed the client for the server.
/// </summary>
/// <value>Timestamp in <see cref="T:Daemaged.NTP.NtpTimestamp">NTP format</see>.</value>
public NtpTimestamp OriginateTimestamp => new NtpTimestamp(_data, INDEX_ORIGINATE_TIMESTAMP);
/// <summary>
/// Poll Interval, in seconds to the nearest power of two.
/// </summary>
/// <value>Maximum range is 4 to 14, normal range 6 to 10.</value>
public int Poll => _data[INDEX_POLL];
/// <summary>
/// Precision of the packet originator's clock, in seconds to
/// the nearest power of two.
/// </summary>
/// <value>Normal range is -6 to -20.</value>
public int Precision => _data[INDEX_PRECISION];
/// <summary>
/// Receive Timestamp: the time at which the request arrived at the server.
/// </summary>
/// <value>Timestamp in <see cref="T:Daemaged.NTP.NtpTimestamp">NTP format</see>.</value>
public NtpTimestamp ReceiveTimestamp => new NtpTimestamp(_data, INDEX_RECEIVE_TIMESTAMP);
/// <summary>
/// Reference Timestamp: the time at which the local clock was last
/// set or corrected.
/// </summary>
/// <value>Timestamp in <see cref="T:Daemaged.NTP.NtpTimestamp">NTP format</see>.</value>
public NtpTimestamp ReferenceTimestamp => new NtpTimestamp(_data, INDEX_REFERENCE_TIMESTAMP);
/// <summary>
/// Stratum level (time quality) of the packet originator's clock.
/// </summary>
/// <value>0 is unspecified or undefined, 1 primary (for Internet
/// NTP servers that generally means an atomic clock, within Windows
/// local networks it's the best time source in the network), higher
/// numbers mean increasing distance from the primary source.</value>
public int Stratum => _data[INDEX_STRATUM];
/// <summary>
/// Transmit Timestamp: the time at which the reply departed the server for the client.
/// </summary>
/// <value>Timestamp in <see cref="T:Daemaged.NTP.NtpTimestamp">NTP format</see>.</value>
public NtpTimestamp TransmitTimestamp => new NtpTimestamp(_data, INDEX_TRANSMIT_TIMESTAMP);
/// <summary>
/// RootDelay: the server's estimated aggregate round-trip-time delay to
/// the stratum 1 server.
/// </summary>
/// <value>Duration in milliseconds.</value>
public double RootDelay {
get {
byte[] rootDelayBuffer = GetRootDelay();
return 1000 * ((double)(256 * (256 * (256 * rootDelayBuffer[0] + rootDelayBuffer[1]) + rootDelayBuffer[2]) + rootDelayBuffer[3]) / 0x10000);
}
}
/// <summary>
/// RootDispersion: the server's estimated maximum measurement error relative to
/// the stratum 1 server.
/// </summary>
/// <value>Duration in milliseconds.</value>
public double RootDispersion {
get {
byte[] rootDispersionBuffer = GetRootDispersion();
return 1000 * ((double)(256 * (256 * (256 * rootDispersionBuffer[0] + rootDispersionBuffer[1]) + rootDispersionBuffer[2]) + rootDispersionBuffer[3]) / 0x10000);
}
}
}
}
| |
/*
* ******************************************************************************
* Copyright 2014-2017 Spectra Logic Corporation. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use
* this file except in compliance with the License. A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* or in the "license" file accompanying this file.
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
* ****************************************************************************
*/
// This code is auto-generated, do not modify
using Ds3.Models;
using System;
using System.Net;
namespace Ds3.Calls
{
public class ModifyDataPathBackendSpectraS3Request : Ds3Request
{
private bool? _activated;
public bool? Activated
{
get { return _activated; }
set { WithActivated(value); }
}
private bool? _allowNewJobRequests;
public bool? AllowNewJobRequests
{
get { return _allowNewJobRequests; }
set { WithAllowNewJobRequests(value); }
}
private int? _autoActivateTimeoutInMins;
public int? AutoActivateTimeoutInMins
{
get { return _autoActivateTimeoutInMins; }
set { WithAutoActivateTimeoutInMins(value); }
}
private AutoInspectMode? _autoInspect;
public AutoInspectMode? AutoInspect
{
get { return _autoInspect; }
set { WithAutoInspect(value); }
}
private int? _cacheAvailableRetryAfterInSeconds;
public int? CacheAvailableRetryAfterInSeconds
{
get { return _cacheAvailableRetryAfterInSeconds; }
set { WithCacheAvailableRetryAfterInSeconds(value); }
}
private Priority? _defaultVerifyDataAfterImport;
public Priority? DefaultVerifyDataAfterImport
{
get { return _defaultVerifyDataAfterImport; }
set { WithDefaultVerifyDataAfterImport(value); }
}
private bool? _defaultVerifyDataPriorToImport;
public bool? DefaultVerifyDataPriorToImport
{
get { return _defaultVerifyDataPriorToImport; }
set { WithDefaultVerifyDataPriorToImport(value); }
}
private bool? _iomEnabled;
public bool? IomEnabled
{
get { return _iomEnabled; }
set { WithIomEnabled(value); }
}
private int? _partiallyVerifyLastPercentOfTapes;
public int? PartiallyVerifyLastPercentOfTapes
{
get { return _partiallyVerifyLastPercentOfTapes; }
set { WithPartiallyVerifyLastPercentOfTapes(value); }
}
private UnavailableMediaUsagePolicy? _unavailableMediaPolicy;
public UnavailableMediaUsagePolicy? UnavailableMediaPolicy
{
get { return _unavailableMediaPolicy; }
set { WithUnavailableMediaPolicy(value); }
}
private int? _unavailablePoolMaxJobRetryInMins;
public int? UnavailablePoolMaxJobRetryInMins
{
get { return _unavailablePoolMaxJobRetryInMins; }
set { WithUnavailablePoolMaxJobRetryInMins(value); }
}
private int? _unavailableTapePartitionMaxJobRetryInMins;
public int? UnavailableTapePartitionMaxJobRetryInMins
{
get { return _unavailableTapePartitionMaxJobRetryInMins; }
set { WithUnavailableTapePartitionMaxJobRetryInMins(value); }
}
public ModifyDataPathBackendSpectraS3Request WithActivated(bool? activated)
{
this._activated = activated;
if (activated != null)
{
this.QueryParams.Add("activated", activated.ToString());
}
else
{
this.QueryParams.Remove("activated");
}
return this;
}
public ModifyDataPathBackendSpectraS3Request WithAllowNewJobRequests(bool? allowNewJobRequests)
{
this._allowNewJobRequests = allowNewJobRequests;
if (allowNewJobRequests != null)
{
this.QueryParams.Add("allow_new_job_requests", allowNewJobRequests.ToString());
}
else
{
this.QueryParams.Remove("allow_new_job_requests");
}
return this;
}
public ModifyDataPathBackendSpectraS3Request WithAutoActivateTimeoutInMins(int? autoActivateTimeoutInMins)
{
this._autoActivateTimeoutInMins = autoActivateTimeoutInMins;
if (autoActivateTimeoutInMins != null)
{
this.QueryParams.Add("auto_activate_timeout_in_mins", autoActivateTimeoutInMins.ToString());
}
else
{
this.QueryParams.Remove("auto_activate_timeout_in_mins");
}
return this;
}
public ModifyDataPathBackendSpectraS3Request WithAutoInspect(AutoInspectMode? autoInspect)
{
this._autoInspect = autoInspect;
if (autoInspect != null)
{
this.QueryParams.Add("auto_inspect", autoInspect.ToString());
}
else
{
this.QueryParams.Remove("auto_inspect");
}
return this;
}
public ModifyDataPathBackendSpectraS3Request WithCacheAvailableRetryAfterInSeconds(int? cacheAvailableRetryAfterInSeconds)
{
this._cacheAvailableRetryAfterInSeconds = cacheAvailableRetryAfterInSeconds;
if (cacheAvailableRetryAfterInSeconds != null)
{
this.QueryParams.Add("cache_available_retry_after_in_seconds", cacheAvailableRetryAfterInSeconds.ToString());
}
else
{
this.QueryParams.Remove("cache_available_retry_after_in_seconds");
}
return this;
}
public ModifyDataPathBackendSpectraS3Request WithDefaultVerifyDataAfterImport(Priority? defaultVerifyDataAfterImport)
{
this._defaultVerifyDataAfterImport = defaultVerifyDataAfterImport;
if (defaultVerifyDataAfterImport != null)
{
this.QueryParams.Add("default_verify_data_after_import", defaultVerifyDataAfterImport.ToString());
}
else
{
this.QueryParams.Remove("default_verify_data_after_import");
}
return this;
}
public ModifyDataPathBackendSpectraS3Request WithDefaultVerifyDataPriorToImport(bool? defaultVerifyDataPriorToImport)
{
this._defaultVerifyDataPriorToImport = defaultVerifyDataPriorToImport;
if (defaultVerifyDataPriorToImport != null)
{
this.QueryParams.Add("default_verify_data_prior_to_import", defaultVerifyDataPriorToImport.ToString());
}
else
{
this.QueryParams.Remove("default_verify_data_prior_to_import");
}
return this;
}
public ModifyDataPathBackendSpectraS3Request WithIomEnabled(bool? iomEnabled)
{
this._iomEnabled = iomEnabled;
if (iomEnabled != null)
{
this.QueryParams.Add("iom_enabled", iomEnabled.ToString());
}
else
{
this.QueryParams.Remove("iom_enabled");
}
return this;
}
public ModifyDataPathBackendSpectraS3Request WithPartiallyVerifyLastPercentOfTapes(int? partiallyVerifyLastPercentOfTapes)
{
this._partiallyVerifyLastPercentOfTapes = partiallyVerifyLastPercentOfTapes;
if (partiallyVerifyLastPercentOfTapes != null)
{
this.QueryParams.Add("partially_verify_last_percent_of_tapes", partiallyVerifyLastPercentOfTapes.ToString());
}
else
{
this.QueryParams.Remove("partially_verify_last_percent_of_tapes");
}
return this;
}
public ModifyDataPathBackendSpectraS3Request WithUnavailableMediaPolicy(UnavailableMediaUsagePolicy? unavailableMediaPolicy)
{
this._unavailableMediaPolicy = unavailableMediaPolicy;
if (unavailableMediaPolicy != null)
{
this.QueryParams.Add("unavailable_media_policy", unavailableMediaPolicy.ToString());
}
else
{
this.QueryParams.Remove("unavailable_media_policy");
}
return this;
}
public ModifyDataPathBackendSpectraS3Request WithUnavailablePoolMaxJobRetryInMins(int? unavailablePoolMaxJobRetryInMins)
{
this._unavailablePoolMaxJobRetryInMins = unavailablePoolMaxJobRetryInMins;
if (unavailablePoolMaxJobRetryInMins != null)
{
this.QueryParams.Add("unavailable_pool_max_job_retry_in_mins", unavailablePoolMaxJobRetryInMins.ToString());
}
else
{
this.QueryParams.Remove("unavailable_pool_max_job_retry_in_mins");
}
return this;
}
public ModifyDataPathBackendSpectraS3Request WithUnavailableTapePartitionMaxJobRetryInMins(int? unavailableTapePartitionMaxJobRetryInMins)
{
this._unavailableTapePartitionMaxJobRetryInMins = unavailableTapePartitionMaxJobRetryInMins;
if (unavailableTapePartitionMaxJobRetryInMins != null)
{
this.QueryParams.Add("unavailable_tape_partition_max_job_retry_in_mins", unavailableTapePartitionMaxJobRetryInMins.ToString());
}
else
{
this.QueryParams.Remove("unavailable_tape_partition_max_job_retry_in_mins");
}
return this;
}
public ModifyDataPathBackendSpectraS3Request()
{
}
internal override HttpVerb Verb
{
get
{
return HttpVerb.PUT;
}
}
internal override string Path
{
get
{
return "/_rest_/data_path_backend";
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using Microsoft.CSharp.RuntimeBinder.Syntax;
namespace Microsoft.CSharp.RuntimeBinder.Semantics
{
internal abstract class CType
{
private TypeKind _typeKind;
private Name _pName;
private bool _fHasErrors; // Whether anyituents have errors. This is immutable.
private bool _fUnres; // Whether anyituents are unresolved. This is immutable.
private bool _isBogus; // can't be used in our language -- unsupported type(s)
private bool _checkedBogus; // Have we checked a method args/return for bogus types
// Is and As methods.
public AggregateType AsAggregateType() { return this as AggregateType; }
public ErrorType AsErrorType() { return this as ErrorType; }
public ArrayType AsArrayType() { return this as ArrayType; }
public PointerType AsPointerType() { return this as PointerType; }
public ParameterModifierType AsParameterModifierType() { return this as ParameterModifierType; }
public NullableType AsNullableType() { return this as NullableType; }
public TypeParameterType AsTypeParameterType() { return this as TypeParameterType; }
public bool IsAggregateType() { return this is AggregateType; }
public bool IsVoidType() { return this is VoidType; }
public bool IsNullType() { return this is NullType; }
public bool IsOpenTypePlaceholderType() { return this is OpenTypePlaceholderType; }
public bool IsBoundLambdaType() { return this is BoundLambdaType; }
public bool IsMethodGroupType() { return this is MethodGroupType; }
public bool IsErrorType() { return this is ErrorType; }
public bool IsArrayType() { return this is ArrayType; }
public bool IsPointerType() { return this is PointerType; }
public bool IsParameterModifierType() { return this is ParameterModifierType; }
public bool IsNullableType() { return this is NullableType; }
public bool IsTypeParameterType() { return this is TypeParameterType; }
public bool IsWindowsRuntimeType()
{
return (AssociatedSystemType.Attributes & TypeAttributes.WindowsRuntime) == TypeAttributes.WindowsRuntime;
}
public bool IsCollectionType()
{
if ((AssociatedSystemType.IsGenericType &&
(AssociatedSystemType.GetGenericTypeDefinition() == typeof(IList<>) ||
AssociatedSystemType.GetGenericTypeDefinition() == typeof(ICollection<>) ||
AssociatedSystemType.GetGenericTypeDefinition() == typeof(IEnumerable<>) ||
AssociatedSystemType.GetGenericTypeDefinition() == typeof(IReadOnlyList<>) ||
AssociatedSystemType.GetGenericTypeDefinition() == typeof(IReadOnlyCollection<>) ||
AssociatedSystemType.GetGenericTypeDefinition() == typeof(IDictionary<,>) ||
AssociatedSystemType.GetGenericTypeDefinition() == typeof(IReadOnlyDictionary<,>))) ||
AssociatedSystemType == typeof(System.Collections.IList) ||
AssociatedSystemType == typeof(System.Collections.ICollection) ||
AssociatedSystemType == typeof(System.Collections.IEnumerable) ||
AssociatedSystemType == typeof(System.Collections.Specialized.INotifyCollectionChanged) ||
AssociatedSystemType == typeof(System.ComponentModel.INotifyPropertyChanged))
{
return true;
}
return false;
}
// API similar to System.Type
public bool IsGenericParameter
{
get { return IsTypeParameterType(); }
}
private Type _associatedSystemType;
public Type AssociatedSystemType
{
get
{
if (_associatedSystemType == null)
{
_associatedSystemType = CalculateAssociatedSystemType(this);
}
return _associatedSystemType;
}
}
private static Type CalculateAssociatedSystemType(CType src)
{
Type result = null;
switch (src.GetTypeKind())
{
case TypeKind.TK_ArrayType:
ArrayType a = src.AsArrayType();
Type elementType = a.GetElementType().AssociatedSystemType;
result = a.IsSZArray ? elementType.MakeArrayType() : elementType.MakeArrayType(a.rank);
break;
case TypeKind.TK_NullableType:
NullableType n = src.AsNullableType();
Type underlyingType = n.GetUnderlyingType().AssociatedSystemType;
result = typeof(Nullable<>).MakeGenericType(underlyingType);
break;
case TypeKind.TK_PointerType:
PointerType p = src.AsPointerType();
Type referentType = p.GetReferentType().AssociatedSystemType;
result = referentType.MakePointerType();
break;
case TypeKind.TK_ParameterModifierType:
ParameterModifierType r = src.AsParameterModifierType();
Type parameterType = r.GetParameterType().AssociatedSystemType;
result = parameterType.MakeByRefType();
break;
case TypeKind.TK_AggregateType:
result = CalculateAssociatedSystemTypeForAggregate(src.AsAggregateType());
break;
case TypeKind.TK_TypeParameterType:
TypeParameterType t = src.AsTypeParameterType();
if (t.IsMethodTypeParameter())
{
MethodInfo meth = t.GetOwningSymbol().AsMethodSymbol().AssociatedMemberInfo as MethodInfo;
result = meth.GetGenericArguments()[t.GetIndexInOwnParameters()];
}
else
{
Type parentType = t.GetOwningSymbol().AsAggregateSymbol().AssociatedSystemType;
result = parentType.GetGenericArguments()[t.GetIndexInOwnParameters()];
}
break;
case TypeKind.TK_ArgumentListType:
case TypeKind.TK_BoundLambdaType:
case TypeKind.TK_ErrorType:
case TypeKind.TK_MethodGroupType:
case TypeKind.TK_NaturalIntegerType:
case TypeKind.TK_NullType:
case TypeKind.TK_OpenTypePlaceholderType:
case TypeKind.TK_UnboundLambdaType:
case TypeKind.TK_VoidType:
default:
break;
}
Debug.Assert(result != null || src.GetTypeKind() == TypeKind.TK_AggregateType);
return result;
}
private static Type CalculateAssociatedSystemTypeForAggregate(AggregateType aggtype)
{
AggregateSymbol agg = aggtype.GetOwningAggregate();
TypeArray typeArgs = aggtype.GetTypeArgsAll();
List<Type> list = new List<Type>();
// Get each type arg.
for (int i = 0; i < typeArgs.Count; i++)
{
// Unnamed type parameter types are just placeholders.
if (typeArgs[i].IsTypeParameterType() && typeArgs[i].AsTypeParameterType().GetTypeParameterSymbol().name == null)
{
return null;
}
list.Add(typeArgs[i].AssociatedSystemType);
}
Type[] systemTypeArgs = list.ToArray();
Type uninstantiatedType = agg.AssociatedSystemType;
if (uninstantiatedType.IsGenericType)
{
try
{
return uninstantiatedType.MakeGenericType(systemTypeArgs);
}
catch (ArgumentException)
{
// If the constraints don't work, just return the type without substituting it.
return uninstantiatedType;
}
}
return uninstantiatedType;
}
public TypeKind GetTypeKind() { return _typeKind; }
public void SetTypeKind(TypeKind kind) { _typeKind = kind; }
public Name GetName() { return _pName; }
public void SetName(Name pName) { _pName = pName; }
public bool checkBogus() { return _isBogus; }
public bool getBogus() { return _isBogus; }
public bool hasBogus() { return _checkedBogus; }
public void setBogus(bool isBogus)
{
_isBogus = isBogus;
_checkedBogus = true;
}
public bool computeCurrentBogusState()
{
if (hasBogus())
{
return checkBogus();
}
bool fBogus = false;
switch (GetTypeKind())
{
case TypeKind.TK_ParameterModifierType:
case TypeKind.TK_PointerType:
case TypeKind.TK_ArrayType:
case TypeKind.TK_NullableType:
if (GetBaseOrParameterOrElementType() != null)
{
fBogus = GetBaseOrParameterOrElementType().computeCurrentBogusState();
}
break;
case TypeKind.TK_ErrorType:
setBogus(false);
break;
case TypeKind.TK_AggregateType:
fBogus = AsAggregateType().getAggregate().computeCurrentBogusState();
for (int i = 0; !fBogus && i < AsAggregateType().GetTypeArgsAll().Count; i++)
{
fBogus |= AsAggregateType().GetTypeArgsAll()[i].computeCurrentBogusState();
}
break;
case TypeKind.TK_TypeParameterType:
case TypeKind.TK_VoidType:
case TypeKind.TK_NullType:
case TypeKind.TK_OpenTypePlaceholderType:
case TypeKind.TK_ArgumentListType:
case TypeKind.TK_NaturalIntegerType:
setBogus(false);
break;
default:
throw Error.InternalCompilerError();
//setBogus(false);
//break;
}
if (fBogus)
{
// Only set this if at least 1 declared thing is bogus
setBogus(fBogus);
}
return hasBogus() && checkBogus();
}
// This call switches on the kind and dispatches accordingly. This should really only be
// used when dereferencing TypeArrays. We should consider refactoring our code to not
// need this type of thing - strongly typed handling of TypeArrays would be much better.
public CType GetBaseOrParameterOrElementType()
{
switch (GetTypeKind())
{
case TypeKind.TK_ArrayType:
return AsArrayType().GetElementType();
case TypeKind.TK_PointerType:
return AsPointerType().GetReferentType();
case TypeKind.TK_ParameterModifierType:
return AsParameterModifierType().GetParameterType();
case TypeKind.TK_NullableType:
return AsNullableType().GetUnderlyingType();
default:
return null;
}
}
public void InitFromParent()
{
Debug.Assert(!IsAggregateType());
CType typePar = null;
if (IsErrorType())
{
typePar = AsErrorType().GetTypeParent();
}
else
{
typePar = GetBaseOrParameterOrElementType();
}
_fHasErrors = typePar.HasErrors();
_fUnres = typePar.IsUnresolved();
}
public bool HasErrors()
{
return _fHasErrors;
}
public void SetErrors(bool fHasErrors)
{
_fHasErrors = fHasErrors;
}
public bool IsUnresolved()
{
return _fUnres;
}
public void SetUnresolved(bool fUnres)
{
_fUnres = fUnres;
}
////////////////////////////////////////////////////////////////////////////////
// Given a symbol, determine its fundamental type. This is the type that
// indicate how the item is stored and what instructions are used to reference
// if. The fundamental types are:
// one of the integral/float types (includes enums with that underlying type)
// reference type
// struct/value type
public FUNDTYPE fundType()
{
switch (GetTypeKind())
{
case TypeKind.TK_AggregateType:
{
AggregateSymbol sym = AsAggregateType().getAggregate();
// Treat enums like their underlying types.
if (sym.IsEnum())
{
sym = sym.GetUnderlyingType().getAggregate();
}
if (sym.IsStruct())
{
// Struct type could be predefined (int, long, etc.) or some other struct.
if (sym.IsPredefined())
return PredefinedTypeFacts.GetFundType(sym.GetPredefType());
return FUNDTYPE.FT_STRUCT;
}
return FUNDTYPE.FT_REF; // Interfaces, classes, delegates are reference types.
}
case TypeKind.TK_TypeParameterType:
return FUNDTYPE.FT_VAR;
case TypeKind.TK_ArrayType:
case TypeKind.TK_NullType:
return FUNDTYPE.FT_REF;
case TypeKind.TK_PointerType:
return FUNDTYPE.FT_PTR;
case TypeKind.TK_NullableType:
return FUNDTYPE.FT_STRUCT;
default:
return FUNDTYPE.FT_NONE;
}
}
public ConstValKind constValKind()
{
if (isPointerLike())
{
return ConstValKind.IntPtr;
}
switch (fundType())
{
case FUNDTYPE.FT_I8:
case FUNDTYPE.FT_U8:
return ConstValKind.Long;
case FUNDTYPE.FT_STRUCT:
// Here we can either have a decimal type, or an enum
// whose fundamental type is decimal.
Debug.Assert((getAggregate().IsEnum() && getAggregate().GetUnderlyingType().getPredefType() == PredefinedType.PT_DECIMAL)
|| (isPredefined() && getPredefType() == PredefinedType.PT_DATETIME)
|| (isPredefined() && getPredefType() == PredefinedType.PT_DECIMAL));
if (isPredefined() && getPredefType() == PredefinedType.PT_DATETIME)
{
return ConstValKind.Long;
}
return ConstValKind.Decimal;
case FUNDTYPE.FT_REF:
if (isPredefined() && getPredefType() == PredefinedType.PT_STRING)
{
return ConstValKind.String;
}
else
{
return ConstValKind.IntPtr;
}
case FUNDTYPE.FT_R4:
return ConstValKind.Float;
case FUNDTYPE.FT_R8:
return ConstValKind.Double;
case FUNDTYPE.FT_I1:
return ConstValKind.Boolean;
default:
return ConstValKind.Int;
}
}
public CType underlyingType()
{
if (IsAggregateType() && getAggregate().IsEnum())
return getAggregate().GetUnderlyingType();
return this;
}
////////////////////////////////////////////////////////////////////////////////
// Strips off ArrayType, ParameterModifierType, PointerType, PinnedType and optionally NullableType
// and returns the result.
public CType GetNakedType(bool fStripNub)
{
for (CType type = this; ;)
{
switch (type.GetTypeKind())
{
default:
return type;
case TypeKind.TK_NullableType:
if (!fStripNub)
return type;
type = type.GetBaseOrParameterOrElementType();
break;
case TypeKind.TK_ArrayType:
case TypeKind.TK_ParameterModifierType:
case TypeKind.TK_PointerType:
type = type.GetBaseOrParameterOrElementType();
break;
}
}
}
public AggregateSymbol GetNakedAgg()
{
return GetNakedAgg(false);
}
private AggregateSymbol GetNakedAgg(bool fStripNub)
{
CType type = GetNakedType(fStripNub);
if (type != null && type.IsAggregateType())
return type.AsAggregateType().getAggregate();
return null;
}
public AggregateSymbol getAggregate()
{
Debug.Assert(IsAggregateType());
return AsAggregateType().GetOwningAggregate();
}
public CType StripNubs()
{
CType type;
for (type = this; type.IsNullableType(); type = type.AsNullableType().GetUnderlyingType())
;
return type;
}
public CType StripNubs(out int pcnub)
{
pcnub = 0;
CType type;
for (type = this; type.IsNullableType(); type = type.AsNullableType().GetUnderlyingType())
(pcnub)++;
return type;
}
public bool isDelegateType()
{
return (IsAggregateType() && getAggregate().IsDelegate());
}
////////////////////////////////////////////////////////////////////////////////
// A few types are considered "simple" types for purposes of conversions and so
// on. They are the fundamental types the compiler knows about for operators and
// conversions.
public bool isSimpleType()
{
return (isPredefined() &&
PredefinedTypeFacts.IsSimpleType(getPredefType()));
}
public bool isSimpleOrEnum()
{
return isSimpleType() || isEnumType();
}
public bool isSimpleOrEnumOrString()
{
return isSimpleType() || isPredefType(PredefinedType.PT_STRING) || isEnumType();
}
private bool isPointerLike()
{
return IsPointerType() || isPredefType(PredefinedType.PT_INTPTR) || isPredefType(PredefinedType.PT_UINTPTR);
}
////////////////////////////////////////////////////////////////////////////////
// A few types are considered "numeric" types. They are the fundamental number
// types the compiler knows about for operators and conversions.
public bool isNumericType()
{
return (isPredefined() &&
PredefinedTypeFacts.IsNumericType(getPredefType()));
}
public bool isStructOrEnum()
{
return (IsAggregateType() && (getAggregate().IsStruct() || getAggregate().IsEnum())) || IsNullableType();
}
public bool isStructType()
{
return IsAggregateType() && getAggregate().IsStruct() || IsNullableType();
}
public bool isEnumType()
{
return (IsAggregateType() && getAggregate().IsEnum());
}
public bool isInterfaceType()
{
return (IsAggregateType() && getAggregate().IsInterface());
}
public bool isClassType()
{
return (IsAggregateType() && getAggregate().IsClass());
}
public AggregateType underlyingEnumType()
{
Debug.Assert(isEnumType());
return getAggregate().GetUnderlyingType();
}
public bool isUnsigned()
{
if (IsAggregateType())
{
AggregateType sym = AsAggregateType();
if (sym.isEnumType())
{
sym = sym.underlyingEnumType();
}
if (sym.isPredefined())
{
PredefinedType pt = sym.getPredefType();
return pt == PredefinedType.PT_UINTPTR || pt == PredefinedType.PT_BYTE || (pt >= PredefinedType.PT_USHORT && pt <= PredefinedType.PT_ULONG);
}
else
{
return false;
}
}
else
{
return IsPointerType();
}
}
public bool isUnsafe()
{
// Pointer types are the only unsafe types.
// Note that generics may not be instantiated with pointer types
return (this != null && (IsPointerType() || (IsArrayType() && AsArrayType().GetElementType().isUnsafe())));
}
public bool isPredefType(PredefinedType pt)
{
if (IsAggregateType())
return AsAggregateType().getAggregate().IsPredefined() && AsAggregateType().getAggregate().GetPredefType() == pt;
return (IsVoidType() && pt == PredefinedType.PT_VOID);
}
public bool isPredefined()
{
return IsAggregateType() && getAggregate().IsPredefined();
}
public PredefinedType getPredefType()
{
//ASSERT(isPredefined());
return getAggregate().GetPredefType();
}
////////////////////////////////////////////////////////////////////////////////
// Is this type System.TypedReference or System.ArgIterator?
// (used for errors because these types can't go certain places)
public bool isSpecialByRefType()
{
// ArgIterator, TypedReference and RuntimeArgumentHandle are not supported.
return false;
}
public bool isStaticClass()
{
AggregateSymbol agg = GetNakedAgg(false);
if (agg == null)
return false;
if (!agg.IsStatic())
return false;
return true;
}
public bool computeManagedType(SymbolLoader symbolLoader)
{
if (IsVoidType())
return false;
switch (fundType())
{
case FUNDTYPE.FT_NONE:
case FUNDTYPE.FT_REF:
case FUNDTYPE.FT_VAR:
return true;
case FUNDTYPE.FT_STRUCT:
if (IsNullableType())
{
return true;
}
else
{
AggregateSymbol aggT = getAggregate();
// See if we already know.
if (aggT.IsKnownManagedStructStatus())
{
return aggT.IsManagedStruct();
}
// Generics are always managed.
if (aggT.GetTypeVarsAll().Count > 0)
{
aggT.SetManagedStruct(true);
return true;
}
// If the struct layout has an error, don't recurse its children.
if (aggT.IsLayoutError())
{
aggT.SetUnmanagedStruct(true);
return false;
}
// at this point we can only determine the managed status
// if we have members defined, otherwise we don't know the result
if (symbolLoader != null)
{
for (Symbol ps = aggT.firstChild; ps != null; ps = ps.nextChild)
{
if (ps.IsFieldSymbol() && !ps.AsFieldSymbol().isStatic)
{
CType type = ps.AsFieldSymbol().GetType();
if (type.computeManagedType(symbolLoader))
{
aggT.SetManagedStruct(true);
return true;
}
}
}
aggT.SetUnmanagedStruct(true);
}
return false;
}
default:
return false;
}
}
public CType GetDelegateTypeOfPossibleExpression()
{
if (isPredefType(PredefinedType.PT_G_EXPRESSION))
{
return AsAggregateType().GetTypeArgsThis()[0];
}
return this;
}
// These check for AGGTYPESYMs, TYVARSYMs and others as appropriate.
public bool IsValType()
{
switch (GetTypeKind())
{
case TypeKind.TK_TypeParameterType:
return AsTypeParameterType().IsValueType();
case TypeKind.TK_AggregateType:
return AsAggregateType().getAggregate().IsValueType();
case TypeKind.TK_NullableType:
return true;
default:
return false;
}
}
public bool IsNonNubValType()
{
switch (GetTypeKind())
{
case TypeKind.TK_TypeParameterType:
return AsTypeParameterType().IsNonNullableValueType();
case TypeKind.TK_AggregateType:
return AsAggregateType().getAggregate().IsValueType();
case TypeKind.TK_NullableType:
return false;
default:
return false;
}
}
public bool IsRefType()
{
switch (GetTypeKind())
{
case TypeKind.TK_ArrayType:
case TypeKind.TK_NullType:
return true;
case TypeKind.TK_TypeParameterType:
return AsTypeParameterType().IsReferenceType();
case TypeKind.TK_AggregateType:
return AsAggregateType().getAggregate().IsRefType();
default:
return false;
}
}
// A few types can be the same pointer value and not actually
// be equivalent or convertible (like ANONMETHSYMs)
public bool IsNeverSameType()
{
return IsBoundLambdaType() || IsMethodGroupType() || (IsErrorType() && !AsErrorType().HasParent());
}
}
}
| |
//---------------------------------------------------------------------------
//
// <copyright file="AsyncDataRequest.cs" company="Microsoft">
// Copyright (C) Microsoft Corporation. All rights reserved.
// </copyright>
//
// Description: Defines a request to the async data system.
//
// Specs: http://avalon/connecteddata/M5%20Specs/Asynchronous%20Data%20Model.mht
//
//---------------------------------------------------------------------------
using System;
namespace MS.Internal.Data
{
/// <summary> Type for the work and completion delegates of an AsyncDataRequest </summary>
internal delegate object AsyncRequestCallback(AsyncDataRequest request);
/// <summary> Status of an async data request. </summary>
internal enum AsyncRequestStatus
{
/// <summary> Request has not been started </summary>
Waiting,
/// <summary> Request is in progress </summary>
Working,
/// <summary> Request has been completed </summary>
Completed,
/// <summary> Request was cancelled </summary>
Cancelled,
/// <summary> Request failed </summary>
Failed
}
/// <summary> A request to the async data system. </summary>
internal class AsyncDataRequest
{
//------------------------------------------------------
//
// Constructors
//
//------------------------------------------------------
/// <summary> Constructor </summary>
internal AsyncDataRequest( object bindingState,
AsyncRequestCallback workCallback,
AsyncRequestCallback completedCallback,
params object[] args
)
{
_bindingState = bindingState;
_workCallback = workCallback;
_completedCallback = completedCallback;
_args = args;
}
//------------------------------------------------------
//
// Public Properties
//
//------------------------------------------------------
/* unused by default scheduler. Restore for custom schedulers.
/// <summary> The "user data" from the binding that issued the request. </summary>
public object BindingState { get { return _bindingState; } }
*/
/// <summary> The result of the request (valid when request is completed). </summary>
public object Result { get { return _result; } }
/// <summary> The status of the request. </summary>
public AsyncRequestStatus Status { get { return _status; } }
/// <summary> The exception (for a failed request). </summary>
public Exception Exception { get { return _exception; } }
//------------------------------------------------------
//
// Public Methods
//
//------------------------------------------------------
/// <summary> Run the request's work delegate and return the result. </summary>
/// <remarks>
/// This method should be called synchronously on a worker thread, as it
/// calls the work delegate, which potentially takes a long time. The
/// method sets the status to "Working". It is normally followed by a
/// call to Complete.
///
/// If the request has already been run or has been abandoned, this method
/// returns null.
/// </remarks>
public object DoWork()
{
if (DoBeginWork() && _workCallback != null)
return _workCallback(this);
else
return null;
}
/// <summary>If the request is in the "Waiting" state, return true and
/// set its status to "Working". Otherwise return false.
/// </summary>
/// <remarks>
/// This method is thread-safe and works atomically. Therefore only
/// one thread will be permitted to run the request.
/// </remarks>
public bool DoBeginWork()
{
return ChangeStatus(AsyncRequestStatus.Working);
}
/// <summary> Set the request's status to "Completed", save the result,
/// and call the completed delegate. </summary>
/// <remarks>
/// This method should be called on any thread, after
/// either calling DoWork or performing the work for a request in some
/// other way.
///
/// If the request has already been run or has been abandoned, this method
/// does nothing.
/// </remarks>
public void Complete(object result)
{
if (ChangeStatus(AsyncRequestStatus.Completed))
{
_result = result;
if (_completedCallback != null)
_completedCallback(this);
}
}
/// <summary> Cancel the request.</summary>
/// <remarks> This method can be called from any thread.
/// <p>Calling Cancel does not actually terminate the work being
/// done on behalf of the request, but merely causes the result
/// of that work to be ignored.</p>
/// </remarks>
public void Cancel()
{
ChangeStatus(AsyncRequestStatus.Cancelled);
}
/// <summary> Fail the request because of an exception.</summary>
/// <remarks> This method can be called from any thread. </remarks>
public void Fail(Exception exception)
{
if (ChangeStatus(AsyncRequestStatus.Failed))
{
_exception = exception;
if (_completedCallback != null)
_completedCallback(this);
}
}
//------------------------------------------------------
//
// Internal properties
//
//------------------------------------------------------
/// <summary> The caller-defined arguments. </summary>
internal object[] Args { get { return _args; } }
//------------------------------------------------------
//
// Private methods
//
//------------------------------------------------------
// Change the status to the new status. Return true if this is allowed.
// Do it all atomically.
bool ChangeStatus(AsyncRequestStatus newStatus)
{
bool allowChange = false;
lock(SyncRoot)
{
switch (newStatus)
{
case AsyncRequestStatus.Working:
allowChange = (_status == AsyncRequestStatus.Waiting);
break;
case AsyncRequestStatus.Completed:
allowChange = (_status == AsyncRequestStatus.Working);
break;
case AsyncRequestStatus.Cancelled:
allowChange = (_status == AsyncRequestStatus.Waiting) ||
(_status == AsyncRequestStatus.Working);
break;
case AsyncRequestStatus.Failed:
allowChange = (_status == AsyncRequestStatus.Working);
break;
}
if (allowChange)
_status = newStatus;;
}
return allowChange;
}
//------------------------------------------------------
//
// Private data
//
//------------------------------------------------------
AsyncRequestStatus _status;
object _result;
object _bindingState;
object[] _args;
Exception _exception;
AsyncRequestCallback _workCallback;
AsyncRequestCallback _completedCallback;
object SyncRoot = new object(); // for synchronization
}
/// <summary> Async request to get the value of a property on an item. </summary>
internal class AsyncGetValueRequest : AsyncDataRequest
{
//------------------------------------------------------
//
// Constructors
//
//------------------------------------------------------
/// <summary> Constructor. </summary>
internal AsyncGetValueRequest( object item,
string propertyName,
object bindingState,
AsyncRequestCallback workCallback,
AsyncRequestCallback completedCallback,
params object[] args
)
: base(bindingState, workCallback, completedCallback, args)
{
_item = item;
_propertyName = propertyName;
}
//------------------------------------------------------
//
// Public Properties
//
//------------------------------------------------------
/// <summary> The item whose property is being requested </summary>
public object SourceItem { get { return _item; } }
/* unused by default scheduler. Restore for custom schedulers.
/// <summary> The name of the property being requested </summary>
public string PropertyName { get { return _propertyName; } }
*/
//------------------------------------------------------
//
// Private data
//
//------------------------------------------------------
object _item;
string _propertyName;
}
/// <summary> Async request to set the value of a property on an item. </summary>
internal class AsyncSetValueRequest : AsyncDataRequest
{
//------------------------------------------------------
//
// Constructors
//
//------------------------------------------------------
/// <summary> Constructor. </summary>
internal AsyncSetValueRequest( object item,
string propertyName,
object value,
object bindingState,
AsyncRequestCallback workCallback,
AsyncRequestCallback completedCallback,
params object[] args
)
: base(bindingState, workCallback, completedCallback, args)
{
_item = item;
_propertyName = propertyName;
_value = value;
}
//------------------------------------------------------
//
// Public Properties
//
//------------------------------------------------------
/// <summary> The item whose property is being set </summary>
public object TargetItem { get { return _item; } }
/* unused by default scheduler. Restore for custom schedulers.
/// <summary> The name of the property being set </summary>
public string PropertyName { get { return _propertyName; } }
*/
/// <summary> The new value for the property </summary>
public object Value { get { return _value; } }
//------------------------------------------------------
//
// Private data
//
//------------------------------------------------------
object _item;
string _propertyName;
object _value;
}
}
| |
/*
* Copyright (C) Sony Computer Entertainment America LLC.
* All Rights Reserved.
*/
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Sce.Atf;
using Sce.Atf.Adaptation;
using Sce.Atf.Applications;
using Sce.Atf.Controls;
using Sce.Atf.Dom;
using Sce.Sled.Lua.Dom;
using Sce.Sled.Lua.Resources;
using Sce.Sled.Shared.Controls;
using Sce.Sled.Shared.Dom;
using Sce.Sled.Shared.Services;
using Sce.Sled.Shared.Utilities;
namespace Sce.Sled.Lua
{
[Export(typeof(IInitializable))]
[Export(typeof(ISledLuaCallStackService))]
[Export(typeof(SledLuaCallStackService))]
[PartCreationPolicy(CreationPolicy.Shared)]
sealed class SledLuaCallStackService : IInitializable, ISledLuaCallStackService
{
#region IInitializable Interface
void IInitializable.Initialize()
{
PreviousStackLevel = -1;
m_luaLanguagePlugin = SledServiceInstance.Get<SledLuaLanguagePlugin>();
m_projectService.Created += ProjectServiceCreated;
m_projectService.Opened += ProjectServiceOpened;
m_projectService.Closing += ProjectServiceClosing;
m_debugService = SledServiceInstance.Get<ISledDebugService>();
m_debugService.UpdateBegin += DebugServiceUpdateBegin;
m_debugService.DataReady += DebugServiceDataReady;
m_debugService.UpdateEnd += DebugServiceUpdateEnd;
m_debugService.Disconnected += DebugServiceDisconnected;
m_luaFunctionCursorWatcherService = SledServiceInstance.Get<ISledLuaFunctionCursorWatcherService>();
m_luaFunctionCursorWatcherService.CursorFunctionChanged += LuaFunctionCursorWatcherServiceCursorFunctionChanged;
m_callStackEditor.MouseClick += CallStackEditorMouseClick;
m_callStackEditor.MouseDoubleClick += CallStackEditorMouseDoubleClick;
// Adjust to shortened name if Lua language plugin is the only one loaded
if (m_languagePluginService.Value.Count == 1)
m_callStackEditor.Name = Localization.SledLuaCallStackTitleShort;
//m_liveConnectService = SledServiceInstance.TryGet<ISledLiveConnectService>();
//if (m_liveConnectService != null)
//{
//}
}
#endregion
#region ISledLuaCallStackService Interface
public SledCallStackType this[int iStackLevel]
{
get
{
return
m_callStackCollection == null
? null
: m_callStackCollection.CallStack[iStackLevel];
}
}
public int CurrentStackLevel
{
get { return m_curStackLevel; }
set { PreviousStackLevel = CurrentStackLevel; m_curStackLevel = value; }
}
public int PreviousStackLevel { get; private set; }
/// <summary>
/// Event fired when the call stack is about to be cleared
/// </summary>
public event EventHandler Clearing;
/// <summary>
/// Event fired when the call stack has been cleared
/// </summary>
public event EventHandler Cleared;
/// <summary>
/// Event fired when a new stack level is being added to the call stack
/// </summary>
public event EventHandler<SledLuaCallStackServiceEventArgs> LevelAdding;
/// <summary>
/// Event fired when a new stack level has finished being added to the call stack
/// </summary>
public event EventHandler<SledLuaCallStackServiceEventArgs> LevelAdded;
/// <summary>
/// Event fired when current stack level is changing
/// </summary>
public event EventHandler<SledLuaCallStackServiceEventArgs> StackLevelChanging;
/// <summary>
/// Event fired when current stack level has finished changing
/// </summary>
public event EventHandler<SledLuaCallStackServiceEventArgs> StackLevelChanged;
/// <summary>
/// Event fired when stack level needs to be looked up
/// </summary>
public event EventHandler<SledLuaCallStackServiceEventArgs> StackLevelLookingUp;
/// <summary>
/// Event fired when stack level has finished being looked up
/// </summary>
public event EventHandler<SledLuaCallStackServiceEventArgs> StackLevelLookedUp;
#endregion
#region ISledProjectService Events
private void ProjectServiceCreated(object sender, SledProjectServiceProjectEventArgs e)
{
CreateCallStackCollection();
}
private void ProjectServiceOpened(object sender, SledProjectServiceProjectEventArgs e)
{
CreateCallStackCollection();
}
private void ProjectServiceClosing(object sender, SledProjectServiceProjectEventArgs e)
{
DestroyCallStackCollection();
}
#endregion
#region ISledDebugService Events
private void DebugServiceUpdateBegin(object sender, SledDebugServiceBreakpointEventArgs e)
{
//SendLiveConnectCallStackClear(m_liveConnectService);
}
private void DebugServiceDataReady(object sender, SledDebugServiceEventArgs e)
{
var typeCode = (Scmp.LuaTypeCodes)e.Scmp.TypeCode;
switch (typeCode)
{
case Scmp.LuaTypeCodes.LuaCallStackBegin:
RemoteTargetCallStackClear();
break;
case Scmp.LuaTypeCodes.LuaCallStack:
{
var var = m_debugService.GetScmpBlob<Scmp.LuaCallStack>();
var node = new DomNode(SledSchema.SledCallStackType.Type);
var cs = node.As<SledCallStackType>();
cs.File = SledUtil.FixSlashes(var.RelScriptPath);
cs.CurrentLine = var.CurrentLine;
cs.LineDefined = var.LineDefined;
cs.LineEnd = var.LastLineDefined;
cs.Function = m_luaFunctionParserService.Value.LookUpFunction(var.FunctionName);
cs.Level = var.StackLevel;
cs.NodeCanBeLookedUp = true;
cs.NodeNeedsLookedUp = (cs.Level != 0);
cs.IsCursorInFunction = (cs.Level == 0);
RemoteTargetCallStackNew(cs);
}
break;
case Scmp.LuaTypeCodes.LuaCallStackEnd:
break;
case Scmp.LuaTypeCodes.LuaCallStackLookupBegin:
break;
case Scmp.LuaTypeCodes.LuaCallStackLookup:
{
var scmp = m_debugService.GetScmpBlob<Scmp.LuaCallStackLookup>();
int iLevel = scmp.StackLevel;
// Save this so the call stack GUI knows where it is
CurrentStackLevel = iLevel;
// Find existing callstack entry at iLevel and update
// it to not need to be looked up anymore
m_callStackCollection.CallStack[iLevel].NodeNeedsLookedUp = false;
}
break;
case Scmp.LuaTypeCodes.LuaCallStackLookupEnd:
{
var cssea = new SledLuaCallStackServiceEventArgs(PreviousStackLevel, CurrentStackLevel);
// Fire event indicating stack level has finished being looked up
StackLevelLookedUp.Raise(this, cssea);
// Fire event indicating stack level has changed
StackLevelChanged.Raise(this, cssea);
}
break;
}
}
private void DebugServiceUpdateEnd(object sender, SledDebugServiceBreakpointEventArgs e)
{
m_callStackEditor.View = m_callStackCollection;
m_callStackCollection.ValidationEnded();
}
private void DebugServiceDisconnected(object sender, SledDebugServiceEventArgs e)
{
RemoteTargetCallStackClear();
}
#endregion
#region ISledLuaFunctionCursorWatcherService Events
private void LuaFunctionCursorWatcherServiceCursorFunctionChanged(object sender, SledLuaFunctionCursorWatcherServiceEventArgs e)
{
// Don't care if not connected to a target
if (m_debugService.IsDisconnected)
return;
if (m_callStackCollection == null)
return;
try
{
m_callStackCollection.ValidationBeginning();
// Indicate to matching callstack function that the cursor is there
foreach (var cs in m_callStackCollection.CallStack)
{
cs.IsCursorInFunction = IsMatchingCallStackFunction(cs, e.File, e.Function);
}
m_callStackEditor.View = null;
m_callStackEditor.View = m_callStackCollection;
}
finally
{
m_callStackCollection.ValidationEnded();
}
}
#endregion
#region Member Methods
private void CreateCallStackCollection()
{
var root =
new DomNode(
SledSchema.SledCallStackListType.Type,
SledLuaSchema.SledLuaCallStackRootElement);
m_callStackCollection = root.As<SledCallStackListType>();
m_callStackCollection.Name =
m_projectService.ProjectName +
Resources.Resource.Space +
Resources.Resource.LuaCallStack;
m_callStackEditor.View = m_callStackCollection;
}
private void DestroyCallStackCollection()
{
m_callStackEditor.View = null;
m_callStackCollection.CallStack.Clear();
m_callStackCollection = null;
}
private void RemoteTargetCallStackNew(SledCallStackType cs)
{
m_callStackCollection.ValidationBeginning();
// Event args indicating new stack level #
var cssea = new SledLuaCallStackServiceEventArgs(-1, cs.Level);
// Fire event signalling a new stack level is being added
LevelAdding.Raise(this, cssea);
// Add new call stack level
m_callStackCollection.CallStack.Add(cs);
// Fire event signalling a new stack level has finished being added
LevelAdded.Raise(this, cssea);
}
private void RemoteTargetCallStackClear()
{
// Fire clearing event
Clearing.Raise(this, EventArgs.Empty);
// Reset
CurrentStackLevel = 0;
// Clear call stack window
m_callStackEditor.View = null;
// Remote items from the collection
if (m_callStackCollection != null)
m_callStackCollection.CallStack.Clear();
// Rebind with a context
m_callStackEditor.View = m_callStackCollection;
// Fire cleared event
Cleared.Raise(this, EventArgs.Empty);
}
private void CallStackEditorMouseClick(object sender, MouseEventArgs e)
{
var editor = sender.As<SledLuaCallStackEditor>();
if (editor == null)
return;
var obj = editor.GetItemAt(e.Location);
if (obj == null)
return;
if (!obj.Is<SledCallStackType>())
return;
var cs = obj.As<SledCallStackType>();
// Don't continue if already showing this level
if (cs.Level == CurrentStackLevel)
return;
// Create event args (cs.Level is new level
// and m_iCurrentStackLevel is old level)
var cssea =
new SledLuaCallStackServiceEventArgs(
CurrentStackLevel,
cs.Level);
// Fire event indicating stack level is changing
StackLevelChanging.Raise(this, cssea);
// See if we have the data or not and look it up if we don't
if (cs.NodeCanBeLookedUp && cs.NodeNeedsLookedUp)
{
// Send message
m_debugService.SendScmp(
new Scmp.LuaCallStackLookupPerform(
m_luaLanguagePlugin.LanguageId,
(Int16)cs.Level));
// Fire event indicating the stack level has to be looked up
StackLevelLookingUp.Raise(this, cssea);
}
else
{
// Store level since we switched
CurrentStackLevel = cs.Level;
// Fire event indicating stack level has changed
StackLevelChanged.Raise(this, cssea);
}
}
private void CallStackEditorMouseDoubleClick(object sender, MouseEventArgs e)
{
var editor = sender.As<SledLuaCallStackEditor>();
if (editor == null)
return;
var obj = editor.GetItemAt(e.Location);
if (obj == null)
return;
if (!obj.Is<SledCallStackType>())
return;
var cs = obj.As<SledCallStackType>();
var szAbsPath =
SledUtil.GetAbsolutePath(
cs.File,
m_projectService.AssetDirectory);
if (!File.Exists(szAbsPath))
return;
// Jump to line
m_gotoService.GotoLine(szAbsPath, cs.CurrentLine, false);
}
private static bool IsMatchingCallStackFunction(SledCallStackType cs, SledProjectFilesFileType file, SledLuaFunctionType function)
{
if (function == null)
return false;
return
((cs.LineDefined == function.LineDefined) &&
(cs.LineEnd == function.LastLineDefined) &&
(string.Compare(cs.File, file.Path, StringComparison.OrdinalIgnoreCase) == 0) &&
(string.Compare(cs.Function, function.Name, StringComparison.OrdinalIgnoreCase) == 0));
}
#endregion
private int m_curStackLevel;
private ISledDebugService m_debugService;
private SledLuaLanguagePlugin m_luaLanguagePlugin;
private ISledLuaFunctionCursorWatcherService m_luaFunctionCursorWatcherService;
private SledCallStackListType m_callStackCollection;
#pragma warning disable 649 // Field is never assigned
[Import]
private SledLuaCallStackEditor m_callStackEditor;
[Import]
private ISledGotoService m_gotoService;
[Import]
private ISledProjectService m_projectService;
[Import]
private Lazy<ISledLanguagePluginService> m_languagePluginService;
[Import]
private Lazy<ISledLuaFunctionParserService> m_luaFunctionParserService;
#pragma warning restore 649
#region Private Classes
[Export(typeof(SledLuaCallStackEditor))]
[Export(typeof(IContextMenuCommandProvider))]
[PartCreationPolicy(CreationPolicy.Shared)]
private class SledLuaCallStackEditor : SledTreeListViewEditor, IContextMenuCommandProvider
{
[ImportingConstructor]
public SledLuaCallStackEditor()
: base(
Localization.SledLuaCallStackTitle,
null,
SledCallStackListType.TheColumnNames,
TreeListView.Style.List,
StandardControlGroup.Right)
{
AllowDebugFreeze = true;
// Keep the items sorted in the order they were added
TreeListView.NodeSorter = new CallstackNodeSorter();
}
#region Implementation of IContextMenuCommandProvider
public IEnumerable<object> GetCommands(object context, object target)
{
if (!ReferenceEquals(context, TreeListViewAdapter.View))
yield break;
var clicked = target.As<SledCallStackType>();
if (clicked == null)
yield break;
yield return StandardCommand.EditCopy;
}
#endregion
#region SledTreeListViewEditor Overrides
protected override string GetCopyText()
{
if ((TreeListViewAdapter == null) ||
(!TreeListViewAdapter.Selection.Any()))
return string.Empty;
const string tab = "\t";
const string indicator = ">";
const string space = " ";
var sb = new StringBuilder();
var items = TreeListViewAdapter.Selection.AsIEnumerable<SledCallStackType>();
foreach (var item in items)
{
sb.Append(item.IsCursorInFunction ? indicator : space);
sb.Append(tab);
sb.Append(item.Function);
sb.Append(tab);
sb.Append(item.File);
sb.Append(tab);
sb.Append(item.CurrentLine);
sb.Append(Environment.NewLine);
}
return sb.ToString();
}
#endregion
private class CallstackNodeSorter : IComparer<TreeListView.Node>
{
public int Compare(TreeListView.Node x, TreeListView.Node y)
{
if ((x == null) && (y == null))
return 0;
if (x == null)
return 1;
if (y == null)
return -1;
if (ReferenceEquals(x, y))
return 0;
return -1;
}
}
}
#endregion
}
public class SledLuaCallStackServiceEventArgs : EventArgs
{
public SledLuaCallStackServiceEventArgs(int oldLevel, int newLevel)
{
OldLevel = oldLevel;
NewLevel = newLevel;
}
public int OldLevel { get; private set; }
public int NewLevel { get; private set; }
}
interface ISledLuaCallStackService
{
/// <summary>
/// Access the call stack of a particular stack level
/// </summary>
/// <param name="iStackLevel">Stack level</param>
/// <returns>Call stack of particular stack level</returns>
SledCallStackType this[int iStackLevel] { get; }
/// <summary>
/// Obtain the current call stack level
/// </summary>
int CurrentStackLevel { get; }
/// <summary>
/// Event fired when the call stack is about to be cleared
/// </summary>
event EventHandler Clearing;
/// <summary>
/// Event fired when the call stack has been cleared
/// </summary>
event EventHandler Cleared;
/// <summary>
/// Event fired when a new stack level is being added to the call stack
/// </summary>
event EventHandler<SledLuaCallStackServiceEventArgs> LevelAdding;
/// <summary>
/// Event fired when a new stack level has finished being added to the call stack
/// </summary>
event EventHandler<SledLuaCallStackServiceEventArgs> LevelAdded;
/// <summary>
/// Event fired when current stack level is changing
/// </summary>
event EventHandler<SledLuaCallStackServiceEventArgs> StackLevelChanging;
/// <summary>
/// Event fired when current stack level has finished changing
/// </summary>
event EventHandler<SledLuaCallStackServiceEventArgs> StackLevelChanged;
/// <summary>
/// Event fired when stack level needs to be looked up
/// </summary>
event EventHandler<SledLuaCallStackServiceEventArgs> StackLevelLookingUp;
/// <summary>
/// Event fired when stack level has finished being looked up
/// </summary>
event EventHandler<SledLuaCallStackServiceEventArgs> StackLevelLookedUp;
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
/*============================================================
**
** Class: ObjectReader
**
**
** Purpose: DeSerializes Binary Wire format
**
**
===========================================================*/
namespace System.Runtime.Serialization.Formatters.Binary {
using System;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Collections;
using System.Text;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Messaging;
using System.Runtime.Serialization;
using System.Security.Permissions;
using System.Security;
using System.Diagnostics;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Diagnostics.Contracts;
using StackCrawlMark = System.Threading.StackCrawlMark;
internal sealed class ObjectReader
{
// System.Serializer information
internal Stream m_stream;
internal ISurrogateSelector m_surrogates;
internal StreamingContext m_context;
internal ObjectManager m_objectManager;
internal InternalFE formatterEnums;
internal SerializationBinder m_binder;
// Top object and headers
internal long topId;
internal bool bSimpleAssembly = false;
internal Object handlerObject;
internal Object m_topObject;
internal Header[] headers;
internal HeaderHandler handler;
internal SerObjectInfoInit serObjectInfoInit;
internal IFormatterConverter m_formatterConverter;
// Stack of Object ParseRecords
internal SerStack stack;
// ValueType Fixup Stack
private SerStack valueFixupStack;
// Cross AppDomain
internal Object[] crossAppDomainArray; //Set by the BinaryFormatter
//MethodCall and MethodReturn are handled special for perf reasons
private bool bFullDeserialization;
#if FEATURE_REMOTING
private bool bMethodCall;
private bool bMethodReturn;
private BinaryMethodCall binaryMethodCall;
private BinaryMethodReturn binaryMethodReturn;
private bool bIsCrossAppDomain;
#endif
private static FileIOPermission sfileIOPermission = new FileIOPermission(PermissionState.Unrestricted);
private SerStack ValueFixupStack
{
get {
if (valueFixupStack == null)
valueFixupStack = new SerStack("ValueType Fixup Stack");
return valueFixupStack;
}
}
internal Object TopObject{
get {
return m_topObject;
}
set {
m_topObject = value;
if (m_objectManager != null)
m_objectManager.TopObject = value;
}
}
#if FEATURE_REMOTING
internal void SetMethodCall(BinaryMethodCall binaryMethodCall)
{
bMethodCall = true;
this.binaryMethodCall = binaryMethodCall;
}
internal void SetMethodReturn(BinaryMethodReturn binaryMethodReturn)
{
bMethodReturn = true;
this.binaryMethodReturn = binaryMethodReturn;
}
#endif
internal ObjectReader(Stream stream, ISurrogateSelector selector, StreamingContext context, InternalFE formatterEnums, SerializationBinder binder)
{
if (stream == null)
{
throw new ArgumentNullException("stream", Environment.GetResourceString("ArgumentNull_Stream"));
}
Contract.EndContractBlock();
SerTrace.Log(this, "Constructor ISurrogateSelector ", ((selector == null) ? "null selector " : "selector present"));
m_stream=stream;
m_surrogates = selector;
m_context = context;
m_binder = binder;
#if !FEATURE_PAL && FEATURE_SERIALIZATION
// This is a hack to allow us to write a type-limiting deserializer
// when we know exactly what type to expect at the head of the
// object graph.
if (m_binder != null) {
ResourceReader.TypeLimitingDeserializationBinder tldBinder = m_binder as ResourceReader.TypeLimitingDeserializationBinder;
if (tldBinder != null)
tldBinder.ObjectReader = this;
}
#endif // !FEATURE_PAL && FEATURE_SERIALIZATION
this.formatterEnums = formatterEnums;
//SerTrace.Log( this, "Constructor formatterEnums.FEtopObject ",formatterEnums.FEtopObject);
}
#if FEATURE_REMOTING
[System.Security.SecurityCritical] // auto-generated
internal Object Deserialize(HeaderHandler handler, __BinaryParser serParser, bool fCheck, bool isCrossAppDomain, IMethodCallMessage methodCallMessage) {
if (serParser == null)
throw new ArgumentNullException("serParser", Environment.GetResourceString("ArgumentNull_WithParamName", serParser));
Contract.EndContractBlock();
#if _DEBUG
SerTrace.Log( this, "Deserialize Entry handler", handler);
#endif
bFullDeserialization = false;
TopObject = null;
topId = 0;
#if FEATURE_REMOTING
bMethodCall = false;
bMethodReturn = false;
bIsCrossAppDomain = isCrossAppDomain;
#endif
bSimpleAssembly = (formatterEnums.FEassemblyFormat == FormatterAssemblyStyle.Simple);
if (fCheck)
{
CodeAccessPermission.Demand(PermissionType.SecuritySerialization);
}
this.handler = handler;
Contract.Assert(!bFullDeserialization, "we just set bFullDeserialization to false");
// Will call back to ParseObject, ParseHeader for each object found
serParser.Run();
#if _DEBUG
SerTrace.Log( this, "Deserialize Finished Parsing DoFixups");
#endif
if (bFullDeserialization)
m_objectManager.DoFixups();
#if FEATURE_REMOTING
if (!bMethodCall && !bMethodReturn)
#endif
{
if (TopObject == null)
throw new SerializationException(Environment.GetResourceString("Serialization_TopObject"));
//if TopObject has a surrogate then the actual object may be changed during special fixup
//So refresh it using topID.
if (HasSurrogate(TopObject.GetType()) && topId != 0)//Not yet resolved
TopObject = m_objectManager.GetObject(topId);
if (TopObject is IObjectReference)
{
TopObject = ((IObjectReference)TopObject).GetRealObject(m_context);
}
}
SerTrace.Log( this, "Deserialize Exit ",TopObject);
if (bFullDeserialization)
{
m_objectManager.RaiseDeserializationEvent(); // This will raise both IDeserialization and [OnDeserialized] events
}
// Return the headers if there is a handler
if (handler != null)
{
handlerObject = handler(headers);
}
#if FEATURE_REMOTING
if (bMethodCall)
{
Object[] methodCallArray = TopObject as Object[];
TopObject = binaryMethodCall.ReadArray(methodCallArray, handlerObject);
}
else if (bMethodReturn)
{
Object[] methodReturnArray = TopObject as Object[];
TopObject = binaryMethodReturn.ReadArray(methodReturnArray, methodCallMessage, handlerObject);
}
#endif
return TopObject;
}
#endif
#if !FEATURE_REMOTING
internal Object Deserialize(HeaderHandler handler, __BinaryParser serParser, bool fCheck)
{
if (serParser == null)
throw new ArgumentNullException("serParser", Environment.GetResourceString("ArgumentNull_WithParamName", serParser));
Contract.EndContractBlock();
#if _DEBUG
SerTrace.Log( this, "Deserialize Entry handler", handler);
#endif
bFullDeserialization = false;
TopObject = null;
topId = 0;
#if FEATURE_REMOTING
bMethodCall = false;
bMethodReturn = false;
bIsCrossAppDomain = isCrossAppDomain;
#endif
bSimpleAssembly = (formatterEnums.FEassemblyFormat == FormatterAssemblyStyle.Simple);
if (fCheck)
{
CodeAccessPermission.Demand(PermissionType.SecuritySerialization);
}
this.handler = handler;
if (bFullDeserialization)
{
// Reinitialize
#if FEATURE_REMOTING
m_objectManager = new ObjectManager(m_surrogates, m_context, false, bIsCrossAppDomain);
#else
m_objectManager = new ObjectManager(m_surrogates, m_context, false, false);
#endif
serObjectInfoInit = new SerObjectInfoInit();
}
// Will call back to ParseObject, ParseHeader for each object found
serParser.Run();
#if _DEBUG
SerTrace.Log( this, "Deserialize Finished Parsing DoFixups");
#endif
if (bFullDeserialization)
m_objectManager.DoFixups();
#if FEATURE_REMOTING
if (!bMethodCall && !bMethodReturn)
#endif
{
if (TopObject == null)
throw new SerializationException(Environment.GetResourceString("Serialization_TopObject"));
//if TopObject has a surrogate then the actual object may be changed during special fixup
//So refresh it using topID.
if (HasSurrogate(TopObject.GetType()) && topId != 0)//Not yet resolved
TopObject = m_objectManager.GetObject(topId);
if (TopObject is IObjectReference)
{
TopObject = ((IObjectReference)TopObject).GetRealObject(m_context);
}
}
SerTrace.Log( this, "Deserialize Exit ",TopObject);
if (bFullDeserialization)
{
m_objectManager.RaiseDeserializationEvent(); // This will raise both IDeserialization and [OnDeserialized] events
}
// Return the headers if there is a handler
if (handler != null)
{
handlerObject = handler(headers);
}
#if FEATURE_REMOTING
if (bMethodCall)
{
Object[] methodCallArray = TopObject as Object[];
TopObject = binaryMethodCall.ReadArray(methodCallArray, handlerObject);
}
else if (bMethodReturn)
{
Object[] methodReturnArray = TopObject as Object[];
TopObject = binaryMethodReturn.ReadArray(methodReturnArray, methodCallMessage, handlerObject);
}
#endif
return TopObject;
}
#endif
[System.Security.SecurityCritical] // auto-generated
private bool HasSurrogate(Type t){
if (m_surrogates == null)
return false;
ISurrogateSelector notUsed;
return m_surrogates.GetSurrogate(t, m_context, out notUsed) != null;
}
[System.Security.SecurityCritical] // auto-generated
private void CheckSerializable(Type t)
{
if (!t.IsSerializable && !HasSurrogate(t))
throw new SerializationException(String.Format(CultureInfo.InvariantCulture, Environment.GetResourceString("Serialization_NonSerType"),
t.FullName, t.Assembly.FullName));
}
[System.Security.SecurityCritical] // auto-generated
private void InitFullDeserialization()
{
bFullDeserialization = true;
stack = new SerStack("ObjectReader Object Stack");
#if FEATURE_REMOTING
m_objectManager = new ObjectManager(m_surrogates, m_context, false, bIsCrossAppDomain);
#else
m_objectManager = new ObjectManager(m_surrogates, m_context, false, false);
#endif
if (m_formatterConverter == null)
m_formatterConverter = new FormatterConverter();
}
internal Object CrossAppDomainArray(int index)
{
Contract.Assert((index < crossAppDomainArray.Length),
"[System.Runtime.Serialization.Formatters.BinaryObjectReader index out of range for CrossAppDomainArray]");
return crossAppDomainArray[index];
}
[System.Security.SecurityCritical] // auto-generated
internal ReadObjectInfo CreateReadObjectInfo(Type objectType)
{
return ReadObjectInfo.Create(objectType, m_surrogates, m_context, m_objectManager, serObjectInfoInit, m_formatterConverter, bSimpleAssembly);
}
[System.Security.SecurityCritical] // auto-generated
internal ReadObjectInfo CreateReadObjectInfo(Type objectType, String[] memberNames, Type[] memberTypes)
{
return ReadObjectInfo.Create(objectType, memberNames, memberTypes, m_surrogates, m_context, m_objectManager, serObjectInfoInit, m_formatterConverter, bSimpleAssembly);
}
// Main Parse routine, called by the XML Parse Handlers in XMLParser and also called internally to
[System.Security.SecurityCritical] // auto-generated
internal void Parse(ParseRecord pr)
{
#if _DEBUG
SerTrace.Log( this, "Parse");
stack.Dump();
pr.Dump();
#endif
switch (pr.PRparseTypeEnum)
{
case InternalParseTypeE.SerializedStreamHeader:
ParseSerializedStreamHeader(pr);
break;
case InternalParseTypeE.SerializedStreamHeaderEnd:
ParseSerializedStreamHeaderEnd(pr);
break;
case InternalParseTypeE.Object:
ParseObject(pr);
break;
case InternalParseTypeE.ObjectEnd:
ParseObjectEnd(pr);
break;
case InternalParseTypeE.Member:
ParseMember(pr);
break;
case InternalParseTypeE.MemberEnd:
ParseMemberEnd(pr);
break;
case InternalParseTypeE.Body:
case InternalParseTypeE.BodyEnd:
case InternalParseTypeE.Envelope:
case InternalParseTypeE.EnvelopeEnd:
break;
case InternalParseTypeE.Empty:
default:
throw new SerializationException(Environment.GetResourceString("Serialization_XMLElement", pr.PRname));
}
}
// Styled ParseError output
private void ParseError(ParseRecord processing, ParseRecord onStack)
{
#if _DEBUG
SerTrace.Log( this, " ParseError ",processing," ",onStack);
#endif
throw new SerializationException(Environment.GetResourceString("Serialization_ParseError",onStack.PRname+" "+((Enum)onStack.PRparseTypeEnum) + " "+processing.PRname+" "+((Enum)processing.PRparseTypeEnum)));
}
// Parse the SerializedStreamHeader element. This is the first element in the stream if present
private void ParseSerializedStreamHeader(ParseRecord pr)
{
#if _DEBUG
SerTrace.Log( this, "SerializedHeader ",pr);
#endif
stack.Push(pr);
}
// Parse the SerializedStreamHeader end element. This is the last element in the stream if present
private void ParseSerializedStreamHeaderEnd(ParseRecord pr)
{
#if _DEBUG
SerTrace.Log( this, "SerializedHeaderEnd ",pr);
#endif
stack.Pop();
}
#if FEATURE_REMOTING
private bool IsRemoting {
get {
//return (m_context.State & (StreamingContextStates.Persistence|StreamingContextStates.File|StreamingContextStates.Clone)) == 0;
return (bMethodCall || bMethodReturn);
}
}
[System.Security.SecurityCritical] // auto-generated
internal void CheckSecurity(ParseRecord pr)
{
InternalST.SoapAssert(pr!=null, "[BinaryObjectReader.CheckSecurity]pr!=null");
Type t = pr.PRdtType;
if ((object)t != null){
if( IsRemoting){
if (typeof(MarshalByRefObject).IsAssignableFrom(t))
throw new ArgumentException(Environment.GetResourceString("Serialization_MBRAsMBV", t.FullName));
FormatterServices.CheckTypeSecurity(t, formatterEnums.FEsecurityLevel);
}
}
}
#endif
// New object encountered in stream
[System.Security.SecurityCritical] // auto-generated
private void ParseObject(ParseRecord pr)
{
#if _DEBUG
SerTrace.Log( this, "ParseObject Entry ");
#endif
if (!bFullDeserialization)
InitFullDeserialization();
if (pr.PRobjectPositionEnum == InternalObjectPositionE.Top)
topId = pr.PRobjectId;
if (pr.PRparseTypeEnum == InternalParseTypeE.Object)
{
stack.Push(pr); // Nested objects member names are already on stack
}
if (pr.PRobjectTypeEnum == InternalObjectTypeE.Array)
{
ParseArray(pr);
#if _DEBUG
SerTrace.Log( this, "ParseObject Exit, ParseArray ");
#endif
return;
}
// If the Type is null, this means we have a typeload issue
// mark the object with TypeLoadExceptionHolder
if ((object)pr.PRdtType == null)
{
pr.PRnewObj = new TypeLoadExceptionHolder(pr.PRkeyDt);
return;
}
if (Object.ReferenceEquals(pr.PRdtType, Converter.typeofString))
{
// String as a top level object
if (pr.PRvalue != null)
{
pr.PRnewObj = pr.PRvalue;
if (pr.PRobjectPositionEnum == InternalObjectPositionE.Top)
{
#if _DEBUG
SerTrace.Log( this, "ParseObject String as top level, Top Object Resolved");
#endif
TopObject = pr.PRnewObj;
//stack.Pop();
return;
}
else
{
#if _DEBUG
SerTrace.Log( this, "ParseObject String as an object");
#endif
stack.Pop();
RegisterObject(pr.PRnewObj, pr, (ParseRecord)stack.Peek());
return;
}
}
else
{
// xml Doesn't have the value until later
return;
}
}
else {
CheckSerializable(pr.PRdtType);
#if FEATURE_REMOTING
if (IsRemoting && formatterEnums.FEsecurityLevel != TypeFilterLevel.Full)
pr.PRnewObj = FormatterServices.GetSafeUninitializedObject(pr.PRdtType);
else
#endif
pr.PRnewObj = FormatterServices.GetUninitializedObject(pr.PRdtType);
// Run the OnDeserializing methods
m_objectManager.RaiseOnDeserializingEvent(pr.PRnewObj);
}
if (pr.PRnewObj == null)
throw new SerializationException(Environment.GetResourceString("Serialization_TopObjectInstantiate",pr.PRdtType));
if (pr.PRobjectPositionEnum == InternalObjectPositionE.Top)
{
#if _DEBUG
SerTrace.Log( this, "ParseObject Top Object Resolved ",pr.PRnewObj.GetType());
#endif
TopObject = pr.PRnewObj;
}
if (pr.PRobjectInfo == null)
pr.PRobjectInfo = ReadObjectInfo.Create(pr.PRdtType, m_surrogates, m_context, m_objectManager, serObjectInfoInit, m_formatterConverter, bSimpleAssembly);
#if FEATURE_REMOTING
CheckSecurity(pr);
#endif
#if _DEBUG
SerTrace.Log( this, "ParseObject Exit ");
#endif
}
// End of object encountered in stream
[System.Security.SecurityCritical] // auto-generated
private void ParseObjectEnd(ParseRecord pr)
{
#if _DEBUG
SerTrace.Log( this, "ParseObjectEnd Entry ",pr.Trace());
#endif
ParseRecord objectPr = (ParseRecord)stack.Peek();
if (objectPr == null)
objectPr = pr;
//Contract.Assert(objectPr != null, "[System.Runtime.Serialization.Formatters.ParseObjectEnd]objectPr != null");
#if _DEBUG
SerTrace.Log( this, "ParseObjectEnd objectPr ",objectPr.Trace());
#endif
if (objectPr.PRobjectPositionEnum == InternalObjectPositionE.Top)
{
#if _DEBUG
SerTrace.Log( this, "ParseObjectEnd Top Object dtType ",objectPr.PRdtType);
#endif
if (Object.ReferenceEquals(objectPr.PRdtType, Converter.typeofString))
{
#if _DEBUG
SerTrace.Log( this, "ParseObjectEnd Top String");
#endif
objectPr.PRnewObj = objectPr.PRvalue;
TopObject = objectPr.PRnewObj;
return;
}
}
stack.Pop();
ParseRecord parentPr = (ParseRecord)stack.Peek();
if (objectPr.PRnewObj == null)
return;
if (objectPr.PRobjectTypeEnum == InternalObjectTypeE.Array)
{
if (objectPr.PRobjectPositionEnum == InternalObjectPositionE.Top)
{
#if _DEBUG
SerTrace.Log( this, "ParseObjectEnd Top Object (Array) Resolved");
#endif
TopObject = objectPr.PRnewObj;
}
#if _DEBUG
SerTrace.Log( this, "ParseArray RegisterObject ",objectPr.PRobjectId," ",objectPr.PRnewObj.GetType());
#endif
RegisterObject(objectPr.PRnewObj, objectPr, parentPr);
return;
}
objectPr.PRobjectInfo.PopulateObjectMembers(objectPr.PRnewObj, objectPr.PRmemberData);
// Registration is after object is populated
if ((!objectPr.PRisRegistered) && (objectPr.PRobjectId > 0))
{
#if _DEBUG
SerTrace.Log( this, "ParseObject Register Object ",objectPr.PRobjectId," ",objectPr.PRnewObj.GetType());
#endif
RegisterObject(objectPr.PRnewObj, objectPr, parentPr);
}
if (objectPr.PRisValueTypeFixup)
{
#if _DEBUG
SerTrace.Log( this, "ParseObjectEnd ValueTypeFixup ",objectPr.PRnewObj.GetType());
#endif
ValueFixup fixup = (ValueFixup)ValueFixupStack.Pop(); //Value fixup
fixup.Fixup(objectPr, parentPr); // Value fixup
}
if (objectPr.PRobjectPositionEnum == InternalObjectPositionE.Top)
{
#if _DEBUG
SerTrace.Log( this, "ParseObjectEnd Top Object Resolved ",objectPr.PRnewObj.GetType());
#endif
TopObject = objectPr.PRnewObj;
}
objectPr.PRobjectInfo.ObjectEnd();
#if _DEBUG
SerTrace.Log( this, "ParseObjectEnd Exit ",objectPr.PRnewObj.GetType()," id: ",objectPr.PRobjectId);
#endif
}
// Array object encountered in stream
[System.Security.SecurityCritical] // auto-generated
private void ParseArray(ParseRecord pr)
{
SerTrace.Log( this, "ParseArray Entry");
long genId = pr.PRobjectId;
if (pr.PRarrayTypeEnum == InternalArrayTypeE.Base64)
{
SerTrace.Log( this, "ParseArray bin.base64 ",pr.PRvalue.Length," ",pr.PRvalue);
// ByteArray
if (pr.PRvalue.Length > 0)
pr.PRnewObj = Convert.FromBase64String(pr.PRvalue);
else
pr.PRnewObj = new Byte[0];
if (stack.Peek() == pr)
{
SerTrace.Log( this, "ParseArray, bin.base64 has been stacked");
stack.Pop();
}
if (pr.PRobjectPositionEnum == InternalObjectPositionE.Top)
{
TopObject = pr.PRnewObj;
}
ParseRecord parentPr = (ParseRecord)stack.Peek();
// Base64 can be registered at this point because it is populated
SerTrace.Log( this, "ParseArray RegisterObject ",pr.PRobjectId," ",pr.PRnewObj.GetType());
RegisterObject(pr.PRnewObj, pr, parentPr);
}
else if ((pr.PRnewObj != null) && Converter.IsWriteAsByteArray(pr.PRarrayElementTypeCode))
{
// Primtive typed Array has already been read
if (pr.PRobjectPositionEnum == InternalObjectPositionE.Top)
{
TopObject = pr.PRnewObj;
}
ParseRecord parentPr = (ParseRecord)stack.Peek();
// Primitive typed array can be registered at this point because it is populated
SerTrace.Log( this, "ParseArray RegisterObject ",pr.PRobjectId," ",pr.PRnewObj.GetType());
RegisterObject(pr.PRnewObj, pr, parentPr);
}
else if ((pr.PRarrayTypeEnum == InternalArrayTypeE.Jagged) || (pr.PRarrayTypeEnum == InternalArrayTypeE.Single))
{
// Multidimensional jagged array or single array
SerTrace.Log( this, "ParseArray Before Jagged,Simple create ",pr.PRarrayElementType," ",pr.PRlengthA[0]);
bool bCouldBeValueType = true;
if ((pr.PRlowerBoundA == null) || (pr.PRlowerBoundA[0] == 0))
{
if (Object.ReferenceEquals(pr.PRarrayElementType, Converter.typeofString))
{
pr.PRobjectA = new String[pr.PRlengthA[0]];
pr.PRnewObj = pr.PRobjectA;
bCouldBeValueType = false;
}
else if (Object.ReferenceEquals(pr.PRarrayElementType, Converter.typeofObject))
{
pr.PRobjectA = new Object[pr.PRlengthA[0]];
pr.PRnewObj = pr.PRobjectA;
bCouldBeValueType = false;
}
else if ((object)pr.PRarrayElementType != null) {
pr.PRnewObj = Array.UnsafeCreateInstance(pr.PRarrayElementType, pr.PRlengthA[0]);
}
pr.PRisLowerBound = false;
}
else
{
if ((object)pr.PRarrayElementType != null) {
pr.PRnewObj = Array.UnsafeCreateInstance(pr.PRarrayElementType, pr.PRlengthA, pr.PRlowerBoundA);
}
pr.PRisLowerBound = true;
}
if (pr.PRarrayTypeEnum == InternalArrayTypeE.Single)
{
if (!pr.PRisLowerBound && (Converter.IsWriteAsByteArray(pr.PRarrayElementTypeCode)))
{
pr.PRprimitiveArray = new PrimitiveArray(pr.PRarrayElementTypeCode, (Array)pr.PRnewObj);
}
else if (bCouldBeValueType && (object)pr.PRarrayElementType != null)
{
if (!pr.PRarrayElementType.IsValueType && !pr.PRisLowerBound)
pr.PRobjectA = (Object[])pr.PRnewObj;
}
}
SerTrace.Log( this, "ParseArray Jagged,Simple Array ",pr.PRnewObj.GetType());
// For binary, headers comes in as an array of header objects
if (pr.PRobjectPositionEnum == InternalObjectPositionE.Headers)
{
SerTrace.Log( this, "ParseArray header array");
headers = (Header[])pr.PRnewObj;
}
pr.PRindexMap = new int[1];
}
else if (pr.PRarrayTypeEnum == InternalArrayTypeE.Rectangular)
{
// Rectangle array
pr.PRisLowerBound = false;
if (pr.PRlowerBoundA != null)
{
for (int i=0; i<pr.PRrank; i++)
{
if (pr.PRlowerBoundA[i] != 0)
pr.PRisLowerBound = true;
}
}
if ((object)pr.PRarrayElementType != null){
if (!pr.PRisLowerBound)
pr.PRnewObj = Array.UnsafeCreateInstance(pr.PRarrayElementType, pr.PRlengthA);
else
pr.PRnewObj = Array.UnsafeCreateInstance(pr.PRarrayElementType, pr.PRlengthA, pr.PRlowerBoundA);
}
SerTrace.Log( this, "ParseArray Rectangle Array ",pr.PRnewObj.GetType()," lower Bound ",pr.PRisLowerBound);
// Calculate number of items
int sum = 1;
for (int i=0; i<pr.PRrank; i++)
{
sum = sum*pr.PRlengthA[i];
}
pr.PRindexMap = new int[pr.PRrank];
pr.PRrectangularMap = new int[pr.PRrank];
pr.PRlinearlength = sum;
}
else
throw new SerializationException(Environment.GetResourceString("Serialization_ArrayType",((Enum)pr.PRarrayTypeEnum)));
#if FEATURE_REMOTING
CheckSecurity(pr);
#endif
SerTrace.Log( this, "ParseArray Exit");
}
// Builds a map for each item in an incoming rectangle array. The map specifies where the item is placed in the output Array Object
private void NextRectangleMap(ParseRecord pr)
{
// For each invocation, calculate the next rectangular array position
// example
// indexMap 0 [0,0,0]
// indexMap 1 [0,0,1]
// indexMap 2 [0,0,2]
// indexMap 3 [0,0,3]
// indexMap 4 [0,1,0]
for (int irank = pr.PRrank-1; irank>-1; irank--)
{
// Find the current or lower dimension which can be incremented.
if (pr.PRrectangularMap[irank] < pr.PRlengthA[irank]-1)
{
// The current dimension is at maximum. Increase the next lower dimension by 1
pr.PRrectangularMap[irank]++;
if (irank < pr.PRrank-1)
{
// The current dimension and higher dimensions are zeroed.
for (int i = irank+1; i<pr.PRrank; i++)
pr.PRrectangularMap[i] = 0;
}
Array.Copy(pr.PRrectangularMap, pr.PRindexMap, pr.PRrank);
break;
}
}
}
// Array object item encountered in stream
[System.Security.SecurityCritical] // auto-generated
private void ParseArrayMember(ParseRecord pr)
{
SerTrace.Log( this, "ParseArrayMember Entry");
ParseRecord objectPr = (ParseRecord)stack.Peek();
// Set up for inserting value into correct array position
if (objectPr.PRarrayTypeEnum == InternalArrayTypeE.Rectangular)
{
if (objectPr.PRmemberIndex > 0)
NextRectangleMap(objectPr); // Rectangle array, calculate position in array
if (objectPr.PRisLowerBound)
{
for (int i=0; i<objectPr.PRrank; i++)
{
objectPr.PRindexMap[i] = objectPr.PRrectangularMap[i] + objectPr.PRlowerBoundA[i];
}
}
}
else
{
if (!objectPr.PRisLowerBound)
{
objectPr.PRindexMap[0] = objectPr.PRmemberIndex; // Zero based array
}
else
objectPr.PRindexMap[0] = objectPr.PRlowerBoundA[0]+objectPr.PRmemberIndex; // Lower Bound based array
}
IndexTraceMessage("ParseArrayMember isLowerBound "+objectPr.PRisLowerBound+" indexMap ", objectPr.PRindexMap);
// Set Array element according to type of element
if (pr.PRmemberValueEnum == InternalMemberValueE.Reference)
{
// Object Reference
// See if object has already been instantiated
Object refObj = m_objectManager.GetObject(pr.PRidRef);
if (refObj == null)
{
// Object not instantiated
// Array fixup manager
IndexTraceMessage("ParseArrayMember Record Fixup "+objectPr.PRnewObj.GetType(), objectPr.PRindexMap);
int[] fixupIndex = new int[objectPr.PRrank];
Array.Copy(objectPr.PRindexMap, 0, fixupIndex, 0, objectPr.PRrank);
SerTrace.Log( this, "ParseArrayMember RecordArrayElementFixup objectId ",objectPr.PRobjectId," idRef ",pr.PRidRef);
m_objectManager.RecordArrayElementFixup(objectPr.PRobjectId, fixupIndex, pr.PRidRef);
}
else
{
IndexTraceMessage("ParseArrayMember SetValue ObjectReference "+objectPr.PRnewObj.GetType()+" "+refObj, objectPr.PRindexMap);
if (objectPr.PRobjectA != null)
objectPr.PRobjectA[objectPr.PRindexMap[0]] = refObj;
else
((Array)objectPr.PRnewObj).SetValue(refObj, objectPr.PRindexMap); // Object has been instantiated
}
}
else if (pr.PRmemberValueEnum == InternalMemberValueE.Nested)
{
//Set up dtType for ParseObject
SerTrace.Log( this, "ParseArrayMember Nested ");
if ((object)pr.PRdtType == null)
{
pr.PRdtType = objectPr.PRarrayElementType;
}
ParseObject(pr);
stack.Push(pr);
if ((object)objectPr.PRarrayElementType != null) {
if ((objectPr.PRarrayElementType.IsValueType) && (pr.PRarrayElementTypeCode == InternalPrimitiveTypeE.Invalid))
{
#if _DEBUG
SerTrace.Log( "ParseArrayMember ValueType ObjectPr ",objectPr.PRnewObj," index ",objectPr.PRmemberIndex);
#endif
pr.PRisValueTypeFixup = true; //Valuefixup
ValueFixupStack.Push(new ValueFixup((Array)objectPr.PRnewObj, objectPr.PRindexMap)); //valuefixup
}
else
{
#if _DEBUG
SerTrace.Log( "ParseArrayMember SetValue Nested, memberIndex ",objectPr.PRmemberIndex);
IndexTraceMessage("ParseArrayMember SetValue Nested ContainerObject "+objectPr.PRnewObj.GetType()+" "+objectPr.PRnewObj+" item Object "+pr.PRnewObj+" index ", objectPr.PRindexMap);
stack.Dump();
SerTrace.Log( "ParseArrayMember SetValue Nested ContainerObject objectPr ",objectPr.Trace());
SerTrace.Log( "ParseArrayMember SetValue Nested ContainerObject pr ",pr.Trace());
#endif
if (objectPr.PRobjectA != null)
objectPr.PRobjectA[objectPr.PRindexMap[0]] = pr.PRnewObj;
else
((Array)objectPr.PRnewObj).SetValue(pr.PRnewObj, objectPr.PRindexMap);
}
}
}
else if (pr.PRmemberValueEnum == InternalMemberValueE.InlineValue)
{
if ((Object.ReferenceEquals(objectPr.PRarrayElementType, Converter.typeofString)) || (Object.ReferenceEquals(pr.PRdtType, Converter.typeofString)))
{
// String in either a string array, or a string element of an object array
ParseString(pr, objectPr);
IndexTraceMessage("ParseArrayMember SetValue String "+objectPr.PRnewObj.GetType()+" "+pr.PRvalue, objectPr.PRindexMap);
if (objectPr.PRobjectA != null)
objectPr.PRobjectA[objectPr.PRindexMap[0]] = (Object)pr.PRvalue;
else
((Array)objectPr.PRnewObj).SetValue((Object)pr.PRvalue, objectPr.PRindexMap);
}
else if (objectPr.PRisArrayVariant)
{
// Array of type object
if (pr.PRkeyDt == null)
throw new SerializationException(Environment.GetResourceString("Serialization_ArrayTypeObject"));
Object var = null;
if (Object.ReferenceEquals(pr.PRdtType, Converter.typeofString))
{
ParseString(pr, objectPr);
var = pr.PRvalue;
}
else if (Object.ReferenceEquals(pr.PRdtTypeCode, InternalPrimitiveTypeE.Invalid))
{
CheckSerializable(pr.PRdtType);
// Not nested and invalid, so it is an empty object
#if FEATURE_REMOTING
if (IsRemoting && formatterEnums.FEsecurityLevel != TypeFilterLevel.Full)
var = FormatterServices.GetSafeUninitializedObject(pr.PRdtType);
else
#endif
var = FormatterServices.GetUninitializedObject(pr.PRdtType);
}
else
{
if (pr.PRvarValue != null)
var = pr.PRvarValue;
else
var = Converter.FromString(pr.PRvalue, pr.PRdtTypeCode);
}
IndexTraceMessage("ParseArrayMember SetValue variant or Object "+objectPr.PRnewObj.GetType()+" var "+var+" indexMap ", objectPr.PRindexMap);
if (objectPr.PRobjectA != null)
objectPr.PRobjectA[objectPr.PRindexMap[0]] = var;
else
((Array)objectPr.PRnewObj).SetValue(var, objectPr.PRindexMap); // Primitive type
}
else
{
// Primitive type
if (objectPr.PRprimitiveArray != null)
{
// Fast path for Soap primitive arrays. Binary was handled in the BinaryParser
objectPr.PRprimitiveArray.SetValue(pr.PRvalue, objectPr.PRindexMap[0]);
}
else
{
Object var = null;
if (pr.PRvarValue != null)
var = pr.PRvarValue;
else
var = Converter.FromString(pr.PRvalue, objectPr.PRarrayElementTypeCode);
SerTrace.Log( this, "ParseArrayMember SetValue Primitive pr.PRvalue "+var," elementTypeCode ",((Enum)objectPr.PRdtTypeCode));
IndexTraceMessage("ParseArrayMember SetValue Primitive "+objectPr.PRnewObj.GetType()+" var: "+var+" varType "+var.GetType(), objectPr.PRindexMap);
if (objectPr.PRobjectA != null)
{
SerTrace.Log( this, "ParseArrayMember SetValue Primitive predefined array "+objectPr.PRobjectA.GetType());
objectPr.PRobjectA[objectPr.PRindexMap[0]] = var;
}
else
((Array)objectPr.PRnewObj).SetValue(var, objectPr.PRindexMap); // Primitive type
SerTrace.Log( this, "ParseArrayMember SetValue Primitive after");
}
}
}
else if (pr.PRmemberValueEnum == InternalMemberValueE.Null)
{
SerTrace.Log( "ParseArrayMember Null item ",pr.PRmemberIndex," nullCount ",pr.PRnullCount);
objectPr.PRmemberIndex += pr.PRnullCount-1; //also incremented again below
}
else
ParseError(pr, objectPr);
#if _DEBUG
SerTrace.Log( "ParseArrayMember increment memberIndex ",objectPr.PRmemberIndex," ",objectPr.Trace());
#endif
objectPr.PRmemberIndex++;
SerTrace.Log( "ParseArrayMember Exit");
}
[System.Security.SecurityCritical] // auto-generated
private void ParseArrayMemberEnd(ParseRecord pr)
{
SerTrace.Log( this, "ParseArrayMemberEnd");
// If this is a nested array object, then pop the stack
if (pr.PRmemberValueEnum == InternalMemberValueE.Nested)
{
ParseObjectEnd(pr);
}
}
// Object member encountered in stream
[System.Security.SecurityCritical] // auto-generated
private void ParseMember(ParseRecord pr)
{
SerTrace.Log( this, "ParseMember Entry ");
ParseRecord objectPr = (ParseRecord)stack.Peek();
String objName = null;
if (objectPr != null)
objName = objectPr.PRname;
#if _DEBUG
SerTrace.Log( this, "ParseMember ",objectPr.PRobjectId," ",pr.PRname);
SerTrace.Log( this, "ParseMember objectPr ",objectPr.Trace());
SerTrace.Log( this, "ParseMember pr ",pr.Trace());
#endif
switch (pr.PRmemberTypeEnum)
{
case InternalMemberTypeE.Item:
ParseArrayMember(pr);
return;
case InternalMemberTypeE.Field:
break;
}
//if ((pr.PRdtType == null) && !objectPr.PRobjectInfo.isSi)
if (((object)pr.PRdtType == null) && objectPr.PRobjectInfo.isTyped)
{
SerTrace.Log( this, "ParseMember pr.PRdtType null and not isSi");
pr.PRdtType = objectPr.PRobjectInfo.GetType(pr.PRname);
if ((object)pr.PRdtType != null)
pr.PRdtTypeCode = Converter.ToCode(pr.PRdtType);
}
if (pr.PRmemberValueEnum == InternalMemberValueE.Null)
{
// Value is Null
SerTrace.Log( this, "ParseMember null member: ",pr.PRname);
SerTrace.Log( this, "AddValue 1");
objectPr.PRobjectInfo.AddValue(pr.PRname, null, ref objectPr.PRsi, ref objectPr.PRmemberData);
}
else if (pr.PRmemberValueEnum == InternalMemberValueE.Nested)
{
SerTrace.Log( this, "ParseMember Nested Type member: ",pr.PRname," objectPr.PRnewObj ",objectPr.PRnewObj);
ParseObject(pr);
stack.Push(pr);
SerTrace.Log( this, "AddValue 2 ",pr.PRnewObj," is value type ",pr.PRnewObj.GetType().IsValueType);
if ((pr.PRobjectInfo != null) && ((object)pr.PRobjectInfo.objectType != null) && (pr.PRobjectInfo.objectType.IsValueType))
{
SerTrace.Log( "ParseMember ValueType ObjectPr ",objectPr.PRnewObj," memberName ",pr.PRname," nested object ",pr.PRnewObj);
pr.PRisValueTypeFixup = true; //Valuefixup
ValueFixupStack.Push(new ValueFixup(objectPr.PRnewObj, pr.PRname, objectPr.PRobjectInfo));//valuefixup
}
else
{
SerTrace.Log( this, "AddValue 2A ");
objectPr.PRobjectInfo.AddValue(pr.PRname, pr.PRnewObj, ref objectPr.PRsi, ref objectPr.PRmemberData);
}
}
else if (pr.PRmemberValueEnum == InternalMemberValueE.Reference)
{
SerTrace.Log( this, "ParseMember Reference Type member: ",pr.PRname);
// See if object has already been instantiated
Object refObj = m_objectManager.GetObject(pr.PRidRef);
if (refObj == null)
{
SerTrace.Log( this, "ParseMember RecordFixup: ",pr.PRname);
SerTrace.Log( this, "AddValue 3");
objectPr.PRobjectInfo.AddValue(pr.PRname, null, ref objectPr.PRsi, ref objectPr.PRmemberData);
objectPr.PRobjectInfo.RecordFixup(objectPr.PRobjectId, pr.PRname, pr.PRidRef); // Object not instantiated
}
else
{
SerTrace.Log( this, "ParseMember Referenced Object Known ",pr.PRname," ",refObj);
SerTrace.Log( this, "AddValue 5");
objectPr.PRobjectInfo.AddValue(pr.PRname, refObj, ref objectPr.PRsi, ref objectPr.PRmemberData);
}
}
else if (pr.PRmemberValueEnum == InternalMemberValueE.InlineValue)
{
// Primitive type or String
SerTrace.Log( this, "ParseMember primitive or String member: ",pr.PRname);
if (Object.ReferenceEquals(pr.PRdtType, Converter.typeofString))
{
ParseString(pr, objectPr);
SerTrace.Log( this, "AddValue 6");
objectPr.PRobjectInfo.AddValue(pr.PRname, pr.PRvalue, ref objectPr.PRsi, ref objectPr.PRmemberData);
}
else if (pr.PRdtTypeCode == InternalPrimitiveTypeE.Invalid)
{
// The member field was an object put the value is Inline either bin.Base64 or invalid
if (pr.PRarrayTypeEnum == InternalArrayTypeE.Base64)
{
SerTrace.Log( this, "AddValue 7");
objectPr.PRobjectInfo.AddValue(pr.PRname, Convert.FromBase64String(pr.PRvalue), ref objectPr.PRsi, ref objectPr.PRmemberData);
}
else if (Object.ReferenceEquals(pr.PRdtType, Converter.typeofObject))
throw new SerializationException(Environment.GetResourceString("Serialization_TypeMissing", pr.PRname));
else
{
SerTrace.Log( this, "Object Class with no memberInfo data Member "+pr.PRname+" type "+pr.PRdtType);
ParseString(pr, objectPr); // Register the object if it has an objectId
// Object Class with no memberInfo data
// only special case where AddValue is needed?
if (Object.ReferenceEquals(pr.PRdtType, Converter.typeofSystemVoid))
{
SerTrace.Log( this, "AddValue 9");
objectPr.PRobjectInfo.AddValue(pr.PRname, pr.PRdtType, ref objectPr.PRsi, ref objectPr.PRmemberData);
}
else if (objectPr.PRobjectInfo.isSi)
{
// ISerializable are added as strings, the conversion to type is done by the
// ISerializable object
SerTrace.Log( this, "AddValue 10");
objectPr.PRobjectInfo.AddValue(pr.PRname, pr.PRvalue, ref objectPr.PRsi, ref objectPr.PRmemberData);
}
}
}
else
{
Object var = null;
if (pr.PRvarValue != null)
var = pr.PRvarValue;
else
var = Converter.FromString(pr.PRvalue, pr.PRdtTypeCode);
#if _DEBUG
// Not a string, convert the value
SerTrace.Log( this, "ParseMember Converting primitive and storing");
stack.Dump();
SerTrace.Log( this, "ParseMember pr "+pr.Trace());
SerTrace.Log( this, "ParseMember objectPr ",objectPr.Trace());
SerTrace.Log( this, "AddValue 11");
#endif
objectPr.PRobjectInfo.AddValue(pr.PRname, var, ref objectPr.PRsi, ref objectPr.PRmemberData);
}
}
else
ParseError(pr, objectPr);
}
// Object member end encountered in stream
[System.Security.SecurityCritical] // auto-generated
private void ParseMemberEnd(ParseRecord pr)
{
SerTrace.Log( this, "ParseMemberEnd");
switch (pr.PRmemberTypeEnum)
{
case InternalMemberTypeE.Item:
ParseArrayMemberEnd(pr);
return;
case InternalMemberTypeE.Field:
if (pr.PRmemberValueEnum == InternalMemberValueE.Nested)
ParseObjectEnd(pr);
break;
default:
ParseError(pr, (ParseRecord)stack.Peek());
break;
}
}
// Processes a string object by getting an internal ID for it and registering it with the objectManager
[System.Security.SecurityCritical] // auto-generated
private void ParseString(ParseRecord pr, ParseRecord parentPr)
{
SerTrace.Log( this, "ParseString Entry ",pr.PRobjectId," ",pr.PRvalue," ",pr.PRisRegistered);
// Process String class
if ((!pr.PRisRegistered) && (pr.PRobjectId > 0))
{
SerTrace.Log( this, "ParseString RegisterObject ",pr.PRvalue," ",pr.PRobjectId);
// String is treated as an object if it has an id
//m_objectManager.RegisterObject(pr.PRvalue, pr.PRobjectId);
RegisterObject(pr.PRvalue, pr, parentPr, true);
}
}
[System.Security.SecurityCritical] // auto-generated
private void RegisterObject(Object obj, ParseRecord pr, ParseRecord objectPr)
{
RegisterObject(obj, pr, objectPr, false);
}
[System.Security.SecurityCritical] // auto-generated
private void RegisterObject(Object obj, ParseRecord pr, ParseRecord objectPr, bool bIsString)
{
if (!pr.PRisRegistered)
{
pr.PRisRegistered = true;
SerializationInfo si = null;
long parentId = 0;
MemberInfo memberInfo = null;
int[] indexMap = null;
if (objectPr != null)
{
indexMap = objectPr.PRindexMap;
parentId = objectPr.PRobjectId;
if (objectPr.PRobjectInfo != null)
{
if (!objectPr.PRobjectInfo.isSi)
{
// ParentId is only used if there is a memberInfo
memberInfo = objectPr.PRobjectInfo.GetMemberInfo(pr.PRname);
}
}
}
// SerializationInfo is always needed for ISerialization
si = pr.PRsi;
SerTrace.Log( this, "RegisterObject 0bj ",obj," objectId ",pr.PRobjectId," si ", si," parentId ",parentId," memberInfo ",memberInfo, " indexMap "+indexMap);
if (bIsString)
m_objectManager.RegisterString((String)obj, pr.PRobjectId, si, parentId, memberInfo);
else
m_objectManager.RegisterObject(obj, pr.PRobjectId, si, parentId, memberInfo, indexMap);
}
}
// Assigns an internal ID associated with the binary id number
// Older formatters generate ids for valuetypes using a different counter than ref types. Newer ones use
// a single counter, only value types have a negative value. Need a way to handle older formats.
private const int THRESHOLD_FOR_VALUETYPE_IDS = Int32.MaxValue;
private bool bOldFormatDetected = false;
private IntSizedArray valTypeObjectIdTable;
[System.Security.SecurityCritical] // auto-generated
internal long GetId(long objectId)
{
if (!bFullDeserialization)
InitFullDeserialization();
if (objectId > 0)
return objectId;
if (bOldFormatDetected || objectId == -1)
{
// Alarm bells. This is an old format. Deal with it.
bOldFormatDetected = true;
if (valTypeObjectIdTable == null)
valTypeObjectIdTable = new IntSizedArray();
long tempObjId = 0;
if ((tempObjId = valTypeObjectIdTable[(int)objectId]) == 0)
{
tempObjId = THRESHOLD_FOR_VALUETYPE_IDS + objectId;
valTypeObjectIdTable[(int)objectId] = (int)tempObjId;
}
return tempObjId;
}
return -1 * objectId;
}
// Trace which includes a single dimensional int array
[Conditional("SER_LOGGING")]
private void IndexTraceMessage(String message, int[] index)
{
StringBuilder sb = StringBuilderCache.Acquire(10);
sb.Append("[");
for (int i=0; i<index.Length; i++)
{
sb.Append(index[i]);
if (i != index.Length -1)
sb.Append(",");
}
sb.Append("]");
SerTrace.Log( this, message," ", StringBuilderCache.GetStringAndRelease(sb));
}
[System.Security.SecurityCritical] // auto-generated
internal Type Bind(String assemblyString, String typeString)
{
Type type = null;
if (m_binder != null)
type = m_binder.BindToType(assemblyString, typeString);
if ((object)type == null)
type= FastBindToType(assemblyString, typeString);
return type;
}
internal class TypeNAssembly
{
public Type type;
public String assemblyName;
}
NameCache typeCache = new NameCache();
[System.Security.SecurityCritical] // auto-generated
internal Type FastBindToType(String assemblyName, String typeName)
{
Type type = null;
TypeNAssembly entry = (TypeNAssembly)typeCache.GetCachedValue(typeName);
if (entry == null || entry.assemblyName != assemblyName)
{
Assembly assm = null;
if (bSimpleAssembly)
{
try {
sfileIOPermission.Assert();
try {
#if FEATURE_FUSION
assm = ObjectReader.ResolveSimpleAssemblyName(new AssemblyName(assemblyName));
#else // FEATURE_FUSION
Assembly.Load(assemblyName);
#endif // FEATURE_FUSION
}
finally {
CodeAccessPermission.RevertAssert();
}
}
catch(Exception e){
SerTrace.Log( this, "FastBindTypeType ",e.ToString());
}
if (assm == null)
return null;
ObjectReader.GetSimplyNamedTypeFromAssembly(assm, typeName, ref type);
}
else {
try
{
sfileIOPermission.Assert();
try {
assm = Assembly.Load(assemblyName);
}
finally {
CodeAccessPermission.RevertAssert();
}
}
catch (Exception e)
{
SerTrace.Log( this, "FastBindTypeType ",e.ToString());
}
if (assm == null)
return null;
type = FormatterServices.GetTypeFromAssembly(assm, typeName);
}
if ((object)type == null)
return null;
// before adding it to cache, let us do the security check
CheckTypeForwardedTo(assm, type.Assembly, type);
entry = new TypeNAssembly();
entry.type = type;
entry.assemblyName = assemblyName;
typeCache.SetCachedValue(entry);
}
return entry.type;
}
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
private static Assembly ResolveSimpleAssemblyName(AssemblyName assemblyName)
{
StackCrawlMark stackMark = StackCrawlMark.LookForMe;
Assembly assm = RuntimeAssembly.LoadWithPartialNameInternal(assemblyName, null, ref stackMark);
if (assm == null && assemblyName != null)
assm = RuntimeAssembly.LoadWithPartialNameInternal(assemblyName.Name, null, ref stackMark);
return assm;
}
[System.Security.SecurityCritical] // auto-generated
private static void GetSimplyNamedTypeFromAssembly(Assembly assm, string typeName, ref Type type)
{
// Catching any exceptions that could be thrown from a failure on assembly load
// This is necessary, for example, if there are generic parameters that are qualified with a version of the assembly that predates the one available
try
{
type = FormatterServices.GetTypeFromAssembly(assm, typeName);
}
catch (TypeLoadException) { }
catch (FileNotFoundException) { }
catch (FileLoadException) { }
catch (BadImageFormatException) { }
if ((object)type == null)
{
type = Type.GetType(typeName, ObjectReader.ResolveSimpleAssemblyName, new TopLevelAssemblyTypeResolver(assm).ResolveType, false /* throwOnError */);
}
}
private String previousAssemblyString;
private String previousName;
private Type previousType;
//private int hit;
[System.Security.SecurityCritical] // auto-generated
internal Type GetType(BinaryAssemblyInfo assemblyInfo, String name)
{
Type objectType = null;
if (((previousName != null) && (previousName.Length == name.Length) && (previousName.Equals(name))) &&
((previousAssemblyString != null) && (previousAssemblyString.Length == assemblyInfo.assemblyString.Length) &&(previousAssemblyString.Equals(assemblyInfo.assemblyString))))
{
objectType = previousType;
//Console.WriteLine("Hit "+(++hit)+" "+objectType);
}
else
{
objectType = Bind(assemblyInfo.assemblyString, name);
if ((object)objectType == null)
{
Assembly sourceAssembly = assemblyInfo.GetAssembly();
if (bSimpleAssembly)
{
ObjectReader.GetSimplyNamedTypeFromAssembly(sourceAssembly, name, ref objectType);
}
else
{
objectType = FormatterServices.GetTypeFromAssembly(sourceAssembly, name);
}
// here let us do the security check
if (objectType != null)
{
CheckTypeForwardedTo(sourceAssembly, objectType.Assembly, objectType);
}
}
previousAssemblyString = assemblyInfo.assemblyString;
previousName = name;
previousType = objectType;
}
//Console.WriteLine("name "+name+" assembly "+assemblyInfo.assemblyString+" objectType "+objectType);
return objectType;
}
[SecuritySafeCritical]
private static void CheckTypeForwardedTo(Assembly sourceAssembly, Assembly destAssembly, Type resolvedType)
{
if ( !FormatterServices.UnsafeTypeForwardersIsEnabled() && sourceAssembly != destAssembly )
{
// we have a type forward to attribute !
// we can try to see if the dest assembly has less permissionSet
if (!destAssembly.PermissionSet.IsSubsetOf(sourceAssembly.PermissionSet))
{
// let us try to see if typeforwardedfrom is there
// let us hit the cache first
TypeInformation typeInfo = BinaryFormatter.GetTypeInformation(resolvedType);
if (typeInfo.HasTypeForwardedFrom)
{
Assembly typeFowardedFromAssembly = null;
try
{
// if this Assembly.Load failed, we still want to throw security exception
typeFowardedFromAssembly = Assembly.Load(typeInfo.AssemblyString);
}
catch { }
if (typeFowardedFromAssembly != sourceAssembly)
{
// throw security exception
throw new SecurityException() { Demanded = sourceAssembly.PermissionSet };
}
}
else
{
// throw security exception
throw new SecurityException() { Demanded = sourceAssembly.PermissionSet };
}
}
}
}
internal sealed class TopLevelAssemblyTypeResolver
{
private Assembly m_topLevelAssembly;
public TopLevelAssemblyTypeResolver(Assembly topLevelAssembly)
{
m_topLevelAssembly = topLevelAssembly;
}
public Type ResolveType(Assembly assembly, string simpleTypeName, bool ignoreCase)
{
if (assembly == null)
assembly = m_topLevelAssembly;
return assembly.GetType(simpleTypeName, false, ignoreCase);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using NetTopologySuite.Geometries;
using SharpMap.Base;
namespace SharpMap.Rendering.Symbolizer
{
/// <summary>
/// Interface for all classes providing Line symbolization handling routine
/// </summary>
public interface ILineSymbolizeHandler : IDisposableEx
{
/// <summary>
/// Function to symbolize the graphics path to the graphics object
/// </summary>
/// <param name="g">The graphics object</param>
/// <param name="paths">The Paths</param>
void SymbolizePaths(Graphics g, IEnumerable<GraphicsPath> paths);
}
/// <summary>
/// Line symbolize helper class that plainly draws a line.
/// </summary>
public class PlainLineSymbolizeHandler : DisposableObject, ILineSymbolizeHandler
{
/// <summary>
/// Gets or sets the <see cref="Pen"/> to use
/// </summary>
public Pen Line { get; set; }
/// <summary>
/// Function to symbolize the graphics path to the graphics object
/// </summary>
/// <param name="g">The graphics object</param>
/// <param name="path">The Path</param>
public void SymbolizePaths(Graphics g, IEnumerable<GraphicsPath> path)
{
foreach (var graphicsPath in path)
g.DrawPath(Line, graphicsPath);
}
/// <summary>
/// Releases managed resources
/// </summary>
protected override void ReleaseManagedResources()
{
if (Line != null)
Line.Dispose();
base.ReleaseManagedResources();
}
}
/// <summary>
/// Class that symbolizes a path by warping a <see cref="Pattern"/> to the provided graphics path.
/// </summary>
public class WarpedLineSymbolizeHander : DisposableObject, ILineSymbolizeHandler
{
/// <summary>
/// Releases managed resources
/// </summary>
protected override void ReleaseManagedResources()
{
if (Line != null)
Line.Dispose();
if (Fill != null)
Fill.Dispose();
if (Pattern != null)
Pattern.Dispose();
base.ReleaseManagedResources();
}
/// <summary>
/// Gets or sets the <see cref="Pen"/> to draw the graphics path
/// </summary>
public Pen Line { get; set; }
/// <summary>
/// Gets or sets the <see cref="Brush"/> to fill the graphics path
/// </summary>
public Brush Fill { get; set; }
/// <summary>
/// The pattern to warp.
/// </summary>
public GraphicsPath Pattern { get; set; }
/// <summary>
/// Gets or sets the interval with witch to repeat the pattern
/// </summary>
public float Interval { get; set; }
/// <summary>
/// Function to symbolize the graphics path to the graphics object
/// </summary>
/// <param name="g">The graphics object</param>
/// <param name="paths">The paths</param>
public void SymbolizePaths(Graphics g, IEnumerable<GraphicsPath> paths)
{
foreach (var graphicsPath in paths)
{
var clonedPattern = (GraphicsPath)Pattern.Clone();
var warpedPath = WarpPathToPath.Warp(graphicsPath, clonedPattern, true, Interval);
if (warpedPath == null) continue;
if (Fill != null)
g.FillPath(Fill, warpedPath);
if (Line != null)
g.DrawPath(Line, warpedPath);
}
}
}
/// <summary>
/// A Line symbolizer that creates <see cref="GraphicsPath"/>objects in the <see cref="OnRenderInternal"/> function.
/// These graphic paths are symbolized in subsequent symbolize calls.
/// </summary>
public class CachedLineSymbolizer : LineSymbolizer
{
private List<GraphicsPath> _graphicsPaths;
private readonly List<ILineSymbolizeHandler> _lineSymbolizeHandlers;
private readonly ILineSymbolizeHandler _fallback = new PlainLineSymbolizeHandler {Line = new Pen(Color.Black)};
/// <summary>
/// Creates an instance of this class
/// </summary>
public CachedLineSymbolizer()
{
_graphicsPaths = new List<GraphicsPath>();
_lineSymbolizeHandlers = new List<ILineSymbolizeHandler>();
}
/// <summary>
/// Releases managed resources
/// </summary>
protected override void ReleaseManagedResources()
{
if (_graphicsPaths != null)
{
foreach (var graphicsPath in Paths)
graphicsPath.Dispose();
_graphicsPaths = null;
}
if (_lineSymbolizeHandlers != null)
{
foreach (var lineSymbolizeHandler in _lineSymbolizeHandlers)
lineSymbolizeHandler.Dispose();
_lineSymbolizeHandlers.Clear();
}
if (_fallback != null)
_fallback.Dispose();
base.ReleaseManagedResources();
}
/// <summary>
/// Creates a new object that is a copy of the current instance.
/// </summary>
/// <returns>
/// A new object that is a copy of this instance.
/// </returns>
/// <filterpriority>2</filterpriority>
public override object Clone()
{
throw new NotImplementedException();
}
/// <summary>
/// The cached path
/// </summary>
public List<GraphicsPath> Paths
{
get { return _graphicsPaths; }
internal set
{
if (value == null)
throw new ArgumentNullException("value");
_graphicsPaths = value;
}
}
/// <summary>
/// The line symbolizers to apply to the <see cref="Paths"/>.
/// </summary>
public List<ILineSymbolizeHandler> LineSymbolizeHandlers
{
get { return _lineSymbolizeHandlers; }
}
/// <summary>
/// Function that actually renders the linestring
/// </summary>
/// <param name="map"></param>
/// <param name="lineString"></param>
/// <param name="graphics"></param>
protected override void OnRenderInternal(MapViewport map, LineString lineString, Graphics graphics)
{
var gp = new GraphicsPath();
gp.AddLines(VectorRenderer.LimitValues(lineString.TransformToImage(map), VectorRenderer.ExtremeValueLimit));
if (ImmediateMode)
{
var tmp = new List<GraphicsPath>(new[] {gp});
Symbolize(graphics, map, tmp);
}
else
_graphicsPaths.Add(gp);
}
/// <summary>
/// Do not cache the geometries paths
/// </summary>
public bool ImmediateMode { get; set; }
/// <summary>
/// Method to indicate that the symbolizer has to be prepared.
/// </summary>
public override void Begin(Graphics g, MapViewport map, int aproximateNumberOfGeometries)
{
_graphicsPaths = new List<GraphicsPath>(aproximateNumberOfGeometries);
base.Begin(g, map, aproximateNumberOfGeometries);
}
/// <summary>
/// Method to indicate that the symbolizer should do its symbolizer work.
/// </summary>
public override void Symbolize(Graphics g, MapViewport map)
{
Symbolize(g, map, Paths);
}
private void Symbolize(Graphics graphics, MapViewport map, List<GraphicsPath> paths)
{
if (_lineSymbolizeHandlers.Count == 0)
_fallback.SymbolizePaths(graphics, paths);
else
{
foreach (var lineSymbolizeHandler in _lineSymbolizeHandlers)
lineSymbolizeHandler.SymbolizePaths(graphics, paths);
}
}
/// <summary>
/// Method to indicate that the symbolizers work is done and it can clean up.
/// </summary>
public override void End(Graphics g, MapViewport map)
{
if (_graphicsPaths.Count > 0)
_graphicsPaths.Clear();
base.End(g, map);
}
}
}
| |
using System;
using System.Collections.Generic;
using StructureMap.Graph;
using StructureMap.Interceptors;
using StructureMap.Pipeline;
namespace StructureMap.Configuration.DSL.Expressions
{
/// <summary>
/// Expression Builder that has grammars for defining policies at the
/// PluginType level
/// </summary>
public class CreatePluginFamilyExpression<TPluginType>
{
private readonly List<Action<PluginFamily>> _alterations = new List<Action<PluginFamily>>();
private readonly List<Action<PluginGraph>> _children = new List<Action<PluginGraph>>();
private readonly Type _pluginType;
public CreatePluginFamilyExpression(Registry registry, ILifecycle scope)
{
_pluginType = typeof (TPluginType);
registry.alter = graph =>
{
PluginFamily family = graph.Families[_pluginType];
_children.Each(action => action(graph));
_alterations.Each(action => action(family));
};
if (scope != null)
{
lifecycleIs(scope);
}
}
public InstanceExpression<TPluginType> MissingNamedInstanceIs { get { return new InstanceExpression<TPluginType>(i => _alterations.Add(family => family.MissingInstance = i)); } }
/// <summary>
/// Add multiple Instances to this PluginType
/// </summary>
public CreatePluginFamilyExpression<TPluginType> AddInstances(Action<IInstanceExpression<TPluginType>> action)
{
var list = new List<Instance>();
var child = new InstanceExpression<TPluginType>(list.Add);
action(child);
alter = family => list.ForEach(family.AddInstance);
return this;
}
/// <summary>
/// Access to all of the uncommon Instance types
/// </summary>
public CreatePluginFamilyExpression<TPluginType> UseSpecial(Action<IInstanceExpression<TPluginType>> configure)
{
var expression = new InstanceExpression<TPluginType>(Use);
configure(expression);
return this;
}
/// <summary>
/// Access to all of the uncommon Instance types
/// </summary>
public CreatePluginFamilyExpression<TPluginType> AddSpecial(Action<IInstanceExpression<TPluginType>> configure)
{
var expression = new InstanceExpression<TPluginType>(Add);
configure(expression);
return this;
}
/// <summary>
/// Shorthand way of saying Use<>
/// </summary>
public SmartInstance<TConcreteType> Use<TConcreteType>() where TConcreteType : TPluginType
{
// This is *my* team's naming convention for generic parameters
// I know you may not like it, but it's my article so there
var instance = new SmartInstance<TConcreteType>();
registerDefault(instance);
return instance;
}
/// <summary>
/// Use a lambda using the IContext to construct the default instance of the Plugin type
///
/// </summary>
public LambdaInstance<TPluginType> Use(Func<IContext, TPluginType> func)
{
var instance = new LambdaInstance<TPluginType>(func);
registerDefault(instance);
return instance;
}
/// <summary>
/// Use a lambda to construct the default instance of the Plugin type
/// </summary>
public LambdaInstance<TPluginType> Use(Func<TPluginType> func)
{
var instance = new LambdaInstance<TPluginType>(func);
registerDefault(instance);
return instance;
}
/// <summary>
/// Makes the supplied instance the default Instance for
/// TPluginType
/// </summary>
public void Use(Instance instance)
{
registerDefault(instance);
}
/// <summary>
/// Shorthand to say TheDefault.IsThis(@object)
/// </summary>
public ObjectInstance Use(TPluginType @object)
{
var instance = new ObjectInstance(@object);
registerDefault(instance);
return instance;
}
/// <summary>
/// Makes the default instance of TPluginType the named
/// instance
/// </summary>
public ReferencedInstance Use(string instanceName)
{
var instance = new ReferencedInstance(instanceName);
Use(instance);
return instance;
}
/// <summary>
/// Defines a fallback instance in case no default was defined for TPluginType
/// </summary>
public SmartInstance<TConcreteType> UseIfNone<TConcreteType>() where TConcreteType : TPluginType
{
var instance = new SmartInstance<TConcreteType>();
registerFallBack(instance);
return instance;
}
public LambdaInstance<TPluginType> UseIfNone(Func<IContext, TPluginType> func)
{
var instance = new LambdaInstance<TPluginType>(func);
registerFallBack(instance);
return instance;
}
public LambdaInstance<TPluginType> UseIfNone(Func<TPluginType> func)
{
var instance = new LambdaInstance<TPluginType>(func);
registerFallBack(instance);
return instance;
}
/// <summary>
/// Convenience method to mark a PluginFamily as a Singleton
/// </summary>
public CreatePluginFamilyExpression<TPluginType> Singleton()
{
return lifecycleIs(Lifecycles.Singleton);
}
/// <summary>
/// Convenience method to mark a PluginFamily as a Transient
/// </summary>
public CreatePluginFamilyExpression<TPluginType> Transient()
{
return lifecycleIs(Lifecycles.Transient);
}
/// <summary>
/// Register an Action to run against any object of this PluginType immediately after
/// it is created, but before the new object is passed back to the caller
/// </summary>
public CreatePluginFamilyExpression<TPluginType> OnCreationForAll(Action<TPluginType> handler)
{
_children.Add(
graph =>
{
var interceptor = new PluginTypeInterceptor(typeof(TPluginType), (c, o) =>
{
handler((TPluginType)o);
return o;
});
graph.InterceptorLibrary.AddInterceptor(interceptor);
});
return this;
}
/// <summary>
/// Register an Action to run against any object of this PluginType immediately after
/// it is created, but before the new object is passed back to the caller
/// </summary>
public CreatePluginFamilyExpression<TPluginType> OnCreationForAll(Action<IContext, TPluginType> handler)
{
_children.Add(
graph =>
{
Func<IContext, object, object> function = (c, o) =>
{
handler(c, (TPluginType)o);
return o;
};
var interceptor = new PluginTypeInterceptor(typeof(TPluginType), function);
graph.InterceptorLibrary.AddInterceptor(interceptor);
});
return this;
}
/// <summary>
/// Adds an Interceptor to only this PluginType
/// </summary>
public CreatePluginFamilyExpression<TPluginType> InterceptWith(InstanceInterceptor interceptor)
{
_children.Add(
graph =>
{
var typeInterceptor = new PluginTypeInterceptor(typeof (TPluginType),
(c, o) => interceptor.Process(o, c));
graph.InterceptorLibrary.AddInterceptor(typeInterceptor);
});
return this;
}
/// <summary>
/// Register a Func to run against any object of this PluginType immediately after it is created,
/// but before the new object is passed back to the caller. Unlike OnCreationForAll(),
/// EnrichAllWith() gives the the ability to return a different object. Use this method for runtime AOP
/// scenarios or to return a decorator.
/// </summary>
public CreatePluginFamilyExpression<TPluginType> EnrichAllWith(EnrichmentHandler<TPluginType> handler)
{
_children.Add(
graph =>
{
Func<IContext, object, object> function = (context, target) => handler((TPluginType)target);
var interceptor = new PluginTypeInterceptor(typeof(TPluginType), function);
graph.InterceptorLibrary.AddInterceptor(interceptor);
});
return this;
}
/// <summary>
/// Register a Func to run against any object of this PluginType immediately after it is created,
/// but before the new object is passed back to the caller. Unlike OnCreationForAll(),
/// EnrichAllWith() gives the the ability to return a different object. Use this method for runtime AOP
/// scenarios or to return a decorator.
/// </summary>
public CreatePluginFamilyExpression<TPluginType> EnrichAllWith(ContextEnrichmentHandler<TPluginType> handler)
{
_children.Add(
graph =>
{
var interceptor = new PluginTypeInterceptor(typeof(TPluginType),
(c, o) => handler(c, (TPluginType)o));
graph.InterceptorLibrary.AddInterceptor(interceptor);
});
return this;
}
/// <summary>
/// Registers an ILifecycle for this Plugin Type that executes before
/// any object of this PluginType is created. ILifecycle's can be
/// used to create a custom scope
/// </summary>
public CreatePluginFamilyExpression<TPluginType> LifecycleIs(ILifecycle lifecycle)
{
lifecycleIs(lifecycle);
return this;
}
/// <summary>
/// Forces StructureMap to always use a unique instance to
/// stop the "BuildSession" caching
/// </summary>
/// <returns></returns>
public CreatePluginFamilyExpression<TPluginType> AlwaysUnique()
{
return LifecycleIs(new UniquePerRequestLifecycle());
}
/// <summary>
/// Adds the object to to the TPluginType
/// </summary>
public ObjectInstance Add(TPluginType @object)
{
var instance = new ObjectInstance(@object);
Add(instance);
return instance;
}
public SmartInstance<TPluggedType> Add<TPluggedType>()
{
var instance = new SmartInstance<TPluggedType>();
Add(instance);
return instance;
}
/// <summary>
/// Add an Instance to this type created by a Lambda
/// </summary>
public LambdaInstance<TPluginType> Add(Func<IContext, TPluginType> func)
{
var instance = new LambdaInstance<TPluginType>(func);
Add(instance);
return instance;
}
public void Add(Instance instance)
{
alter = f => f.AddInstance(instance);
}
private CreatePluginFamilyExpression<TPluginType> lifecycleIs(ILifecycle lifecycle)
{
alter = family => family.SetScopeTo(lifecycle);
return this;
}
private void registerDefault(Instance instance)
{
alter = family => family.SetDefault(instance);
}
private void registerFallBack(Instance instance)
{
alter = family => family.SetFallback(instance);
}
private Action<PluginFamily> alter
{
set { _alterations.Add(value); }
}
}
}
| |
//
// Copyright (c) 2008-2011, Kenneth Bell
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
namespace DiscUtils.Udf
{
using System.Collections.Generic;
using System.IO;
using DiscUtils.Iso9660;
using DiscUtils.Vfs;
/// <summary>
/// Class for accessing OSTA Universal Disk Format file systems.
/// </summary>
public sealed class UdfReader : VfsFileSystemFacade
{
/// <summary>
/// Initializes a new instance of the UdfReader class.
/// </summary>
/// <param name="data">The stream containing the UDF file system.</param>
public UdfReader(Stream data)
: base(new VfsUdfReader(data))
{
}
/// <summary>
/// Initializes a new instance of the UdfReader class.
/// </summary>
/// <param name="data">The stream containing the UDF file system.</param>
/// <param name="sectorSize">The sector size of the physical media.</param>
public UdfReader(Stream data, int sectorSize)
: base(new VfsUdfReader(data, sectorSize))
{
}
/// <summary>
/// Detects if a stream contains a valid UDF file system.
/// </summary>
/// <param name="data">The stream to inspect.</param>
/// <returns><c>true</c> if the stream contains a UDF file system, else false.</returns>
public static bool Detect(Stream data)
{
if (data.Length < IsoUtilities.SectorSize)
{
return false;
}
long vdpos = 0x8000; // Skip lead-in
byte[] buffer = new byte[IsoUtilities.SectorSize];
bool validDescriptor = true;
bool foundUdfMarker = false;
BaseVolumeDescriptor bvd;
while (validDescriptor)
{
data.Position = vdpos;
int numRead = Utilities.ReadFully(data, buffer, 0, IsoUtilities.SectorSize);
if (numRead != IsoUtilities.SectorSize)
{
break;
}
bvd = new BaseVolumeDescriptor(buffer, 0);
switch (bvd.StandardIdentifier)
{
case "NSR02":
case "NSR03":
foundUdfMarker = true;
break;
case "BEA01":
case "BOOT2":
case "CD001":
case "CDW02":
case "TEA01":
break;
default:
validDescriptor = false;
break;
}
vdpos += IsoUtilities.SectorSize;
}
return foundUdfMarker;
}
/// <summary>
/// Gets UDF extended attributes for a file or directory.
/// </summary>
/// <param name="path">Path to the file or directory.</param>
/// <returns>Array of extended attributes, which may be empty or <c>null</c> if
/// there are no extended attributes.</returns>
public ExtendedAttribute[] GetExtendedAttributes(string path)
{
VfsUdfReader realFs = GetRealFileSystem<VfsUdfReader>();
return realFs.GetExtendedAttributes(path);
}
private sealed class VfsUdfReader : VfsReadOnlyFileSystem<FileIdentifier, File, Directory, UdfContext>
{
private Stream _data;
private uint _sectorSize;
private LogicalVolumeDescriptor _lvd;
private PrimaryVolumeDescriptor _pvd;
public VfsUdfReader(Stream data)
: base(null)
{
_data = data;
if (!UdfReader.Detect(data))
{
throw new InvalidDataException("Stream is not a recognized UDF format");
}
// Try a number of possible sector sizes, from most common.
if (ProbeSectorSize(2048))
{
_sectorSize = 2048;
}
else if (ProbeSectorSize(512))
{
_sectorSize = 512;
}
else if (ProbeSectorSize(4096))
{
_sectorSize = 4096;
}
else if (ProbeSectorSize(1024))
{
_sectorSize = 1024;
}
else
{
throw new InvalidDataException("Unable to detect physical media sector size");
}
Initialize();
}
public VfsUdfReader(Stream data, int sectorSize)
: base(null)
{
_data = data;
_sectorSize = (uint)sectorSize;
if (!UdfReader.Detect(data))
{
throw new InvalidDataException("Stream is not a recognized UDF format");
}
Initialize();
}
public override string FriendlyName
{
get { return "OSTA Universal Disk Format"; }
}
public override string VolumeLabel
{
get { return _lvd.LogicalVolumeIdentifier; }
}
public ExtendedAttribute[] GetExtendedAttributes(string path)
{
List<ExtendedAttribute> result = new List<ExtendedAttribute>();
File file = GetFile(path);
foreach (var record in file.ExtendedAttributes)
{
ImplementationUseExtendedAttributeRecord implRecord = record as ImplementationUseExtendedAttributeRecord;
if (implRecord != null)
{
result.Add(new ExtendedAttribute(implRecord.ImplementationIdentifier.Identifier, implRecord.ImplementationUseData));
}
}
return result.ToArray();
}
protected override File ConvertDirEntryToFile(FileIdentifier dirEntry)
{
return File.FromDescriptor(Context, dirEntry.FileLocation);
}
private void Initialize()
{
Context = new UdfContext()
{
PhysicalPartitions = new Dictionary<ushort, PhysicalPartition>(),
PhysicalSectorSize = (int)_sectorSize,
LogicalPartitions = new List<LogicalPartition>(),
};
IBuffer dataBuffer = new StreamBuffer(_data, Ownership.None);
AnchorVolumeDescriptorPointer avdp = AnchorVolumeDescriptorPointer.FromStream(_data, 256, _sectorSize);
uint sector = avdp.MainDescriptorSequence.Location;
bool terminatorFound = false;
while (!terminatorFound)
{
_data.Position = sector * (long)_sectorSize;
DescriptorTag dt;
if (!DescriptorTag.TryFromStream(_data, out dt))
{
break;
}
switch (dt.TagIdentifier)
{
case TagIdentifier.PrimaryVolumeDescriptor:
_pvd = PrimaryVolumeDescriptor.FromStream(_data, sector, _sectorSize);
break;
case TagIdentifier.ImplementationUseVolumeDescriptor:
// Not used
break;
case TagIdentifier.PartitionDescriptor:
PartitionDescriptor pd = PartitionDescriptor.FromStream(_data, sector, _sectorSize);
if (Context.PhysicalPartitions.ContainsKey(pd.PartitionNumber))
{
throw new IOException("Duplicate partition number reading UDF Partition Descriptor");
}
Context.PhysicalPartitions[pd.PartitionNumber] = new PhysicalPartition(pd, dataBuffer, _sectorSize);
break;
case TagIdentifier.LogicalVolumeDescriptor:
_lvd = LogicalVolumeDescriptor.FromStream(_data, sector, _sectorSize);
break;
case TagIdentifier.UnallocatedSpaceDescriptor:
// Not used for reading
break;
case TagIdentifier.TerminatingDescriptor:
terminatorFound = true;
break;
default:
break;
}
sector++;
}
// Convert logical partition descriptors into actual partition objects
for (int i = 0; i < _lvd.PartitionMaps.Length; ++i)
{
Context.LogicalPartitions.Add(LogicalPartition.FromDescriptor(Context, _lvd, i));
}
byte[] fsdBuffer = UdfUtilities.ReadExtent(Context, _lvd.FileSetDescriptorLocation);
if (DescriptorTag.IsValid(fsdBuffer, 0))
{
FileSetDescriptor fsd = Utilities.ToStruct<FileSetDescriptor>(fsdBuffer, 0);
RootDirectory = (Directory)File.FromDescriptor(Context, fsd.RootDirectoryIcb);
}
}
private bool ProbeSectorSize(int size)
{
if (_data.Length < 257 * (long)size)
{
return false;
}
_data.Position = 256 * (long)size;
DescriptorTag dt;
if (!DescriptorTag.TryFromStream(_data, out dt))
{
return false;
}
return dt.TagIdentifier == TagIdentifier.AnchorVolumeDescriptorPointer
&& dt.TagLocation == 256;
}
}
}
}
| |
// MIT License
//
// Copyright (c) 2009-2017 Luca Piccioni
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
// This file is automatically generated
#pragma warning disable 649, 1572, 1573
// ReSharper disable RedundantUsingDirective
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Security;
using System.Text;
using Khronos;
// ReSharper disable CheckNamespace
// ReSharper disable InconsistentNaming
// ReSharper disable JoinDeclarationAndInitializer
namespace OpenGL
{
public partial class Gl
{
/// <summary>
/// [GL] glWindowPos4dMESA: Binding for glWindowPos4dMESA.
/// </summary>
/// <param name="x">
/// A <see cref="T:double"/>.
/// </param>
/// <param name="y">
/// A <see cref="T:double"/>.
/// </param>
/// <param name="z">
/// A <see cref="T:double"/>.
/// </param>
/// <param name="w">
/// A <see cref="T:double"/>.
/// </param>
[RequiredByFeature("GL_MESA_window_pos")]
public static void WindowPos4MESA(double x, double y, double z, double w)
{
Debug.Assert(Delegates.pglWindowPos4dMESA != null, "pglWindowPos4dMESA not implemented");
Delegates.pglWindowPos4dMESA(x, y, z, w);
LogCommand("glWindowPos4dMESA", null, x, y, z, w );
DebugCheckErrors(null);
}
/// <summary>
/// [GL] glWindowPos4dvMESA: Binding for glWindowPos4dvMESA.
/// </summary>
/// <param name="v">
/// A <see cref="T:double[]"/>.
/// </param>
[RequiredByFeature("GL_MESA_window_pos")]
public static void WindowPos4MESA(double[] v)
{
Debug.Assert(v.Length >= 4);
unsafe {
fixed (double* p_v = v)
{
Debug.Assert(Delegates.pglWindowPos4dvMESA != null, "pglWindowPos4dvMESA not implemented");
Delegates.pglWindowPos4dvMESA(p_v);
LogCommand("glWindowPos4dvMESA", null, v );
}
}
DebugCheckErrors(null);
}
/// <summary>
/// [GL] glWindowPos4fMESA: Binding for glWindowPos4fMESA.
/// </summary>
/// <param name="x">
/// A <see cref="T:float"/>.
/// </param>
/// <param name="y">
/// A <see cref="T:float"/>.
/// </param>
/// <param name="z">
/// A <see cref="T:float"/>.
/// </param>
/// <param name="w">
/// A <see cref="T:float"/>.
/// </param>
[RequiredByFeature("GL_MESA_window_pos")]
public static void WindowPos4MESA(float x, float y, float z, float w)
{
Debug.Assert(Delegates.pglWindowPos4fMESA != null, "pglWindowPos4fMESA not implemented");
Delegates.pglWindowPos4fMESA(x, y, z, w);
LogCommand("glWindowPos4fMESA", null, x, y, z, w );
DebugCheckErrors(null);
}
/// <summary>
/// [GL] glWindowPos4fvMESA: Binding for glWindowPos4fvMESA.
/// </summary>
/// <param name="v">
/// A <see cref="T:float[]"/>.
/// </param>
[RequiredByFeature("GL_MESA_window_pos")]
public static void WindowPos4MESA(float[] v)
{
Debug.Assert(v.Length >= 4);
unsafe {
fixed (float* p_v = v)
{
Debug.Assert(Delegates.pglWindowPos4fvMESA != null, "pglWindowPos4fvMESA not implemented");
Delegates.pglWindowPos4fvMESA(p_v);
LogCommand("glWindowPos4fvMESA", null, v );
}
}
DebugCheckErrors(null);
}
/// <summary>
/// [GL] glWindowPos4iMESA: Binding for glWindowPos4iMESA.
/// </summary>
/// <param name="x">
/// A <see cref="T:int"/>.
/// </param>
/// <param name="y">
/// A <see cref="T:int"/>.
/// </param>
/// <param name="z">
/// A <see cref="T:int"/>.
/// </param>
/// <param name="w">
/// A <see cref="T:int"/>.
/// </param>
[RequiredByFeature("GL_MESA_window_pos")]
public static void WindowPos4MESA(int x, int y, int z, int w)
{
Debug.Assert(Delegates.pglWindowPos4iMESA != null, "pglWindowPos4iMESA not implemented");
Delegates.pglWindowPos4iMESA(x, y, z, w);
LogCommand("glWindowPos4iMESA", null, x, y, z, w );
DebugCheckErrors(null);
}
/// <summary>
/// [GL] glWindowPos4ivMESA: Binding for glWindowPos4ivMESA.
/// </summary>
/// <param name="v">
/// A <see cref="T:int[]"/>.
/// </param>
[RequiredByFeature("GL_MESA_window_pos")]
public static void WindowPos4MESA(int[] v)
{
Debug.Assert(v.Length >= 4);
unsafe {
fixed (int* p_v = v)
{
Debug.Assert(Delegates.pglWindowPos4ivMESA != null, "pglWindowPos4ivMESA not implemented");
Delegates.pglWindowPos4ivMESA(p_v);
LogCommand("glWindowPos4ivMESA", null, v );
}
}
DebugCheckErrors(null);
}
/// <summary>
/// [GL] glWindowPos4sMESA: Binding for glWindowPos4sMESA.
/// </summary>
/// <param name="x">
/// A <see cref="T:short"/>.
/// </param>
/// <param name="y">
/// A <see cref="T:short"/>.
/// </param>
/// <param name="z">
/// A <see cref="T:short"/>.
/// </param>
/// <param name="w">
/// A <see cref="T:short"/>.
/// </param>
[RequiredByFeature("GL_MESA_window_pos")]
public static void WindowPos4MESA(short x, short y, short z, short w)
{
Debug.Assert(Delegates.pglWindowPos4sMESA != null, "pglWindowPos4sMESA not implemented");
Delegates.pglWindowPos4sMESA(x, y, z, w);
LogCommand("glWindowPos4sMESA", null, x, y, z, w );
DebugCheckErrors(null);
}
/// <summary>
/// [GL] glWindowPos4svMESA: Binding for glWindowPos4svMESA.
/// </summary>
/// <param name="v">
/// A <see cref="T:short[]"/>.
/// </param>
[RequiredByFeature("GL_MESA_window_pos")]
public static void WindowPos4MESA(short[] v)
{
Debug.Assert(v.Length >= 4);
unsafe {
fixed (short* p_v = v)
{
Debug.Assert(Delegates.pglWindowPos4svMESA != null, "pglWindowPos4svMESA not implemented");
Delegates.pglWindowPos4svMESA(p_v);
LogCommand("glWindowPos4svMESA", null, v );
}
}
DebugCheckErrors(null);
}
internal static unsafe partial class Delegates
{
[RequiredByFeature("GL_MESA_window_pos")]
[SuppressUnmanagedCodeSecurity]
internal delegate void glWindowPos4dMESA(double x, double y, double z, double w);
[RequiredByFeature("GL_MESA_window_pos")]
[ThreadStatic]
internal static glWindowPos4dMESA pglWindowPos4dMESA;
[RequiredByFeature("GL_MESA_window_pos")]
[SuppressUnmanagedCodeSecurity]
internal delegate void glWindowPos4dvMESA(double* v);
[RequiredByFeature("GL_MESA_window_pos")]
[ThreadStatic]
internal static glWindowPos4dvMESA pglWindowPos4dvMESA;
[RequiredByFeature("GL_MESA_window_pos")]
[SuppressUnmanagedCodeSecurity]
internal delegate void glWindowPos4fMESA(float x, float y, float z, float w);
[RequiredByFeature("GL_MESA_window_pos")]
[ThreadStatic]
internal static glWindowPos4fMESA pglWindowPos4fMESA;
[RequiredByFeature("GL_MESA_window_pos")]
[SuppressUnmanagedCodeSecurity]
internal delegate void glWindowPos4fvMESA(float* v);
[RequiredByFeature("GL_MESA_window_pos")]
[ThreadStatic]
internal static glWindowPos4fvMESA pglWindowPos4fvMESA;
[RequiredByFeature("GL_MESA_window_pos")]
[SuppressUnmanagedCodeSecurity]
internal delegate void glWindowPos4iMESA(int x, int y, int z, int w);
[RequiredByFeature("GL_MESA_window_pos")]
[ThreadStatic]
internal static glWindowPos4iMESA pglWindowPos4iMESA;
[RequiredByFeature("GL_MESA_window_pos")]
[SuppressUnmanagedCodeSecurity]
internal delegate void glWindowPos4ivMESA(int* v);
[RequiredByFeature("GL_MESA_window_pos")]
[ThreadStatic]
internal static glWindowPos4ivMESA pglWindowPos4ivMESA;
[RequiredByFeature("GL_MESA_window_pos")]
[SuppressUnmanagedCodeSecurity]
internal delegate void glWindowPos4sMESA(short x, short y, short z, short w);
[RequiredByFeature("GL_MESA_window_pos")]
[ThreadStatic]
internal static glWindowPos4sMESA pglWindowPos4sMESA;
[RequiredByFeature("GL_MESA_window_pos")]
[SuppressUnmanagedCodeSecurity]
internal delegate void glWindowPos4svMESA(short* v);
[RequiredByFeature("GL_MESA_window_pos")]
[ThreadStatic]
internal static glWindowPos4svMESA pglWindowPos4svMESA;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 0.15.0.0
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
namespace Microsoft.Azure.Management.TrafficManager
{
using System;
using System.Linq;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// EndpointsOperations operations.
/// </summary>
internal partial class EndpointsOperations : IServiceOperations<TrafficManagerManagementClient>, IEndpointsOperations
{
/// <summary>
/// Initializes a new instance of the EndpointsOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal EndpointsOperations(TrafficManagerManagementClient client)
{
if (client == null)
{
throw new ArgumentNullException("client");
}
this.Client = client;
}
/// <summary>
/// Gets a reference to the TrafficManagerManagementClient
/// </summary>
public TrafficManagerManagementClient Client { get; private set; }
/// <summary>
/// Update a Traffic Manager endpoint.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group containing the Traffic Manager endpoint to
/// be updated.
/// </param>
/// <param name='profileName'>
/// The name of the Traffic Manager profile.
/// </param>
/// <param name='endpointType'>
/// The type of the Traffic Manager endpoint to be updated.
/// </param>
/// <param name='endpointName'>
/// The name of the Traffic Manager endpoint to be updated.
/// </param>
/// <param name='parameters'>
/// The Traffic Manager endpoint parameters supplied to the Update operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<Endpoint>> UpdateWithHttpMessagesAsync(string resourceGroupName, string profileName, string endpointType, string endpointName, Endpoint parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (profileName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "profileName");
}
if (endpointType == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "endpointType");
}
if (endpointName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "endpointName");
}
if (parameters == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "parameters");
}
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("profileName", profileName);
tracingParameters.Add("endpointType", endpointType);
tracingParameters.Add("endpointName", endpointName);
tracingParameters.Add("parameters", parameters);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Update", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/trafficmanagerprofiles/{profileName}/{endpointType}/{endpointName}").ToString();
_url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{profileName}", Uri.EscapeDataString(profileName));
_url = _url.Replace("{endpointType}", Uri.EscapeDataString(endpointType));
_url = _url.Replace("{endpointName}", Uri.EscapeDataString(endpointName));
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PATCH");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
_requestContent = SafeJsonConvert.SerializeObject(parameters, this.Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8);
_httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<Endpoint>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<Endpoint>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets a Traffic Manager endpoint.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group containing the Traffic Manager endpoint.
/// </param>
/// <param name='profileName'>
/// The name of the Traffic Manager profile.
/// </param>
/// <param name='endpointType'>
/// The type of the Traffic Manager endpoint.
/// </param>
/// <param name='endpointName'>
/// The name of the Traffic Manager endpoint.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<Endpoint>> GetWithHttpMessagesAsync(string resourceGroupName, string profileName, string endpointType, string endpointName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (profileName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "profileName");
}
if (endpointType == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "endpointType");
}
if (endpointName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "endpointName");
}
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("profileName", profileName);
tracingParameters.Add("endpointType", endpointType);
tracingParameters.Add("endpointName", endpointName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/trafficmanagerprofiles/{profileName}/{endpointType}/{endpointName}").ToString();
_url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{profileName}", Uri.EscapeDataString(profileName));
_url = _url.Replace("{endpointType}", Uri.EscapeDataString(endpointType));
_url = _url.Replace("{endpointName}", Uri.EscapeDataString(endpointName));
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<Endpoint>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<Endpoint>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Create or update a Traffic Manager endpoint.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group containing the Traffic Manager endpoint to
/// be created or updated.
/// </param>
/// <param name='profileName'>
/// The name of the Traffic Manager profile.
/// </param>
/// <param name='endpointType'>
/// The type of the Traffic Manager endpoint to be created or updated.
/// </param>
/// <param name='endpointName'>
/// The name of the Traffic Manager endpoint to be created or updated.
/// </param>
/// <param name='parameters'>
/// The Traffic Manager endpoint parameters supplied to the CreateOrUpdate
/// operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<Endpoint>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string profileName, string endpointType, string endpointName, Endpoint parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (profileName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "profileName");
}
if (endpointType == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "endpointType");
}
if (endpointName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "endpointName");
}
if (parameters == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "parameters");
}
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("profileName", profileName);
tracingParameters.Add("endpointType", endpointType);
tracingParameters.Add("endpointName", endpointName);
tracingParameters.Add("parameters", parameters);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "CreateOrUpdate", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/trafficmanagerprofiles/{profileName}/{endpointType}/{endpointName}").ToString();
_url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{profileName}", Uri.EscapeDataString(profileName));
_url = _url.Replace("{endpointType}", Uri.EscapeDataString(endpointType));
_url = _url.Replace("{endpointName}", Uri.EscapeDataString(endpointName));
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PUT");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
_requestContent = SafeJsonConvert.SerializeObject(parameters, this.Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8);
_httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 201)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<Endpoint>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<Endpoint>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
// Deserialize Response
if ((int)_statusCode == 201)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<Endpoint>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Deletes a Traffic Manager endpoint.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group containing the Traffic Manager endpoint to
/// be deleted.
/// </param>
/// <param name='profileName'>
/// The name of the Traffic Manager profile.
/// </param>
/// <param name='endpointType'>
/// The type of the Traffic Manager endpoint to be deleted.
/// </param>
/// <param name='endpointName'>
/// The name of the Traffic Manager endpoint to be deleted.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string profileName, string endpointType, string endpointName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (profileName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "profileName");
}
if (endpointType == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "endpointType");
}
if (endpointName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "endpointName");
}
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("profileName", profileName);
tracingParameters.Add("endpointType", endpointType);
tracingParameters.Add("endpointName", endpointName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Delete", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/trafficmanagerprofiles/{profileName}/{endpointType}/{endpointName}").ToString();
_url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{profileName}", Uri.EscapeDataString(profileName));
_url = _url.Replace("{endpointType}", Uri.EscapeDataString(endpointType));
_url = _url.Replace("{endpointName}", Uri.EscapeDataString(endpointName));
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("DELETE");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 204)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
// 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.IO;
using System.Reflection;
using System.Threading.Tasks;
using System.Xml;
using Microsoft.Build.BackEnd;
using Microsoft.Build.BackEnd.SdkResolution;
using Microsoft.Build.Collections;
using Microsoft.Build.Engine.UnitTests.BackEnd;
using Microsoft.Build.Evaluation;
using Microsoft.Build.Execution;
using Microsoft.Build.Framework;
using Microsoft.Build.Shared;
using ElementLocation = Microsoft.Build.Construction.ElementLocation;
using ILoggingService = Microsoft.Build.BackEnd.Logging.ILoggingService;
using LegacyThreadingData = Microsoft.Build.Execution.LegacyThreadingData;
using Shouldly;
using Xunit;
using Xunit.Abstractions;
namespace Microsoft.Build.UnitTests.BackEnd
{
/// <summary>
/// Unit tests for the TaskBuilder component
/// </summary>
public class TaskBuilder_Tests : ITargetBuilderCallback
{
/// <summary>
/// The mock component host and logger
/// </summary>
private MockHost _host;
private readonly ITestOutputHelper _testOutput;
/// <summary>
/// The temporary project we use to run the test
/// </summary>
private ProjectInstance _testProject;
/// <summary>
/// Prepares the environment for the test.
/// </summary>
public TaskBuilder_Tests(ITestOutputHelper output)
{
_host = new MockHost();
_testOutput = output;
_testProject = CreateTestProject();
}
/*********************************************************************************
*
* OUTPUT PARAMS
*
*********************************************************************************/
/// <summary>
/// Verifies that we do look up the task during execute when the condition is true.
/// </summary>
[Fact]
public void TasksAreDiscoveredWhenTaskConditionTrue()
{
MockLogger logger = new MockLogger();
string projectFileContents = ObjectModelHelpers.CleanupFileContents(
@"<Project ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'>
<Target Name='t'>
<NonExistantTask Condition=""'1'=='1'""/>
<Message Text='Made it'/>
</Target>
</Project>");
Project project = new Project(XmlReader.Create(new StringReader(projectFileContents)));
List<ILogger> loggers = new List<ILogger>();
loggers.Add(logger);
project.Build("t", loggers);
logger.AssertLogContains("MSB4036");
logger.AssertLogDoesntContain("Made it");
}
/// <summary>
/// Tests that when the task condition is false, Execute still returns true even though we never loaded
/// the task. We verify that we never loaded the task because if we did try, the task load itself would
/// have failed, resulting in an error.
/// </summary>
[Fact]
public void TasksNotDiscoveredWhenTaskConditionFalse()
{
MockLogger logger = new MockLogger();
string projectFileContents = ObjectModelHelpers.CleanupFileContents(
@"<Project ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'>
<Target Name='t'>
<NonExistantTask Condition=""'1'=='2'""/>
<Message Text='Made it'/>
</Target>
</Project>");
Project project = new Project(XmlReader.Create(new StringReader(projectFileContents)));
List<ILogger> loggers = new List<ILogger>();
loggers.Add(logger);
project.Build("t", loggers);
logger.AssertLogContains("Made it");
}
/// <summary>
/// Verify when task outputs are overridden the override messages are correctly displayed
/// </summary>
[Fact]
public void OverridePropertiesInCreateProperty()
{
MockLogger logger = new MockLogger();
string projectFileContents = ObjectModelHelpers.CleanupFileContents(
@"<Project ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'>
<ItemGroup>
<EmbeddedResource Include='a.resx'>
<LogicalName>foo</LogicalName>
</EmbeddedResource>
<EmbeddedResource Include='b.resx'>
<LogicalName>bar</LogicalName>
</EmbeddedResource>
<EmbeddedResource Include='c.resx'>
<LogicalName>barz</LogicalName>
</EmbeddedResource>
</ItemGroup>
<Target Name='t'>
<CreateProperty Value=""@(EmbeddedResource->'/assemblyresource:%(Identity),%(LogicalName)', ' ')""
Condition=""'%(LogicalName)' != '' "">
<Output TaskParameter=""Value"" PropertyName=""LinkSwitches""/>
</CreateProperty>
<Message Text='final:[$(LinkSwitches)]'/>
</Target>
</Project>");
Project project = new Project(XmlReader.Create(new StringReader(projectFileContents)));
List<ILogger> loggers = new List<ILogger>();
loggers.Add(logger);
project.Build("t", loggers);
logger.AssertLogContains(new string[] { "final:[/assemblyresource:c.resx,barz]" });
logger.AssertLogContains(new string[] { ResourceUtilities.FormatResourceStringStripCodeAndKeyword("TaskStarted", "CreateProperty") });
logger.AssertLogContains(new string[] { ResourceUtilities.FormatResourceStringStripCodeAndKeyword("PropertyOutputOverridden", "LinkSwitches", "/assemblyresource:a.resx,foo", "/assemblyresource:b.resx,bar") });
logger.AssertLogContains(new string[] { ResourceUtilities.FormatResourceStringStripCodeAndKeyword("PropertyOutputOverridden", "LinkSwitches", "/assemblyresource:b.resx,bar", "/assemblyresource:c.resx,barz") });
}
/// <summary>
/// Verify that when a task outputs are inferred the override messages are displayed
/// </summary>
[Fact]
public void OverridePropertiesInInferredCreateProperty()
{
string[] files = null;
try
{
files = ObjectModelHelpers.GetTempFiles(2, new DateTime(2005, 1, 1));
MockLogger logger = new MockLogger();
string projectFileContents = ObjectModelHelpers.CleanupFileContents(
@"<Project ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'>
<ItemGroup>
<i Include='" + files[0] + "'><output>" + files[1] + @"</output></i>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include='a.resx'>
<LogicalName>foo</LogicalName>
</EmbeddedResource>
<EmbeddedResource Include='b.resx'>
<LogicalName>bar</LogicalName>
</EmbeddedResource>
<EmbeddedResource Include='c.resx'>
<LogicalName>barz</LogicalName>
</EmbeddedResource>
</ItemGroup>
<Target Name='t2' DependsOnTargets='t'>
<Message Text='final:[$(LinkSwitches)]'/>
</Target>
<Target Name='t' Inputs='%(i.Identity)' Outputs='%(i.Output)'>
<Message Text='start:[Hello]'/>
<CreateProperty Value=""@(EmbeddedResource->'/assemblyresource:%(Identity),%(LogicalName)', ' ')""
Condition=""'%(LogicalName)' != '' "">
<Output TaskParameter=""Value"" PropertyName=""LinkSwitches""/>
</CreateProperty>
<Message Text='end:[hello]'/>
</Target>
</Project>");
Project project = new Project(XmlReader.Create(new StringReader(projectFileContents)));
List<ILogger> loggers = new List<ILogger>();
loggers.Add(logger);
project.Build("t2", loggers);
// We should only see messages from the second target, as the first is only inferred
logger.AssertLogDoesntContain("start:");
logger.AssertLogDoesntContain("end:");
logger.AssertLogContains(new string[] { "final:[/assemblyresource:c.resx,barz]" });
logger.AssertLogDoesntContain(ResourceUtilities.FormatResourceStringStripCodeAndKeyword("TaskStarted", "CreateProperty"));
logger.AssertLogContains(new string[] { ResourceUtilities.FormatResourceStringStripCodeAndKeyword("PropertyOutputOverridden", "LinkSwitches", "/assemblyresource:a.resx,foo", "/assemblyresource:b.resx,bar") });
logger.AssertLogContains(new string[] { ResourceUtilities.FormatResourceStringStripCodeAndKeyword("PropertyOutputOverridden", "LinkSwitches", "/assemblyresource:b.resx,bar", "/assemblyresource:c.resx,barz") });
}
finally
{
ObjectModelHelpers.DeleteTempFiles(files);
}
}
/// <summary>
/// Tests that tasks batch on outputs correctly.
/// </summary>
[Fact]
public void TaskOutputBatching()
{
MockLogger logger = new MockLogger();
string projectFileContents = ObjectModelHelpers.CleanupFileContents(@"
<Project ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'>
<ItemGroup>
<TaskParameterItem Include=""foo"">
<ParameterName>Value</ParameterName>
<ParameterName2>Include</ParameterName2>
<PropertyName>MetadataProperty</PropertyName>
<ItemType>MetadataItem</ItemType>
</TaskParameterItem>
</ItemGroup>
<Target Name='Build'>
<CreateProperty Value=""@(TaskParameterItem)"">
<Output TaskParameter=""Value"" PropertyName=""Property1""/>
</CreateProperty>
<Message Text='Property1=[$(Property1)]' />
<CreateProperty Value=""@(TaskParameterItem)"">
<Output TaskParameter=""%(TaskParameterItem.ParameterName)"" PropertyName=""Property2""/>
</CreateProperty>
<Message Text='Property2=[$(Property2)]' />
<CreateProperty Value=""@(TaskParameterItem)"">
<Output TaskParameter=""Value"" PropertyName=""%(TaskParameterItem.PropertyName)""/>
</CreateProperty>
<Message Text='MetadataProperty=[$(MetadataProperty)]' />
<CreateItem Include=""@(TaskParameterItem)"">
<Output TaskParameter=""Include"" ItemName=""TestItem1""/>
</CreateItem>
<Message Text='TestItem1=[@(TestItem1)]' />
<CreateItem Include=""@(TaskParameterItem)"">
<Output TaskParameter=""%(TaskParameterItem.ParameterName2)"" ItemName=""TestItem2""/>
</CreateItem>
<Message Text='TestItem2=[@(TestItem2)]' />
<CreateItem Include=""@(TaskParameterItem)"">
<Output TaskParameter=""Include"" ItemName=""%(TaskParameterItem.ItemType)""/>
</CreateItem>
<Message Text='MetadataItem=[@(MetadataItem)]' />
</Target>
</Project>");
Project project = new Project(XmlReader.Create(new StringReader(projectFileContents)));
List<ILogger> loggers = new List<ILogger>();
loggers.Add(logger);
project.Build(loggers);
logger.AssertLogContains("Property1=[foo]");
logger.AssertLogContains("Property2=[foo]");
logger.AssertLogContains("MetadataProperty=[foo]");
logger.AssertLogContains("TestItem1=[foo]");
logger.AssertLogContains("TestItem2=[foo]");
logger.AssertLogContains("MetadataItem=[foo]");
}
/// <summary>
/// MSbuildLastTaskResult property contains true or false indicating
/// the success or failure of the last task.
/// </summary>
[Fact]
public void MSBuildLastTaskResult()
{
string projectFileContents = ObjectModelHelpers.CleanupFileContents(@"
<Project DefaultTargets='t2' ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'>
<Target Name='t'>
<Message Text='[start:$(MSBuildLastTaskResult)]'/> <!-- Should be blank -->
<Warning Text='warning'/>
<Message Text='[0:$(MSBuildLastTaskResult)]'/> <!-- Should be true, only a warning-->
<!-- task's Execute returns false -->
<Copy SourceFiles='|' DestinationFolder='c:\' ContinueOnError='true' />
<PropertyGroup>
<p>$(MSBuildLastTaskResult)</p>
</PropertyGroup>
<Message Text='[1:$(MSBuildLastTaskResult)]'/> <!-- Should be false: propertygroup did not reset it -->
<Message Text='[p:$(p)]'/> <!-- Should be false as stored earlier -->
<Message Text='[2:$(MSBuildLastTaskResult)]'/> <!-- Message succeeded, should now be true -->
</Target>
<Target Name='t2' DependsOnTargets='t'>
<Message Text='[3:$(MSBuildLastTaskResult)]'/> <!-- Should still have true -->
<!-- check Error task as well -->
<Error Text='error' ContinueOnError='true' />
<Message Text='[4:$(MSBuildLastTaskResult)]'/> <!-- Should be false -->
<!-- trigger OnError target, ContinueOnError is false -->
<Error Text='error2'/>
<OnError ExecuteTargets='t3'/>
</Target>
<Target Name='t3' >
<Message Text='[5:$(MSBuildLastTaskResult)]'/> <!-- Should be false -->
</Target>
</Project>");
Project project = new Project(XmlReader.Create(new StringReader(projectFileContents)));
List<ILogger> loggers = new List<ILogger>();
MockLogger logger = new MockLogger();
loggers.Add(logger);
project.Build("t2", loggers);
logger.AssertLogContains("[start:]");
logger.AssertLogContains("[0:true]");
logger.AssertLogContains("[1:false]");
logger.AssertLogContains("[p:false]");
logger.AssertLogContains("[2:true]");
logger.AssertLogContains("[3:true]");
logger.AssertLogContains("[4:false]");
logger.AssertLogContains("[4:false]");
}
/// <summary>
/// Verifies that we can add "recursivedir" built-in metadata as target outputs.
/// This is to support wildcards in CreateItem. Allowing anything
/// else could let the item get corrupt (inconsistent values for Filename and FullPath, for example)
/// </summary>
[Fact]
public void TasksCanAddRecursiveDirBuiltInMetadata()
{
MockLogger logger = new MockLogger(this._testOutput);
string projectFileContents = ObjectModelHelpers.CleanupFileContents($@"
<Project>
<Target Name='t'>
<CreateItem Include='{Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)}\**\*.dll'>
<Output TaskParameter='Include' ItemName='x' />
</CreateItem>
<Message Text='@(x)'/>
<Message Text='[%(x.RecursiveDir)]'/>
</Target>
</Project>");
Project project = new Project(XmlReader.Create(new StringReader(projectFileContents)));
project.Build("t", new[] { logger }).ShouldBeTrue();
// Assuming the current directory of the test .dll has at least one subfolder
// such as Roslyn, the log will contain [Roslyn\] (or [Roslyn/] on Unix)
string slashAndBracket = Path.DirectorySeparatorChar.ToString() + "]";
logger.AssertLogContains(slashAndBracket);
logger.AssertLogDoesntContain("MSB4118");
logger.AssertLogDoesntContain("MSB3031");
}
/// <summary>
/// Verify CreateItem prevents adding any built-in metadata explicitly, even recursivedir.
/// </summary>
[Fact]
public void OtherBuiltInMetadataErrors()
{
MockLogger logger = new MockLogger();
string projectFileContents = ObjectModelHelpers.CleanupFileContents(@"
<Project ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'>
<Target Name='t'>
<CreateItem Include='Foo' AdditionalMetadata='RecursiveDir=1'>
<Output TaskParameter='Include' ItemName='x' />
</CreateItem>
</Target>
</Project>");
Project project = new Project(XmlReader.Create(new StringReader(projectFileContents)));
List<ILogger> loggers = new List<ILogger>();
loggers.Add(logger);
bool result = project.Build("t", loggers);
Assert.False(result);
logger.AssertLogContains("MSB3031");
}
/// <summary>
/// Verify CreateItem prevents adding any built-in metadata explicitly, even recursivedir.
/// </summary>
[Fact]
public void OtherBuiltInMetadataErrors2()
{
MockLogger logger = new MockLogger();
string projectFileContents = ObjectModelHelpers.CleanupFileContents(@"
<Project ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'>
<Target Name='t'>
<CreateItem Include='Foo' AdditionalMetadata='Extension=1'/>
</Target>
</Project>");
Project project = new Project(XmlReader.Create(new StringReader(projectFileContents)));
List<ILogger> loggers = new List<ILogger>();
loggers.Add(logger);
bool result = project.Build("t", loggers);
Assert.False(result);
logger.AssertLogContains("MSB3031");
}
/// <summary>
/// Verify that properties can be passed in to a task and out as items, despite the
/// built-in metadata restrictions.
/// </summary>
[Fact]
public void PropertiesInItemsOutOfTask()
{
MockLogger logger = new MockLogger();
string projectFileContents = ObjectModelHelpers.CleanupFileContents(@"
<Project ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'>
<Target Name='t'>
<PropertyGroup>
<p>c:\a.ext</p>
</PropertyGroup>
<CreateItem Include='$(p)'>
<Output TaskParameter='Include' ItemName='x' />
</CreateItem>
<Message Text='[%(x.Extension)]'/>
</Target>
</Project>");
Project project = new Project(XmlReader.Create(new StringReader(projectFileContents)));
List<ILogger> loggers = new List<ILogger>();
loggers.Add(logger);
bool result = project.Build("t", loggers);
Assert.True(result);
logger.AssertLogContains("[.ext]");
}
/// <summary>
/// Verify that properties can be passed in to a task and out as items, despite
/// having illegal characters for a file name
/// </summary>
[Fact]
public void IllegalFileCharsInItemsOutOfTask()
{
MockLogger logger = new MockLogger();
string projectFileContents = ObjectModelHelpers.CleanupFileContents(@"
<Project ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'>
<Target Name='t'>
<PropertyGroup>
<p>||illegal||</p>
</PropertyGroup>
<CreateItem Include='$(p)'>
<Output TaskParameter='Include' ItemName='x' />
</CreateItem>
<Message Text='[@(x)]'/>
</Target>
</Project>");
Project project = new Project(XmlReader.Create(new StringReader(projectFileContents)));
List<ILogger> loggers = new List<ILogger>();
loggers.Add(logger);
bool result = project.Build("t", loggers);
Assert.True(result);
logger.AssertLogContains("[||illegal||]");
}
/// <summary>
/// If an item being output from a task has null metadata, we shouldn't crash.
/// </summary>
[Fact]
[Trait("Category", "mono-osx-failing")]
public void NullMetadataOnOutputItems()
{
string customTaskPath = Assembly.GetExecutingAssembly().Location;
string projectContents = @"<Project ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`>
<UsingTask TaskName=`NullMetadataTask` AssemblyFile=`" + customTaskPath + @"` />
<Target Name=`Build`>
<NullMetadataTask>
<Output TaskParameter=`OutputItems` ItemName=`Outputs`/>
</NullMetadataTask>
<Message Text=`[%(Outputs.Identity): %(Outputs.a)]` Importance=`High` />
</Target>
</Project>";
MockLogger logger = ObjectModelHelpers.BuildProjectExpectSuccess(projectContents, _testOutput);
logger.AssertLogContains("[foo: ]");
}
/// <summary>
/// If an item being output from a task has null metadata, we shouldn't crash.
/// </summary>
[Fact]
[Trait("Category", "mono-osx-failing")]
public void NullMetadataOnLegacyOutputItems()
{
string customTaskPath = Assembly.GetExecutingAssembly().Location;
string projectContents = @"<Project ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`>
<UsingTask TaskName=`NullMetadataTask` AssemblyFile=`" + customTaskPath + @"` />
<Target Name=`Build`>
<NullMetadataTask>
<Output TaskParameter=`OutputItems` ItemName=`Outputs`/>
</NullMetadataTask>
<Message Text=`[%(Outputs.Identity): %(Outputs.a)]` Importance=`High` />
</Target>
</Project>";
MockLogger logger = ObjectModelHelpers.BuildProjectExpectSuccess(projectContents, _testOutput);
logger.AssertLogContains("[foo: ]");
}
/// <summary>
/// Regression test for https://github.com/microsoft/msbuild/issues/5080
/// </summary>
[Fact]
public void SameAssemblyFromDifferentRelativePathsSharesAssemblyLoadContext()
{
string realTaskPath = Assembly.GetExecutingAssembly().Location;
string fileName = Path.GetFileName(realTaskPath);
string directoryName = Path.GetDirectoryName(realTaskPath);
using var env = TestEnvironment.Create();
string customTaskFolder = Path.Combine(directoryName, "buildCrossTargeting");
env.CreateFolder(customTaskFolder);
string projectContents = @"<Project ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`>
<UsingTask TaskName=`RegisterObject` AssemblyFile=`" + Path.Combine(customTaskFolder, "..", fileName) + @"` />
<UsingTask TaskName=`RetrieveObject` AssemblyFile=`" + realTaskPath + @"` />
<Target Name=`Build`>
<RegisterObject />
<RetrieveObject />
</Target>
</Project>";
MockLogger logger = ObjectModelHelpers.BuildProjectExpectSuccess(projectContents, _testOutput);
logger.AssertLogDoesntContain("MSB4018");
}
#if FEATURE_CODETASKFACTORY
/// <summary>
/// If an item being output from a task has null metadata, we shouldn't crash.
/// </summary>
[Fact]
public void NullMetadataOnOutputItems_InlineTask()
{
string projectContents = @"
<Project xmlns='msbuildnamespace' ToolsVersion='msbuilddefaulttoolsversion'>
<UsingTask TaskName=`NullMetadataTask_v12` TaskFactory=`CodeTaskFactory` AssemblyFile=`$(MSBuildToolsPath)\Microsoft.Build.Tasks.Core.dll`>
<ParameterGroup>
<OutputItems ParameterType=`Microsoft.Build.Framework.ITaskItem[]` Output=`true` />
</ParameterGroup>
<Task>
<Code>
<![CDATA[
OutputItems = new ITaskItem[1];
IDictionary<string, string> metadata = new Dictionary<string, string>();
metadata.Add(`a`, null);
OutputItems[0] = new TaskItem(`foo`, (IDictionary)metadata);
return true;
]]>
</Code>
</Task>
</UsingTask>
<Target Name=`Build`>
<NullMetadataTask_v12>
<Output TaskParameter=`OutputItems` ItemName=`Outputs` />
</NullMetadataTask_v12>
<Message Text=`[%(Outputs.Identity): %(Outputs.a)]` Importance=`High` />
</Target>
</Project>";
MockLogger logger = ObjectModelHelpers.BuildProjectExpectSuccess(projectContents, _testOutput);
logger.AssertLogContains("[foo: ]");
}
/// <summary>
/// If an item being output from a task has null metadata, we shouldn't crash.
/// </summary>
[Fact]
[Trait("Category", "non-mono-tests")]
public void NullMetadataOnLegacyOutputItems_InlineTask()
{
string projectContents = @"
<Project xmlns='msbuildnamespace' ToolsVersion='msbuilddefaulttoolsversion'>
<UsingTask TaskName=`NullMetadataTask_v4` TaskFactory=`CodeTaskFactory` AssemblyFile=`$(MSBuildFrameworkToolsPath)\Microsoft.Build.Tasks.v4.0.dll`>
<ParameterGroup>
<OutputItems ParameterType=`Microsoft.Build.Framework.ITaskItem[]` Output=`true` />
</ParameterGroup>
<Task>
<Code>
<![CDATA[
OutputItems = new ITaskItem[1];
IDictionary<string, string> metadata = new Dictionary<string, string>();
metadata.Add(`a`, null);
OutputItems[0] = new TaskItem(`foo`, (IDictionary)metadata);
return true;
]]>
</Code>
</Task>
</UsingTask>
<Target Name=`Build`>
<NullMetadataTask_v4>
<Output TaskParameter=`OutputItems` ItemName=`Outputs` />
</NullMetadataTask_v4>
<Message Text=`[%(Outputs.Identity): %(Outputs.a)]` Importance=`High` />
</Target>
</Project>";
MockLogger logger = ObjectModelHelpers.BuildProjectExpectSuccess(projectContents, _testOutput);
logger.AssertLogContains("[foo: ]");
}
#endif
/// <summary>
/// Validates that the defining project metadata is set (or not set) as expected in
/// various task output-related operations, using a task built against the current
/// version of MSBuild.
/// </summary>
[Fact]
public void ValidateDefiningProjectMetadataOnTaskOutputs()
{
string customTaskPath = Assembly.GetExecutingAssembly().Location;
ValidateDefiningProjectMetadataOnTaskOutputsHelper(customTaskPath);
}
/// <summary>
/// Validates that the defining project metadata is set (or not set) as expected in
/// various task output-related operations, using a task built against V4 MSBuild,
/// which didn't support the defining project metadata.
/// </summary>
[Fact]
[Trait("Category", "mono-osx-failing")]
public void ValidateDefiningProjectMetadataOnTaskOutputs_LegacyItems()
{
string customTaskPath = Assembly.GetExecutingAssembly().Location;
ValidateDefiningProjectMetadataOnTaskOutputsHelper(customTaskPath);
}
#if FEATURE_APARTMENT_STATE
/// <summary>
/// Tests that putting the RunInSTA attribute on a task causes it to run in the STA thread.
/// </summary>
[Fact]
[Trait("Category", "mono-osx-failing")]
public void TestSTAThreadRequired()
{
TestSTATask(true, false, false);
}
/// <summary>
/// Tests an STA task with an exception
/// </summary>
[Fact]
[Trait("Category", "mono-osx-failing")]
public void TestSTAThreadRequiredWithException()
{
TestSTATask(true, false, true);
}
/// <summary>
/// Tests an STA task with failure.
/// </summary>
[Fact]
[Trait("Category", "mono-osx-failing")]
public void TestSTAThreadRequiredWithFailure()
{
TestSTATask(true, true, false);
}
/// <summary>
/// Tests an MTA task.
/// </summary>
[Fact]
[Trait("Category", "mono-osx-failing")]
public void TestSTAThreadNotRequired()
{
TestSTATask(false, false, false);
}
/// <summary>
/// Tests an MTA task with an exception.
/// </summary>
[Fact]
[Trait("Category", "mono-osx-failing")]
public void TestSTAThreadNotRequiredWithException()
{
TestSTATask(false, false, true);
}
/// <summary>
/// Tests an MTA task with failure.
/// </summary>
[Fact]
[Trait("Category", "mono-osx-failing")]
public void TestSTAThreadNotRequiredWithFailure()
{
TestSTATask(false, true, false);
}
#endif
#region ITargetBuilderCallback Members
/// <summary>
/// Empty impl
/// </summary>
Task<ITargetResult[]> ITargetBuilderCallback.LegacyCallTarget(string[] targets, bool continueOnError, ElementLocation referenceLocation)
{
throw new NotImplementedException();
}
/// <summary>
/// Empty impl
/// </summary>
void IRequestBuilderCallback.Yield()
{
}
/// <summary>
/// Empty impl
/// </summary>
void IRequestBuilderCallback.Reacquire()
{
}
/// <summary>
/// Empty impl
/// </summary>
void IRequestBuilderCallback.EnterMSBuildCallbackState()
{
}
/// <summary>
/// Empty impl
/// </summary>
void IRequestBuilderCallback.ExitMSBuildCallbackState()
{
}
/// <summary>
/// Empty impl
/// </summary>
int IRequestBuilderCallback.RequestCores(object monitorLockObject, int requestedCores, bool waitForCores)
{
return 0;
}
/// <summary>
/// Empty impl
/// </summary>
void IRequestBuilderCallback.ReleaseCores(int coresToRelease)
{
}
#endregion
#region IRequestBuilderCallback Members
/// <summary>
/// Empty impl
/// </summary>
Task<BuildResult[]> IRequestBuilderCallback.BuildProjects(string[] projectFiles, PropertyDictionary<ProjectPropertyInstance>[] properties, string[] toolsVersions, string[] targets, bool waitForResults, bool skipNonexistentTargets)
{
throw new NotImplementedException();
}
/// <summary>
/// Not implemented.
/// </summary>
Task IRequestBuilderCallback.BlockOnTargetInProgress(int blockingRequestId, string blockingTarget, BuildResult partialBuildResult)
{
throw new NotImplementedException();
}
#endregion
/*********************************************************************************
*
* Helpers
*
*********************************************************************************/
/// <summary>
/// Helper method for validating the setting of defining project metadata on items
/// coming from task outputs
/// </summary>
private void ValidateDefiningProjectMetadataOnTaskOutputsHelper(string customTaskPath)
{
string projectAPath = Path.Combine(ObjectModelHelpers.TempProjectDir, "a.proj");
string projectBPath = Path.Combine(ObjectModelHelpers.TempProjectDir, "b.proj");
string projectAContents = @"
<Project xmlns=`msbuildnamespace` ToolsVersion=`msbuilddefaulttoolsversion`>
<UsingTask TaskName=`ItemCreationTask` AssemblyFile=`" + customTaskPath + @"` />
<Import Project=`b.proj` />
<Target Name=`Run`>
<ItemCreationTask
InputItemsToPassThrough=`@(PassThrough)`
InputItemsToCopy=`@(Copy)`>
<Output TaskParameter=`OutputString` ItemName=`A` />
<Output TaskParameter=`PassedThroughOutputItems` ItemName=`B` />
<Output TaskParameter=`CreatedOutputItems` ItemName=`C` />
<Output TaskParameter=`CopiedOutputItems` ItemName=`D` />
</ItemCreationTask>
<Warning Text=`A is wrong: EXPECTED: [a] ACTUAL: [%(A.DefiningProjectName)]` Condition=`'%(A.DefiningProjectName)' != 'a'` />
<Warning Text=`B is wrong: EXPECTED: [a] ACTUAL: [%(B.DefiningProjectName)]` Condition=`'%(B.DefiningProjectName)' != 'a'` />
<Warning Text=`C is wrong: EXPECTED: [a] ACTUAL: [%(C.DefiningProjectName)]` Condition=`'%(C.DefiningProjectName)' != 'a'` />
<Warning Text=`D is wrong: EXPECTED: [a] ACTUAL: [%(D.DefiningProjectName)]` Condition=`'%(D.DefiningProjectName)' != 'a'` />
</Target>
</Project>
";
string projectBContents = @"
<Project xmlns=`msbuildnamespace` ToolsVersion=`msbuilddefaulttoolsversion`>
<ItemGroup>
<PassThrough Include=`aaa.cs` />
<Copy Include=`bbb.cs` />
</ItemGroup>
</Project>
";
try
{
File.WriteAllText(projectAPath, ObjectModelHelpers.CleanupFileContents(projectAContents));
File.WriteAllText(projectBPath, ObjectModelHelpers.CleanupFileContents(projectBContents));
MockLogger logger = new MockLogger(_testOutput);
ObjectModelHelpers.BuildTempProjectFileExpectSuccess("a.proj", logger);
logger.AssertNoWarnings();
}
finally
{
if (File.Exists(projectAPath))
{
File.Delete(projectAPath);
}
if (File.Exists(projectBPath))
{
File.Delete(projectBPath);
}
}
}
#if FEATURE_APARTMENT_STATE
/// <summary>
/// Executes an STA task test.
/// </summary>
private void TestSTATask(bool requireSTA, bool failTask, bool throwException)
{
MockLogger logger = new MockLogger();
logger.AllowTaskCrashes = throwException;
string taskAssemblyName;
Project project = CreateSTATestProject(requireSTA, failTask, throwException, out taskAssemblyName);
List<ILogger> loggers = new List<ILogger>();
loggers.Add(logger);
BuildParameters parameters = new BuildParameters();
parameters.Loggers = new ILogger[] { logger };
BuildResult result = BuildManager.DefaultBuildManager.Build(parameters, new BuildRequestData(project.CreateProjectInstance(), new string[] { "Foo" }));
if (requireSTA)
{
logger.AssertLogContains("STA");
}
else
{
logger.AssertLogContains("MTA");
}
if (throwException)
{
logger.AssertLogContains("EXCEPTION");
Assert.Equal(BuildResultCode.Failure, result.OverallResult);
return;
}
else
{
logger.AssertLogDoesntContain("EXCEPTION");
}
if (failTask)
{
logger.AssertLogContains("FAIL");
Assert.Equal(BuildResultCode.Failure, result.OverallResult);
}
else
{
logger.AssertLogDoesntContain("FAIL");
}
if (!throwException && !failTask)
{
Assert.Equal(BuildResultCode.Success, result.OverallResult);
}
}
/// <summary>
/// Helper to create a project which invokes the STA helper task.
/// </summary>
private Project CreateSTATestProject(bool requireSTA, bool failTask, bool throwException, out string assemblyToDelete)
{
assemblyToDelete = GenerateSTATask(requireSTA);
string projectFileContents = ObjectModelHelpers.CleanupFileContents(@"
<Project ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'>
<UsingTask TaskName='ThreadTask' AssemblyFile='" + assemblyToDelete + @"'/>
<Target Name='Foo'>
<ThreadTask Fail='" + failTask + @"' ThrowException='" + throwException + @"'/>
</Target>
</Project>");
Project project = new Project(XmlReader.Create(new StringReader(projectFileContents)));
return project;
}
#endif
/// <summary>
/// Helper to create the STA test task.
/// </summary>
private string GenerateSTATask(bool requireSTA)
{
string taskContents =
@"
using System;
using Microsoft.Build.Framework;
namespace ClassLibrary2
{" + (requireSTA ? "[RunInSTA]" : String.Empty) + @"
public class ThreadTask : ITask
{
#region ITask Members
public IBuildEngine BuildEngine
{
get;
set;
}
public bool ThrowException
{
get;
set;
}
public bool Fail
{
get;
set;
}
public bool Execute()
{
string message;
if (System.Threading.Thread.CurrentThread.GetApartmentState() == System.Threading.ApartmentState.STA)
{
message = ""STA"";
}
else
{
message = ""MTA"";
}
BuildEngine.LogMessageEvent(new BuildMessageEventArgs(message, """", ""ThreadTask"", MessageImportance.High));
if (ThrowException)
{
throw new InvalidOperationException(""EXCEPTION"");
}
if (Fail)
{
BuildEngine.LogMessageEvent(new BuildMessageEventArgs(""FAIL"", """", ""ThreadTask"", MessageImportance.High));
}
return !Fail;
}
public ITaskHost HostObject
{
get;
set;
}
#endregion
}
}";
return CustomTaskHelper.GetAssemblyForTask(taskContents);
}
/// <summary>
/// Creates a test project.
/// </summary>
/// <returns>The project.</returns>
private ProjectInstance CreateTestProject()
{
string projectFileContents = ObjectModelHelpers.CleanupFileContents(@"
<Project ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'>
<ItemGroup>
<Compile Include='b.cs' />
<Compile Include='c.cs' />
</ItemGroup>
<ItemGroup>
<Reference Include='System' />
</ItemGroup>
<Target Name='Empty' />
<Target Name='Skip' Inputs='testProject.proj' Outputs='testProject.proj' />
<Target Name='Error' >
<ErrorTask1 ContinueOnError='True'/>
<ErrorTask2 ContinueOnError='False'/>
<ErrorTask3 />
<OnError ExecuteTargets='Foo'/>
<OnError ExecuteTargets='Bar'/>
</Target>
<Target Name='Foo' Inputs='foo.cpp' Outputs='foo.o'>
<FooTask1/>
</Target>
<Target Name='Bar'>
<BarTask1/>
</Target>
<Target Name='Baz' DependsOnTargets='Bar'>
<BazTask1/>
<BazTask2/>
</Target>
<Target Name='Baz2' DependsOnTargets='Bar;Foo'>
<Baz2Task1/>
<Baz2Task2/>
<Baz2Task3/>
</Target>
<Target Name='DepSkip' DependsOnTargets='Skip'>
<DepSkipTask1/>
<DepSkipTask2/>
<DepSkipTask3/>
</Target>
<Target Name='DepError' DependsOnTargets='Foo;Skip;Error'>
<DepSkipTask1/>
<DepSkipTask2/>
<DepSkipTask3/>
</Target>
</Project>
");
IConfigCache cache = (IConfigCache)_host.GetComponent(BuildComponentType.ConfigCache);
BuildRequestConfiguration config = new BuildRequestConfiguration(1, new BuildRequestData("testfile", new Dictionary<string, string>(), "3.5", new string[0], null), "2.0");
Project project = new Project(XmlReader.Create(new StringReader(projectFileContents)));
config.Project = project.CreateProjectInstance();
cache.AddConfiguration(config);
return config.Project;
}
/// <summary>
/// The mock component host object.
/// </summary>
private class MockHost : MockLoggingService, IBuildComponentHost, IBuildComponent
{
#region IBuildComponentHost Members
/// <summary>
/// The config cache
/// </summary>
private IConfigCache _configCache;
/// <summary>
/// The logging service
/// </summary>
private ILoggingService _loggingService;
/// <summary>
/// The results cache
/// </summary>
private IResultsCache _resultsCache;
/// <summary>
/// The request builder
/// </summary>
private IRequestBuilder _requestBuilder;
/// <summary>
/// The target builder
/// </summary>
private ITargetBuilder _targetBuilder;
/// <summary>
/// The build parameters.
/// </summary>
private BuildParameters _buildParameters;
/// <summary>
/// Retrieves the LegacyThreadingData associated with a particular component host
/// </summary>
private LegacyThreadingData _legacyThreadingData;
private ISdkResolverService _sdkResolverService;
/// <summary>
/// Constructor
///
/// UNDONE: Refactor this, and the other MockHosts, to use a common base implementation. The duplication of the
/// logging implementation alone is unfortunate.
/// </summary>
public MockHost()
{
_buildParameters = new BuildParameters();
_legacyThreadingData = new LegacyThreadingData();
_configCache = new ConfigCache();
((IBuildComponent)_configCache).InitializeComponent(this);
_loggingService = this;
_resultsCache = new ResultsCache();
((IBuildComponent)_resultsCache).InitializeComponent(this);
_requestBuilder = new RequestBuilder();
((IBuildComponent)_requestBuilder).InitializeComponent(this);
_targetBuilder = new TargetBuilder();
((IBuildComponent)_targetBuilder).InitializeComponent(this);
_sdkResolverService = new MockSdkResolverService();
((IBuildComponent)_sdkResolverService).InitializeComponent(this);
}
/// <summary>
/// Returns the node logging service. We don't distinguish here.
/// </summary>
public ILoggingService LoggingService
{
get
{
return _loggingService;
}
}
/// <summary>
/// Retrieves the name of the host.
/// </summary>
public string Name
{
get
{
return "TaskBuilder_Tests.MockHost";
}
}
/// <summary>
/// Returns the build parameters.
/// </summary>
public BuildParameters BuildParameters
{
get
{
return _buildParameters;
}
}
/// <summary>
/// Retrieves the LegacyThreadingData associated with a particular component host
/// </summary>
LegacyThreadingData IBuildComponentHost.LegacyThreadingData
{
get
{
return _legacyThreadingData;
}
}
/// <summary>
/// Constructs and returns a component of the specified type.
/// </summary>
/// <param name="type">The type of component to return</param>
/// <returns>The component</returns>
public IBuildComponent GetComponent(BuildComponentType type)
{
return type switch
{
BuildComponentType.ConfigCache => (IBuildComponent)_configCache,
BuildComponentType.LoggingService => (IBuildComponent)_loggingService,
BuildComponentType.ResultsCache => (IBuildComponent)_resultsCache,
BuildComponentType.RequestBuilder => (IBuildComponent)_requestBuilder,
BuildComponentType.TargetBuilder => (IBuildComponent)_targetBuilder,
BuildComponentType.SdkResolverService => (IBuildComponent)_sdkResolverService,
_ => throw new ArgumentException("Unexpected type " + type),
};
}
/// <summary>
/// Register a component factory.
/// </summary>
public void RegisterFactory(BuildComponentType type, BuildComponentFactoryDelegate factory)
{
}
#endregion
#region IBuildComponent Members
/// <summary>
/// Sets the component host
/// </summary>
/// <param name="host">The component host</param>
public void InitializeComponent(IBuildComponentHost host)
{
throw new NotImplementedException();
}
/// <summary>
/// Shuts down the component
/// </summary>
public void ShutdownComponent()
{
throw new NotImplementedException();
}
#endregion
}
}
}
| |
// RtmBackend.cs created with MonoDevelop
// User: boyd at 7:10 AM 2/11/2008
//
// To change standard headers go to Edit->Preferences->Coding->Standard Headers
//
using System;
using Mono.Unix;
using RtmNet;
using System.Threading;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Diagnostics;
using System.Net;
namespace Tasque.Backends.RtmBackend
{
public class RtmBackend : Backend
{
public RtmBackend () : base ("Remember the Milk")
{
taskLock = new Object ();
catLock = new Object ();
runRefreshEvent = new AutoResetEvent (false);
runningRefreshThread = false;
refreshThread = new Thread (RefreshThreadLoop);
}
public override Category DefaultCategory {
get {
if (!Initialized)
throw new InvalidOperationException ("Backend not initialized");
return Categories.ElementAt (0);
}
set { throw new NotSupportedException (); }
}
public string RtmUserName {
get {
if (rtmAuth != null && rtmAuth.User != null)
return rtmAuth.User.Username;
else
return null;
}
}
#region Public Methods
public override Task CreateTask (string taskName)
{
throw new NotImplementedException ();
// var category = categories.ElementAt (0);
// var categoryID = (category as RtmCategory).ID;
// RtmTask rtmTask = null;
//
// if (rtm != null) {
// try {
// var list = rtm.TasksAdd (timeline, taskName, categoryID);
// var ts = list.TaskSeriesCollection [0];
// if (ts != null)
// rtmTask = new RtmTask (ts, this, list.ID);
// } catch (Exception e) {
// Debug.WriteLine ("Unable to set create task: " + taskName);
// Debug.WriteLine (e.ToString ());
// }
// } else
// throw new Exception ("Unable to communicate with Remember The Milk");
//
// return rtmTask;
}
// protected override void OnDeleteTask (Task task)
// {
// var rtmTask = task as RtmTask;
// if (rtm != null) {
// try {
// rtm.TasksDelete (timeline, rtmTask.ListID, rtmTask.SeriesTaskID, rtmTask.TaskTaskID);
// } catch (Exception e) {
// Debug.WriteLine ("Unable to delete task: " + task.Name);
// Debug.WriteLine (e.ToString ());
// }
// } else
// throw new Exception ("Unable to communicate with Remember The Milk");
// base.OnDeleteTask (task);
// }
public override void Refresh ()
{
Debug.WriteLine ("Refreshing data...");
if (!runningRefreshThread)
StartThread ();
runRefreshEvent.Set ();
Debug.WriteLine ("Done refreshing data!");
}
public override void Initialize ()
{
// *************************************
// AUTHENTICATION to Remember The Milk
// *************************************
var authToken = Application.Instance.Preferences.Get (Tasque.Preferences.AuthTokenKey);
if (authToken != null) {
Debug.WriteLine ("Found AuthToken, checking credentials...");
try {
rtm = new Rtm (ApiKey, SharedSecret, authToken);
rtmAuth = rtm.AuthCheckToken (authToken);
timeline = rtm.TimelineCreate ();
Debug.WriteLine ("RTM Auth Token is valid!");
Debug.WriteLine ("Setting configured status to true");
Configured = true;
} catch (RtmApiException e) {
Application.Instance.Preferences.Set (Tasque.Preferences.AuthTokenKey, null);
Application.Instance.Preferences.Set (Tasque.Preferences.UserIdKey, null);
Application.Instance.Preferences.Set (Tasque.Preferences.UserNameKey, null);
rtm = null;
rtmAuth = null;
Trace.TraceError ("Exception authenticating, reverting" + e.Message);
} catch (RtmWebException e) {
rtm = null;
rtmAuth = null;
Trace.TraceError ("Not connected to RTM, maybe proxy: #{0}", e.Message);
} catch (WebException e) {
rtm = null;
rtmAuth = null;
Trace.TraceError ("Problem connecting to internet: #{0}", e.Message);
}
}
if (rtm == null)
rtm = new Rtm (ApiKey, SharedSecret);
StartThread ();
}
public void StartThread ()
{
if (!Configured) {
Debug.WriteLine ("Backend not configured, not starting thread");
return;
}
runningRefreshThread = true;
Debug.WriteLine ("ThreadState: " + refreshThread.ThreadState);
if (refreshThread.ThreadState == System.Threading.ThreadState.Running)
Debug.WriteLine ("RtmBackend refreshThread already running");
else {
if (!refreshThread.IsAlive)
refreshThread = new Thread (RefreshThreadLoop);
refreshThread.Start ();
}
runRefreshEvent.Set ();
}
protected override void Dispose (bool disposing)
{
if (disposing) {
runningRefreshThread = false;
runRefreshEvent.Set ();
refreshThread.Abort ();
}
base.Dispose (disposing);
}
public override IBackendPreferences Preferences { get { return new RtmPreferencesWidget (); } }
public string GetAuthUrl ()
{
frob = rtm.AuthGetFrob ();
return rtm.AuthCalcUrl (frob, AuthLevel.Delete);
}
public void FinishedAuth ()
{
rtmAuth = rtm.AuthGetToken (frob);
if (rtmAuth != null) {
var prefs = Application.Instance.Preferences;
prefs.Set (Tasque.Preferences.AuthTokenKey, rtmAuth.Token);
if (rtmAuth.User != null) {
prefs.Set (Tasque.Preferences.UserNameKey, rtmAuth.User.Username);
prefs.Set (Tasque.Preferences.UserIdKey, rtmAuth.User.UserId);
}
}
var authToken = Application.Instance.Preferences.Get (Tasque.Preferences.AuthTokenKey);
if (authToken != null) {
Debug.WriteLine ("Found AuthToken, checking credentials...");
try {
rtm = new Rtm (ApiKey, SharedSecret, authToken);
rtmAuth = rtm.AuthCheckToken (authToken);
timeline = rtm.TimelineCreate ();
Debug.WriteLine ("RTM Auth Token is valid!");
Debug.WriteLine ("Setting configured status to true");
Configured = true;
Refresh ();
} catch (Exception e) {
rtm = null;
rtmAuth = null;
Trace.TraceError ("Exception authenticating, reverting" + e.Message);
}
}
}
public void UpdateTaskName (RtmTask task)
{
if (rtm != null) {
try {
rtm.TasksSetName (timeline, task.ListID, task.SeriesTaskID,
task.TaskTaskID, task.Name);
} catch (Exception e) {
Debug.WriteLine ("Unable to set name on task: " + task.Name);
Debug.WriteLine (e.ToString ());
}
}
}
public void UpdateTaskDueDate (RtmTask task)
{
if (rtm != null) {
try {
if (task.DueDate == DateTime.MinValue)
rtm.TasksSetDueDate (timeline, task.ListID, task.SeriesTaskID, task.TaskTaskID);
else
rtm.TasksSetDueDate (timeline, task.ListID, task.SeriesTaskID,
task.TaskTaskID, task.DueDateString);
} catch (Exception e) {
Debug.WriteLine ("Unable to set due date on task: " + task.Name);
Debug.WriteLine (e.ToString ());
}
}
}
public void UpdateTaskPriority (RtmTask task)
{
if (rtm != null) {
try {
rtm.TasksSetPriority (timeline, task.ListID, task.SeriesTaskID,
task.TaskTaskID, task.PriorityString);
} catch (Exception e) {
Debug.WriteLine ("Unable to set priority on task: " + task.Name);
Debug.WriteLine (e.ToString ());
}
}
}
public void UpdateTaskActive (RtmTask task)
{
if (rtm != null) {
try {
rtm.TasksUncomplete (timeline, task.ListID, task.SeriesTaskID, task.TaskTaskID);
} catch (Exception e) {
Debug.WriteLine ("Unable to set Task as completed: " + task.Name);
Debug.WriteLine (e.ToString ());
}
}
}
public void UpdateTaskCompleted (RtmTask task)
{
if (rtm != null) {
try {
rtm.TasksComplete (timeline, task.ListID, task.SeriesTaskID, task.TaskTaskID);
} catch (Exception e) {
Debug.WriteLine ("Unable to set Task as completed: " + task.Name);
Debug.WriteLine (e.ToString ());
}
}
}
public void UpdateTaskDeleted (RtmTask task)
{
if (rtm != null) {
try {
rtm.TasksDelete (timeline, task.ListID, task.SeriesTaskID, task.TaskTaskID);
} catch (Exception e) {
Debug.WriteLine ("Unable to set Task as deleted: " + task.Name);
Debug.WriteLine (e.ToString ());
}
}
}
public void MoveTaskCategory (RtmTask task, string id)
{
if (rtm != null) {
try {
rtm.TasksMoveTo (timeline, task.ListID, id, task.SeriesTaskID, task.TaskTaskID);
} catch (Exception e) {
Debug.WriteLine ("Unable to set Task as completed: " + task.Name);
Debug.WriteLine (e.ToString ());
}
}
}
public RtmNote CreateNote (RtmTask rtmTask, string text)
{
Note note = null;
RtmNote rtmNote = null;
if (rtm != null) {
try {
note = rtm.NotesAdd (timeline, rtmTask.ListID, rtmTask.SeriesTaskID,
rtmTask.TaskTaskID, string.Empty, text);
rtmNote = new RtmNote (note);
rtmNote.OnTextChangedAction = delegate { SaveNote (rtmTask, rtmNote); };
} catch (Exception e) {
Debug.WriteLine ("RtmBackend.CreateNote: Unable to create a new note");
Debug.WriteLine (e.ToString ());
}
} else
throw new Exception ("Unable to communicate with Remember The Milk");
return rtmNote;
}
public void DeleteNote (RtmTask rtmTask, RtmNote note)
{
if (rtm != null) {
try {
rtm.NotesDelete (timeline, note.ID);
} catch (Exception e) {
Debug.WriteLine ("RtmBackend.DeleteNote: Unable to delete note");
Debug.WriteLine (e.ToString ());
}
} else
throw new Exception ("Unable to communicate with Remember The Milk");
}
void SaveNote (RtmTask rtmTask, RtmNote note)
{
if (rtm != null) {
try {
rtm.NotesEdit (timeline, note.ID, string.Empty, note.Text);
} catch (Exception e) {
Debug.WriteLine ("RtmBackend.SaveNote: Unable to save note");
Debug.WriteLine (e.ToString ());
}
} else
throw new Exception ("Unable to communicate with Remember The Milk");
}
#endregion // Public Methods
#region Private Methods
/// <summary>
/// Update the model to match what is in RTM
/// FIXME: This is a lame implementation and needs to be optimized
/// </summary>
void UpdateCategories (Lists lists)
{
Debug.WriteLine ("RtmBackend.UpdateCategories was called");
try {
foreach (var list in lists.listCollection) {
lock (catLock) {
Application.Instance.Dispatcher.Invoke (delegate {
RtmCategory rtmCategory;
if (!Categories.Any (c => ((RtmCategory)c).ID == list.ID)) {
rtmCategory = new RtmCategory (list);
Categories.Add (rtmCategory);
}
});
}
}
} catch (Exception e) {
Debug.WriteLine ("Exception in fetch " + e.Message);
}
Debug.WriteLine ("RtmBackend.UpdateCategories is done");
}
/// <summary>
/// Update the model to match what is in RTM
/// FIXME: This is a lame implementation and needs to be optimized
/// </summary>
void UpdateTasks (Lists lists)
{
Debug.WriteLine ("RtmBackend.UpdateTasks was called");
try {
foreach (var list in lists.listCollection) {
Tasks tasks = null;
try {
tasks = rtm.TasksGetList (list.ID);
} catch (Exception tglex) {
Debug.WriteLine ("Exception calling TasksGetList(list.ListID) " + tglex.Message);
}
if (tasks != null) {
foreach (var tList in tasks.ListCollection) {
if (tList.TaskSeriesCollection == null)
continue;
foreach (var ts in tList.TaskSeriesCollection) {
lock (taskLock) {
Application.Instance.Dispatcher.Invoke (delegate {
if (!Tasks.Any (t => ((RtmTask)t).ID == ts.TaskID)) {
var rtmTask = new RtmTask (ts, this, list.ID);
var cat = Categories.SingleOrDefault (
c => ((RtmCategory)c).ID == list.ID);
if (cat != null)
cat.Add (rtmTask);
}
});
}
}
}
}
}
} catch (Exception e) {
Debug.WriteLine ("Exception in fetch " + e.Message);
Debug.WriteLine (e.ToString ());
}
Debug.WriteLine ("RtmBackend.UpdateTasks is done");
}
void RefreshThreadLoop ()
{
while (runningRefreshThread) {
runRefreshEvent.WaitOne ();
if (!runningRefreshThread)
return;
// Fire the event on the main thread
Application.Instance.Dispatcher.Invoke (delegate { OnBackendSyncStarted (); });
if (rtmAuth != null) {
var lists = rtm.ListsGetList ();
UpdateCategories (lists);
UpdateTasks (lists);
}
// Fire the event on the main thread
Application.Instance.Dispatcher.Invoke (delegate {
if (!Initialized)
Initialized = true;
});
}
// Fire the event on the main thread
Application.Instance.Dispatcher.Invoke (delegate { OnBackendSyncFinished (); });
}
#endregion // Private Methods
const string ApiKey = "b29f7517b6584035d07df3170b80c430";
const string SharedSecret = "93eb5f83628b2066";
Thread refreshThread;
bool runningRefreshThread;
AutoResetEvent runRefreshEvent;
Rtm rtm;
string frob;
Auth rtmAuth;
string timeline;
object taskLock, catLock;
}
}
| |
using System;
using System.Linq;
using System.Reactive.Linq;
using Avalonia.Input.Raw;
using Avalonia.Interactivity;
using Avalonia.Platform;
using Avalonia.VisualTree;
namespace Avalonia.Input
{
/// <summary>
/// Represents a mouse device.
/// </summary>
public class MouseDevice : IMouseDevice, IDisposable
{
private int _clickCount;
private Rect _lastClickRect;
private ulong _lastClickTime;
private readonly Pointer _pointer;
private bool _disposed;
private PixelPoint? _position;
public MouseDevice(Pointer? pointer = null)
{
_pointer = pointer ?? new Pointer(Pointer.GetNextFreeId(), PointerType.Mouse, true);
}
/// <summary>
/// Gets the control that is currently capturing by the mouse, if any.
/// </summary>
/// <remarks>
/// When an element captures the mouse, it receives mouse input whether the cursor is
/// within the control's bounds or not. To set the mouse capture, call the
/// <see cref="Capture"/> method.
/// </remarks>
[Obsolete("Use IPointer instead")]
public IInputElement? Captured => _pointer.Captured;
/// <summary>
/// Gets the mouse position, in screen coordinates.
/// </summary>
[Obsolete("Use events instead")]
public PixelPoint Position
{
get => _position ?? new PixelPoint(-1, -1);
protected set => _position = value;
}
/// <summary>
/// Captures mouse input to the specified control.
/// </summary>
/// <param name="control">The control.</param>
/// <remarks>
/// When an element captures the mouse, it receives mouse input whether the cursor is
/// within the control's bounds or not. The current mouse capture control is exposed
/// by the <see cref="Captured"/> property.
/// </remarks>
public void Capture(IInputElement? control)
{
_pointer.Capture(control);
}
/// <summary>
/// Gets the mouse position relative to a control.
/// </summary>
/// <param name="relativeTo">The control.</param>
/// <returns>The mouse position in the control's coordinates.</returns>
public Point GetPosition(IVisual relativeTo)
{
relativeTo = relativeTo ?? throw new ArgumentNullException(nameof(relativeTo));
if (relativeTo.VisualRoot == null)
{
throw new InvalidOperationException("Control is not attached to visual tree.");
}
#pragma warning disable CS0618 // Type or member is obsolete
var rootPoint = relativeTo.VisualRoot.PointToClient(Position);
#pragma warning restore CS0618 // Type or member is obsolete
var transform = relativeTo.VisualRoot.TransformToVisual(relativeTo);
return rootPoint * transform!.Value;
}
public void ProcessRawEvent(RawInputEventArgs e)
{
if (!e.Handled && e is RawPointerEventArgs margs)
ProcessRawEvent(margs);
}
public void TopLevelClosed(IInputRoot root)
{
ClearPointerOver(this, 0, root, PointerPointProperties.None, KeyModifiers.None);
}
public void SceneInvalidated(IInputRoot root, Rect rect)
{
// Pointer is outside of the target area
if (_position == null )
{
if (root.PointerOverElement != null)
ClearPointerOver(this, 0, root, PointerPointProperties.None, KeyModifiers.None);
return;
}
var clientPoint = root.PointToClient(_position.Value);
if (rect.Contains(clientPoint))
{
if (_pointer.Captured == null)
{
SetPointerOver(this, 0 /* TODO: proper timestamp */, root, clientPoint,
PointerPointProperties.None, KeyModifiers.None);
}
else
{
SetPointerOver(this, 0 /* TODO: proper timestamp */, root, _pointer.Captured,
PointerPointProperties.None, KeyModifiers.None);
}
}
}
int ButtonCount(PointerPointProperties props)
{
var rv = 0;
if (props.IsLeftButtonPressed)
rv++;
if (props.IsMiddleButtonPressed)
rv++;
if (props.IsRightButtonPressed)
rv++;
if (props.IsXButton1Pressed)
rv++;
if (props.IsXButton2Pressed)
rv++;
return rv;
}
private void ProcessRawEvent(RawPointerEventArgs e)
{
e = e ?? throw new ArgumentNullException(nameof(e));
var mouse = (MouseDevice)e.Device;
if(mouse._disposed)
return;
_position = e.Root.PointToScreen(e.Position);
var props = CreateProperties(e);
var keyModifiers = KeyModifiersUtils.ConvertToKey(e.InputModifiers);
switch (e.Type)
{
case RawPointerEventType.LeaveWindow:
LeaveWindow(mouse, e.Timestamp, e.Root, props, keyModifiers);
break;
case RawPointerEventType.LeftButtonDown:
case RawPointerEventType.RightButtonDown:
case RawPointerEventType.MiddleButtonDown:
case RawPointerEventType.XButton1Down:
case RawPointerEventType.XButton2Down:
if (ButtonCount(props) > 1)
e.Handled = MouseMove(mouse, e.Timestamp, e.Root, e.Position, props, keyModifiers);
else
e.Handled = MouseDown(mouse, e.Timestamp, e.Root, e.Position,
props, keyModifiers);
break;
case RawPointerEventType.LeftButtonUp:
case RawPointerEventType.RightButtonUp:
case RawPointerEventType.MiddleButtonUp:
case RawPointerEventType.XButton1Up:
case RawPointerEventType.XButton2Up:
if (ButtonCount(props) != 0)
e.Handled = MouseMove(mouse, e.Timestamp, e.Root, e.Position, props, keyModifiers);
else
e.Handled = MouseUp(mouse, e.Timestamp, e.Root, e.Position, props, keyModifiers);
break;
case RawPointerEventType.Move:
e.Handled = MouseMove(mouse, e.Timestamp, e.Root, e.Position, props, keyModifiers);
break;
case RawPointerEventType.Wheel:
e.Handled = MouseWheel(mouse, e.Timestamp, e.Root, e.Position, props, ((RawMouseWheelEventArgs)e).Delta, keyModifiers);
break;
}
}
private void LeaveWindow(IMouseDevice device, ulong timestamp, IInputRoot root, PointerPointProperties properties,
KeyModifiers inputModifiers)
{
device = device ?? throw new ArgumentNullException(nameof(device));
root = root ?? throw new ArgumentNullException(nameof(root));
_position = null;
ClearPointerOver(this, timestamp, root, properties, inputModifiers);
}
PointerPointProperties CreateProperties(RawPointerEventArgs args)
{
var kind = PointerUpdateKind.Other;
if (args.Type == RawPointerEventType.LeftButtonDown)
kind = PointerUpdateKind.LeftButtonPressed;
if (args.Type == RawPointerEventType.MiddleButtonDown)
kind = PointerUpdateKind.MiddleButtonPressed;
if (args.Type == RawPointerEventType.RightButtonDown)
kind = PointerUpdateKind.RightButtonPressed;
if (args.Type == RawPointerEventType.XButton1Down)
kind = PointerUpdateKind.XButton1Pressed;
if (args.Type == RawPointerEventType.XButton2Down)
kind = PointerUpdateKind.XButton2Pressed;
if (args.Type == RawPointerEventType.LeftButtonUp)
kind = PointerUpdateKind.LeftButtonReleased;
if (args.Type == RawPointerEventType.MiddleButtonUp)
kind = PointerUpdateKind.MiddleButtonReleased;
if (args.Type == RawPointerEventType.RightButtonUp)
kind = PointerUpdateKind.RightButtonReleased;
if (args.Type == RawPointerEventType.XButton1Up)
kind = PointerUpdateKind.XButton1Released;
if (args.Type == RawPointerEventType.XButton2Up)
kind = PointerUpdateKind.XButton2Released;
return new PointerPointProperties(args.InputModifiers, kind);
}
private MouseButton _lastMouseDownButton;
private bool MouseDown(IMouseDevice device, ulong timestamp, IInputElement root, Point p,
PointerPointProperties properties,
KeyModifiers inputModifiers)
{
device = device ?? throw new ArgumentNullException(nameof(device));
root = root ?? throw new ArgumentNullException(nameof(root));
var hit = HitTest(root, p);
if (hit != null)
{
_pointer.Capture(hit);
var source = GetSource(hit);
if (source != null)
{
var settings = AvaloniaLocator.Current.GetService<IPlatformSettings>();
var doubleClickTime = settings?.DoubleClickTime.TotalMilliseconds ?? 500;
var doubleClickSize = settings?.DoubleClickSize ?? new Size(4, 4);
if (!_lastClickRect.Contains(p) || timestamp - _lastClickTime > doubleClickTime)
{
_clickCount = 0;
}
++_clickCount;
_lastClickTime = timestamp;
_lastClickRect = new Rect(p, new Size())
.Inflate(new Thickness(doubleClickSize.Width / 2, doubleClickSize.Height / 2));
_lastMouseDownButton = properties.PointerUpdateKind.GetMouseButton();
var e = new PointerPressedEventArgs(source, _pointer, root, p, timestamp, properties, inputModifiers, _clickCount);
source.RaiseEvent(e);
return e.Handled;
}
}
return false;
}
private bool MouseMove(IMouseDevice device, ulong timestamp, IInputRoot root, Point p, PointerPointProperties properties,
KeyModifiers inputModifiers)
{
device = device ?? throw new ArgumentNullException(nameof(device));
root = root ?? throw new ArgumentNullException(nameof(root));
IInputElement? source;
if (_pointer.Captured == null)
{
source = SetPointerOver(this, timestamp, root, p, properties, inputModifiers);
}
else
{
SetPointerOver(this, timestamp, root, _pointer.Captured, properties, inputModifiers);
source = _pointer.Captured;
}
if (source is object)
{
var e = new PointerEventArgs(InputElement.PointerMovedEvent, source, _pointer, root,
p, timestamp, properties, inputModifiers);
source.RaiseEvent(e);
return e.Handled;
}
return false;
}
private bool MouseUp(IMouseDevice device, ulong timestamp, IInputRoot root, Point p, PointerPointProperties props,
KeyModifiers inputModifiers)
{
device = device ?? throw new ArgumentNullException(nameof(device));
root = root ?? throw new ArgumentNullException(nameof(root));
var hit = HitTest(root, p);
var source = GetSource(hit);
if (source is not null)
{
var e = new PointerReleasedEventArgs(source, _pointer, root, p, timestamp, props, inputModifiers,
_lastMouseDownButton);
source?.RaiseEvent(e);
_pointer.Capture(null);
return e.Handled;
}
return false;
}
private bool MouseWheel(IMouseDevice device, ulong timestamp, IInputRoot root, Point p,
PointerPointProperties props,
Vector delta, KeyModifiers inputModifiers)
{
device = device ?? throw new ArgumentNullException(nameof(device));
root = root ?? throw new ArgumentNullException(nameof(root));
var hit = HitTest(root, p);
var source = GetSource(hit);
if (source is not null)
{
var e = new PointerWheelEventArgs(source, _pointer, root, p, timestamp, props, inputModifiers, delta);
source?.RaiseEvent(e);
return e.Handled;
}
return false;
}
private IInteractive? GetSource(IVisual? hit)
{
if (hit is null)
return null;
return _pointer.Captured ??
(hit as IInteractive) ??
hit.GetSelfAndVisualAncestors().OfType<IInteractive>().FirstOrDefault();
}
private IInputElement? HitTest(IInputElement root, Point p)
{
root = root ?? throw new ArgumentNullException(nameof(root));
return _pointer.Captured ?? root.InputHitTest(p);
}
PointerEventArgs CreateSimpleEvent(RoutedEvent ev, ulong timestamp, IInteractive? source,
PointerPointProperties properties,
KeyModifiers inputModifiers)
{
return new PointerEventArgs(ev, source, _pointer, null, default,
timestamp, properties, inputModifiers);
}
private void ClearPointerOver(IPointerDevice device, ulong timestamp, IInputRoot root,
PointerPointProperties properties,
KeyModifiers inputModifiers)
{
device = device ?? throw new ArgumentNullException(nameof(device));
root = root ?? throw new ArgumentNullException(nameof(root));
var element = root.PointerOverElement;
var e = CreateSimpleEvent(InputElement.PointerLeaveEvent, timestamp, element, properties, inputModifiers);
if (element!=null && !element.IsAttachedToVisualTree)
{
// element has been removed from visual tree so do top down cleanup
if (root.IsPointerOver)
ClearChildrenPointerOver(e, root,true);
}
while (element != null)
{
e.Source = element;
e.Handled = false;
element.RaiseEvent(e);
element = (IInputElement?)element.VisualParent;
}
root.PointerOverElement = null;
}
private void ClearChildrenPointerOver(PointerEventArgs e, IInputElement element,bool clearRoot)
{
foreach (IInputElement el in element.VisualChildren)
{
if (el.IsPointerOver)
{
ClearChildrenPointerOver(e, el, true);
break;
}
}
if(clearRoot)
{
e.Source = element;
e.Handled = false;
element.RaiseEvent(e);
}
}
private IInputElement? SetPointerOver(IPointerDevice device, ulong timestamp, IInputRoot root, Point p,
PointerPointProperties properties,
KeyModifiers inputModifiers)
{
device = device ?? throw new ArgumentNullException(nameof(device));
root = root ?? throw new ArgumentNullException(nameof(root));
var element = root.InputHitTest(p);
if (element != root.PointerOverElement)
{
if (element != null)
{
SetPointerOver(device, timestamp, root, element, properties, inputModifiers);
}
else
{
ClearPointerOver(device, timestamp, root, properties, inputModifiers);
}
}
return element;
}
private void SetPointerOver(IPointerDevice device, ulong timestamp, IInputRoot root, IInputElement element,
PointerPointProperties properties,
KeyModifiers inputModifiers)
{
device = device ?? throw new ArgumentNullException(nameof(device));
root = root ?? throw new ArgumentNullException(nameof(root));
element = element ?? throw new ArgumentNullException(nameof(element));
IInputElement? branch = null;
IInputElement? el = element;
while (el != null)
{
if (el.IsPointerOver)
{
branch = el;
break;
}
el = (IInputElement?)el.VisualParent;
}
el = root.PointerOverElement;
var e = CreateSimpleEvent(InputElement.PointerLeaveEvent, timestamp, el, properties, inputModifiers);
if (el!=null && branch!=null && !el.IsAttachedToVisualTree)
{
ClearChildrenPointerOver(e,branch,false);
}
while (el != null && el != branch)
{
e.Source = el;
e.Handled = false;
el.RaiseEvent(e);
el = (IInputElement?)el.VisualParent;
}
el = root.PointerOverElement = element;
e.RoutedEvent = InputElement.PointerEnterEvent;
while (el != null && el != branch)
{
e.Source = el;
e.Handled = false;
el.RaiseEvent(e);
el = (IInputElement?)el.VisualParent;
}
}
public void Dispose()
{
_disposed = true;
_pointer?.Dispose();
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.ResourceManager
{
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// DeploymentsOperations operations.
/// </summary>
public partial interface IDeploymentsOperations
{
/// <summary>
/// Delete deployment.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group. The name is case insensitive.
/// </param>
/// <param name='deploymentName'>
/// The name of the deployment to be deleted.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string deploymentName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Checks whether deployment exists.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group to check. The name is case
/// insensitive.
/// </param>
/// <param name='deploymentName'>
/// The name of the deployment.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<bool>> CheckExistenceWithHttpMessagesAsync(string resourceGroupName, string deploymentName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Create a named template deployment using a template.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group. The name is case insensitive.
/// </param>
/// <param name='deploymentName'>
/// The name of the deployment.
/// </param>
/// <param name='parameters'>
/// Additional parameters supplied to the operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<DeploymentExtended>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string deploymentName, Deployment parameters, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Get a deployment.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group to get. The name is case
/// insensitive.
/// </param>
/// <param name='deploymentName'>
/// The name of the deployment.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<DeploymentExtended>> GetWithHttpMessagesAsync(string resourceGroupName, string deploymentName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Cancel a currently running template deployment.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group. The name is case insensitive.
/// </param>
/// <param name='deploymentName'>
/// The name of the deployment.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> CancelWithHttpMessagesAsync(string resourceGroupName, string deploymentName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Validate a deployment template.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group. The name is case insensitive.
/// </param>
/// <param name='deploymentName'>
/// The name of the deployment.
/// </param>
/// <param name='parameters'>
/// Deployment to validate.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<DeploymentValidateResult>> ValidateWithHttpMessagesAsync(string resourceGroupName, string deploymentName, Deployment parameters, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Exports a deployment template.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group. The name is case insensitive.
/// </param>
/// <param name='deploymentName'>
/// The name of the deployment.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<DeploymentExportResult>> ExportTemplateWithHttpMessagesAsync(string resourceGroupName, string deploymentName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Get a list of deployments.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group to filter by. The name is case
/// insensitive.
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<DeploymentExtended>>> ListWithHttpMessagesAsync(string resourceGroupName, Microsoft.Rest.Azure.OData.ODataQuery<DeploymentExtendedFilter> odataQuery = default(Microsoft.Rest.Azure.OData.ODataQuery<DeploymentExtendedFilter>), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Delete deployment.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group. The name is case insensitive.
/// </param>
/// <param name='deploymentName'>
/// The name of the deployment to be deleted.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string deploymentName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Create a named template deployment using a template.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group. The name is case insensitive.
/// </param>
/// <param name='deploymentName'>
/// The name of the deployment.
/// </param>
/// <param name='parameters'>
/// Additional parameters supplied to the operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<DeploymentExtended>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string deploymentName, Deployment parameters, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Get a list of deployments.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<DeploymentExtended>>> ListNextWithHttpMessagesAsync(string nextPageLink, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
/*============================================================
**
**
**
**
**
**
** Purpose: Exception for failure to load a file that was successfully found.
**
**
===========================================================*/
using System;
using System.Globalization;
using System.Runtime.Serialization;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Security;
using System.Security.Permissions;
using System.Runtime.Versioning;
using SecurityException = System.Security.SecurityException;
namespace System.IO {
[Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public class FileLoadException : IOException {
private String _fileName; // the name of the file we could not load.
private String _fusionLog; // fusion log (when applicable)
public FileLoadException()
: base(Environment.GetResourceString("IO.FileLoad")) {
SetErrorCode(__HResults.COR_E_FILELOAD);
}
public FileLoadException(String message)
: base(message) {
SetErrorCode(__HResults.COR_E_FILELOAD);
}
public FileLoadException(String message, Exception inner)
: base(message, inner) {
SetErrorCode(__HResults.COR_E_FILELOAD);
}
public FileLoadException(String message, String fileName) : base(message)
{
SetErrorCode(__HResults.COR_E_FILELOAD);
_fileName = fileName;
}
public FileLoadException(String message, String fileName, Exception inner)
: base(message, inner) {
SetErrorCode(__HResults.COR_E_FILELOAD);
_fileName = fileName;
}
public override String Message
{
get {
SetMessageField();
return _message;
}
}
private void SetMessageField()
{
if (_message == null)
_message = FormatFileLoadExceptionMessage(_fileName, HResult);
}
public String FileName {
get { return _fileName; }
}
#if FEATURE_LEGACYNETCF
// override Data property to populate FileLoadException with Hresult
public override System.Collections.IDictionary Data {
[System.Security.SecuritySafeCritical]
get {
var _data = base.Data;
if (CompatibilitySwitches.IsAppEarlierThanWindowsPhone8 && !_data.Contains("HResult"))
{
_data.Add("HResult", HResult);
}
return _data;
}
}
#endif //FEATURE_LEGACYNETCF
public override String ToString()
{
String s = GetType().FullName + ": " + Message;
if (_fileName != null && _fileName.Length != 0)
s += Environment.NewLine + Environment.GetResourceString("IO.FileName_Name", _fileName);
if (InnerException != null)
s = s + " ---> " + InnerException.ToString();
if (StackTrace != null)
s += Environment.NewLine + StackTrace;
#if FEATURE_FUSION
try
{
if(FusionLog!=null)
{
if (s==null)
s=" ";
s+=Environment.NewLine;
s+=Environment.NewLine;
s+=FusionLog;
}
}
catch(SecurityException)
{
}
#endif // FEATURE_FUSION
return s;
}
protected FileLoadException(SerializationInfo info, StreamingContext context) : base (info, context) {
// Base class constructor will check info != null.
_fileName = info.GetString("FileLoad_FileName");
try
{
_fusionLog = info.GetString("FileLoad_FusionLog");
}
catch
{
_fusionLog = null;
}
}
private FileLoadException(String fileName, String fusionLog,int hResult)
: base(null)
{
SetErrorCode(hResult);
_fileName = fileName;
_fusionLog=fusionLog;
SetMessageField();
}
#if FEATURE_FUSION
public String FusionLog {
[System.Security.SecuritySafeCritical] // auto-generated
[SecurityPermissionAttribute( SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlEvidence | SecurityPermissionFlag.ControlPolicy)]
get { return _fusionLog; }
}
#endif // FEATURE_FUSION
#if FEATURE_SERIALIZATION
[System.Security.SecurityCritical] // auto-generated_required
public override void GetObjectData(SerializationInfo info, StreamingContext context) {
// Serialize data for our base classes. base will verify info != null.
base.GetObjectData(info, context);
// Serialize data for this class
info.AddValue("FileLoad_FileName", _fileName, typeof(String));
try
{
info.AddValue("FileLoad_FusionLog", FusionLog, typeof(String));
}
catch (SecurityException)
{
}
}
#endif
[System.Security.SecuritySafeCritical] // auto-generated
internal static String FormatFileLoadExceptionMessage(String fileName,
int hResult)
{
string format = null;
GetFileLoadExceptionMessage(hResult, JitHelpers.GetStringHandleOnStack(ref format));
string message = null;
GetMessageForHR(hResult, JitHelpers.GetStringHandleOnStack(ref message));
return String.Format(CultureInfo.CurrentCulture, format, fileName, message);
}
[System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern void GetFileLoadExceptionMessage(int hResult, StringHandleOnStack retString);
[System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern void GetMessageForHR(int hresult, StringHandleOnStack retString);
}
}
| |
// The MIT License (MIT)
//
// Copyright (c) 2014-2017, Institute for Software & Systems Engineering
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
namespace SafetySharp.Runtime.Serialization
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Modeling;
using Serializers;
using Utilities;
using ISSE.SafetyChecking.Utilities;
/// <summary>
/// Represents a registry of <see cref="Serializer" />s.
/// </summary>
public sealed class SerializationRegistry
{
/// <summary>
/// The default serialization registry instance.
/// </summary>
public static readonly SerializationRegistry Default = new SerializationRegistry();
/// <summary>
/// The list of registered serializers.
/// </summary>
private readonly List<Serializer> _serializers = new List<Serializer>();
/// <summary>
/// Initializes a new instance.
/// </summary>
private SerializationRegistry()
{
RegisterSerializer(new ObjectSerializer());
RegisterSerializer(new BoxedValueSerializer());
RegisterSerializer(new FaultEffectSerializer());
RegisterSerializer(new ArraySerializer());
RegisterSerializer(new ListSerializer());
RegisterSerializer(new DictionarySerializer());
RegisterSerializer(new StringSerializer());
RegisterSerializer(new TypeSerializer());
RegisterSerializer(new MethodInfoSerializer());
RegisterSerializer(new DelegateSerializer());
}
/// <summary>
/// Registers the <paramref name="serializer" />. The newly added <paramref name="serializer" /> is the first one to be
/// considered for the serialization of an object; the previously added serializers are only considered if the new
/// <paramref name="serializer" />'s <see cref="Serializer.CanSerialize" /> method returns <c>false</c> for an object.
/// </summary>
/// <param name="serializer">The serializer that should be registered.</param>
private void RegisterSerializer(Serializer serializer)
{
Requires.NotNull(serializer, nameof(serializer));
Requires.That(!_serializers.Contains(serializer), nameof(serializer),
$"The serializer '{serializer.GetType().FullName}' has already been registered.");
_serializers.Add(serializer);
}
/// <summary>
/// Tries to find a serializer that is able to serialize the <paramref name="obj" />.
/// </summary>
internal Serializer GetSerializer(object obj)
{
return GetSerializer(GetSerializerIndex(obj));
}
/// <summary>
/// Gets the serializer at the <paramref name="index" />.
/// </summary>
internal Serializer GetSerializer(int index)
{
return _serializers[index];
}
/// <summary>
/// Tries to find the index of a serializer that is able to serialize the <paramref name="obj" />.
/// </summary>
internal int GetSerializerIndex(object obj)
{
return _serializers.FindLastIndex(s => s.CanSerialize(obj));
}
/// <summary>
/// Generates the <see cref="StateVectorLayout" /> for the <paramref name="objects" />.
/// </summary>
/// <param name="model">The model the state vector should be layouted for.</param>
/// <param name="objects">The objects consisting of state values the state vector layout should be generated for.</param>
/// <param name="mode">The serialization mode that should be used to generate the state vector layout.</param>
internal StateVectorLayout GetStateVectorLayout(ModelBase model, ObjectTable objects, SerializationMode mode)
{
Requires.NotNull(model, nameof(model));
Requires.NotNull(objects, nameof(objects));
Requires.InRange(mode, nameof(mode));
var layout = new StateVectorLayout();
foreach (var slot in objects.SelectMany(obj => GetSerializer(obj).GetStateSlotMetadata(obj, objects.GetObjectIdentifier(obj), mode)))
layout.Add(slot);
layout.Compact(model, mode);
return layout;
}
/// <summary>
/// Gets all objects referenced by the <paramref name="objects" />, not including <paramref name="objects" /> itself.
/// </summary>
/// <param name="objects">The objects the referenced objects should be returned for.</param>
/// <param name="mode">The serialization mode that should be used to serialize the objects.</param>
internal IEnumerable<object> GetReferencedObjects(object[] objects, SerializationMode mode)
{
Requires.NotNull(objects, nameof(objects));
var referencedObjects = new HashSet<object>(ReferenceEqualityComparer<object>.Default);
foreach (var obj in objects)
{
referencedObjects.Add(obj);
GetReferencedObjects(referencedObjects, obj, mode);
}
return referencedObjects;
}
/// <summary>
/// Adds all objects referenced by <paramref name="obj" />, excluding <paramref name="obj" /> itself, to the set of
/// <paramref name="referencedObjects" />.
/// </summary>
/// <param name="referencedObjects">The set of referenced objects.</param>
/// <param name="obj">The object the referenced objects should be returned for.</param>
/// <param name="mode">The serialization mode that should be used to serialize the objects.</param>
private void GetReferencedObjects(HashSet<object> referencedObjects, object obj, SerializationMode mode)
{
foreach (var referencedObject in GetSerializer(obj).GetReferencedObjects(obj, mode))
{
if (referencedObject != null && referencedObjects.Add(referencedObject))
GetReferencedObjects(referencedObjects, referencedObject, mode);
}
}
/// <summary>
/// Gets all objects referenced by the value-typed <paramref name="obj" />.
/// </summary>
/// <param name="obj">The value-typed object the referenced objects should be returned for.</param>
/// <param name="mode">The serialization mode that should be used to serialize the objects.</param>
internal IEnumerable<object> GetObjectsReferencedByStruct(object obj, SerializationMode mode)
{
Requires.NotNull(obj, nameof(obj));
Requires.That(obj.GetType().IsStructType(), "Expected a value-typed object.");
var referencedObjects = new HashSet<object>(ReferenceEqualityComparer<object>.Default);
GetObjectsReferencedByStruct(referencedObjects, obj, mode);
return referencedObjects;
}
/// <summary>
/// Adds all objects referenced by the value-typed <paramref name="obj" /> to the set of <paramref name="referencedObjects" />
/// .
/// </summary>
/// <param name="referencedObjects">The set of referenced objects.</param>
/// <param name="obj">The value-typed object the referenced objects should be returned for.</param>
/// <param name="mode">The serialization mode that should be used to serialize the objects.</param>
private static void GetObjectsReferencedByStruct(HashSet<object> referencedObjects, object obj, SerializationMode mode)
{
foreach (var field in GetSerializationFields(obj.GetType(), mode))
{
if (field.FieldType.IsStructType())
{
var fieldValue = field.GetValue(obj);
if (fieldValue != null)
GetObjectsReferencedByStruct(referencedObjects, fieldValue, mode);
}
else if (field.FieldType.IsReferenceType())
{
var referencedObj = field.GetValue(obj);
if (referencedObj != null)
referencedObjects.Add(referencedObj);
}
}
}
/// <summary>
/// Gets the fields declared by the <paramref name="type" /> that should be serialized.
/// </summary>
/// <param name="type">The type that should be serialized.</param>
/// <param name="mode">The serialization mode that should be used to serialize the objects.</param>
/// <param name="inheritanceRoot">
/// The first base of <paramref name="type" /> whose fields should be ignored. If
/// <c>null</c>, <see cref="object" /> is the inheritance root.
/// </param>
/// <param name="discoveringObjects">Indicates whether objects are being discovered.</param>
internal static IEnumerable<FieldInfo> GetSerializationFields(Type type, SerializationMode mode,
Type inheritanceRoot = null,bool discoveringObjects = false)
{
if (type.IsHidden(mode, discoveringObjects))
return Enumerable.Empty<FieldInfo>();
var fields = type.GetFields(inheritanceRoot ?? typeof(object)).Where(field =>
{
// Ignore static or constant fields
if (field.IsStatic || field.IsLiteral)
return false;
// Don't try to serialize hidden fields
if (field.IsHidden(mode, discoveringObjects) || field.FieldType.IsHidden(mode, discoveringObjects))
return false;
// Otherwise, serialize the field
return true;
});
// It is important to sort the fields in a deterministic order; by default, .NET's reflection APIs don't
// return fields in any particular order at all, which obviously causes problems when we then go on to try
// to deserialize fields in a different order than the one that was used to serialize them
return fields.OrderBy(field => field.DeclaringType.FullName).ThenBy(field => field.Name);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.Xunit.Performance;
using System;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Reflection;
using System.Collections.Generic;
using Xunit;
[assembly: OptimizeForBenchmarks]
[assembly: MeasureInstructionsRetired]
public static class ConstantArgsInt
{
#if DEBUG
public const int Iterations = 1;
#else
public const int Iterations = 100000;
#endif
// Ints feeding math operations.
//
// Inlining in Bench0xp should enable constant folding
// Inlining in Bench0xn will not enable constant folding
static int Five = 5;
static int Ten = 10;
static int Id(int x)
{
return x;
}
static int F00(int x)
{
return x * x;
}
static bool Bench00p()
{
int t = 10;
int f = F00(t);
return (f == 100);
}
static bool Bench00n()
{
int t = Ten;
int f = F00(t);
return (f == 100);
}
static bool Bench00p1()
{
int t = Id(10);
int f = F00(t);
return (f == 100);
}
static bool Bench00n1()
{
int t = Id(Ten);
int f = F00(t);
return (f == 100);
}
static bool Bench00p2()
{
int t = Id(10);
int f = F00(Id(t));
return (f == 100);
}
static bool Bench00n2()
{
int t = Id(Ten);
int f = F00(Id(t));
return (f == 100);
}
static bool Bench00p3()
{
int t = 10;
int f = F00(Id(Id(t)));
return (f == 100);
}
static bool Bench00n3()
{
int t = Ten;
int f = F00(Id(Id(t)));
return (f == 100);
}
static bool Bench00p4()
{
int t = 5;
int f = F00(2 * t);
return (f == 100);
}
static bool Bench00n4()
{
int t = Five;
int f = F00(2 * t);
return (f == 100);
}
static int F01(int x)
{
return 1000 / x;
}
static bool Bench01p()
{
int t = 10;
int f = F01(t);
return (f == 100);
}
static bool Bench01n()
{
int t = Ten;
int f = F01(t);
return (f == 100);
}
static int F02(int x)
{
return 20 * (x / 2);
}
static bool Bench02p()
{
int t = 10;
int f = F02(t);
return (f == 100);
}
static bool Bench02n()
{
int t = Ten;
int f = F02(t);
return (f == 100);
}
static int F03(int x)
{
return 91 + 1009 % x;
}
static bool Bench03p()
{
int t = 10;
int f = F03(t);
return (f == 100);
}
static bool Bench03n()
{
int t = Ten;
int f = F03(t);
return (f == 100);
}
static int F04(int x)
{
return 50 * (x % 4);
}
static bool Bench04p()
{
int t = 10;
int f = F04(t);
return (f == 100);
}
static bool Bench04n()
{
int t = Ten;
int f = F04(t);
return (f == 100);
}
static int F05(int x)
{
return (1 << x) - 924;
}
static bool Bench05p()
{
int t = 10;
int f = F05(t);
return (f == 100);
}
static bool Bench05n()
{
int t = Ten;
int f = F05(t);
return (f == 100);
}
static int F051(int x)
{
return (102400 >> x);
}
static bool Bench05p1()
{
int t = 10;
int f = F051(t);
return (f == 100);
}
static bool Bench05n1()
{
int t = Ten;
int f = F051(t);
return (f == 100);
}
static int F06(int x)
{
return -x + 110;
}
static bool Bench06p()
{
int t = 10;
int f = F06(t);
return (f == 100);
}
static bool Bench06n()
{
int t = Ten;
int f = F06(t);
return (f == 100);
}
static int F07(int x)
{
return ~x + 111;
}
static bool Bench07p()
{
int t = 10;
int f = F07(t);
return (f == 100);
}
static bool Bench07n()
{
int t = Ten;
int f = F07(t);
return (f == 100);
}
static int F071(int x)
{
return (x ^ -1) + 111;
}
static bool Bench07p1()
{
int t = 10;
int f = F071(t);
return (f == 100);
}
static bool Bench07n1()
{
int t = Ten;
int f = F071(t);
return (f == 100);
}
static int F08(int x)
{
return (x & 0x7) + 98;
}
static bool Bench08p()
{
int t = 10;
int f = F08(t);
return (f == 100);
}
static bool Bench08n()
{
int t = Ten;
int f = F08(t);
return (f == 100);
}
static int F09(int x)
{
return (x | 0x7) + 85;
}
static bool Bench09p()
{
int t = 10;
int f = F09(t);
return (f == 100);
}
static bool Bench09n()
{
int t = Ten;
int f = F09(t);
return (f == 100);
}
// Ints feeding comparisons.
//
// Inlining in Bench1xp should enable branch optimization
// Inlining in Bench1xn will not enable branch optimization
static int F10(int x)
{
return x == 10 ? 100 : 0;
}
static bool Bench10p()
{
int t = 10;
int f = F10(t);
return (f == 100);
}
static bool Bench10n()
{
int t = Ten;
int f = F10(t);
return (f == 100);
}
static int F101(int x)
{
return x != 10 ? 0 : 100;
}
static bool Bench10p1()
{
int t = 10;
int f = F101(t);
return (f == 100);
}
static bool Bench10n1()
{
int t = Ten;
int f = F101(t);
return (f == 100);
}
static int F102(int x)
{
return x >= 10 ? 100 : 0;
}
static bool Bench10p2()
{
int t = 10;
int f = F102(t);
return (f == 100);
}
static bool Bench10n2()
{
int t = Ten;
int f = F102(t);
return (f == 100);
}
static int F103(int x)
{
return x <= 10 ? 100 : 0;
}
static bool Bench10p3()
{
int t = 10;
int f = F103(t);
return (f == 100);
}
static bool Bench10n3()
{
int t = Ten;
int f = F102(t);
return (f == 100);
}
static int F11(int x)
{
if (x == 10)
{
return 100;
}
else
{
return 0;
}
}
static bool Bench11p()
{
int t = 10;
int f = F11(t);
return (f == 100);
}
static bool Bench11n()
{
int t = Ten;
int f = F11(t);
return (f == 100);
}
static int F111(int x)
{
if (x != 10)
{
return 0;
}
else
{
return 100;
}
}
static bool Bench11p1()
{
int t = 10;
int f = F111(t);
return (f == 100);
}
static bool Bench11n1()
{
int t = Ten;
int f = F111(t);
return (f == 100);
}
static int F112(int x)
{
if (x > 10)
{
return 0;
}
else
{
return 100;
}
}
static bool Bench11p2()
{
int t = 10;
int f = F112(t);
return (f == 100);
}
static bool Bench11n2()
{
int t = Ten;
int f = F112(t);
return (f == 100);
}
static int F113(int x)
{
if (x < 10)
{
return 0;
}
else
{
return 100;
}
}
static bool Bench11p3()
{
int t = 10;
int f = F113(t);
return (f == 100);
}
static bool Bench11n3()
{
int t = Ten;
int f = F113(t);
return (f == 100);
}
// Ununsed (or effectively unused) parameters
//
// Simple callee analysis may overstate inline benefit
static int F20(int x)
{
return 100;
}
static bool Bench20p()
{
int t = 10;
int f = F20(t);
return (f == 100);
}
static bool Bench20p1()
{
int t = Ten;
int f = F20(t);
return (f == 100);
}
static int F21(int x)
{
return -x + 100 + x;
}
static bool Bench21p()
{
int t = 10;
int f = F21(t);
return (f == 100);
}
static bool Bench21n()
{
int t = Ten;
int f = F21(t);
return (f == 100);
}
static int F211(int x)
{
return x - x + 100;
}
static bool Bench21p1()
{
int t = 10;
int f = F211(t);
return (f == 100);
}
static bool Bench21n1()
{
int t = Ten;
int f = F211(t);
return (f == 100);
}
static int F22(int x)
{
if (x > 0)
{
return 100;
}
return 100;
}
static bool Bench22p()
{
int t = 10;
int f = F22(t);
return (f == 100);
}
static bool Bench22p1()
{
int t = Ten;
int f = F22(t);
return (f == 100);
}
static int F23(int x)
{
if (x > 0)
{
return 90 + x;
}
return 100;
}
static bool Bench23p()
{
int t = 10;
int f = F23(t);
return (f == 100);
}
static bool Bench23n()
{
int t = Ten;
int f = F23(t);
return (f == 100);
}
// Multiple parameters
static int F30(int x, int y)
{
return y * y;
}
static bool Bench30p()
{
int t = 10;
int f = F30(t, t);
return (f == 100);
}
static bool Bench30n()
{
int t = Ten;
int f = F30(t, t);
return (f == 100);
}
static bool Bench30p1()
{
int s = Ten;
int t = 10;
int f = F30(s, t);
return (f == 100);
}
static bool Bench30n1()
{
int s = 10;
int t = Ten;
int f = F30(s, t);
return (f == 100);
}
static bool Bench30p2()
{
int s = 10;
int t = 10;
int f = F30(s, t);
return (f == 100);
}
static bool Bench30n2()
{
int s = Ten;
int t = Ten;
int f = F30(s, t);
return (f == 100);
}
static bool Bench30p3()
{
int s = 10;
int t = s;
int f = F30(s, t);
return (f == 100);
}
static bool Bench30n3()
{
int s = Ten;
int t = s;
int f = F30(s, t);
return (f == 100);
}
static int F31(int x, int y, int z)
{
return z * z;
}
static bool Bench31p()
{
int t = 10;
int f = F31(t, t, t);
return (f == 100);
}
static bool Bench31n()
{
int t = Ten;
int f = F31(t, t, t);
return (f == 100);
}
static bool Bench31p1()
{
int r = Ten;
int s = Ten;
int t = 10;
int f = F31(r, s, t);
return (f == 100);
}
static bool Bench31n1()
{
int r = 10;
int s = 10;
int t = Ten;
int f = F31(r, s, t);
return (f == 100);
}
static bool Bench31p2()
{
int r = 10;
int s = 10;
int t = 10;
int f = F31(r, s, t);
return (f == 100);
}
static bool Bench31n2()
{
int r = Ten;
int s = Ten;
int t = Ten;
int f = F31(r, s, t);
return (f == 100);
}
static bool Bench31p3()
{
int r = 10;
int s = r;
int t = s;
int f = F31(r, s, t);
return (f == 100);
}
static bool Bench31n3()
{
int r = Ten;
int s = r;
int t = s;
int f = F31(r, s, t);
return (f == 100);
}
// Two args, both used
static int F40(int x, int y)
{
return x * x + y * y - 100;
}
static bool Bench40p()
{
int t = 10;
int f = F40(t, t);
return (f == 100);
}
static bool Bench40n()
{
int t = Ten;
int f = F40(t, t);
return (f == 100);
}
static bool Bench40p1()
{
int s = Ten;
int t = 10;
int f = F40(s, t);
return (f == 100);
}
static bool Bench40p2()
{
int s = 10;
int t = Ten;
int f = F40(s, t);
return (f == 100);
}
static int F41(int x, int y)
{
return x * y;
}
static bool Bench41p()
{
int t = 10;
int f = F41(t, t);
return (f == 100);
}
static bool Bench41n()
{
int t = Ten;
int f = F41(t, t);
return (f == 100);
}
static bool Bench41p1()
{
int s = 10;
int t = Ten;
int f = F41(s, t);
return (f == 100);
}
static bool Bench41p2()
{
int s = Ten;
int t = 10;
int f = F41(s, t);
return (f == 100);
}
private static IEnumerable<object[]> MakeArgs(params string[] args)
{
return args.Select(arg => new object[] { arg });
}
public static IEnumerable<object[]> TestFuncs = MakeArgs(
"Bench00p", "Bench00n",
"Bench00p1", "Bench00n1",
"Bench00p2", "Bench00n2",
"Bench00p3", "Bench00n3",
"Bench00p4", "Bench00n4",
"Bench01p", "Bench01n",
"Bench02p", "Bench02n",
"Bench03p", "Bench03n",
"Bench04p", "Bench04n",
"Bench05p", "Bench05n",
"Bench05p1", "Bench05n1",
"Bench06p", "Bench06n",
"Bench07p", "Bench07n",
"Bench07p1", "Bench07n1",
"Bench08p", "Bench08n",
"Bench09p", "Bench09n",
"Bench10p", "Bench10n",
"Bench10p1", "Bench10n1",
"Bench10p2", "Bench10n2",
"Bench10p3", "Bench10n3",
"Bench11p", "Bench11n",
"Bench11p1", "Bench11n1",
"Bench11p2", "Bench11n2",
"Bench11p3", "Bench11n3",
"Bench20p", "Bench20p1",
"Bench21p", "Bench21n",
"Bench21p1", "Bench21n1",
"Bench22p", "Bench22p1",
"Bench23p", "Bench23n",
"Bench30p", "Bench30n",
"Bench30p1", "Bench30n1",
"Bench30p2", "Bench30n2",
"Bench30p3", "Bench30n3",
"Bench31p", "Bench31n",
"Bench31p1", "Bench31n1",
"Bench31p2", "Bench31n2",
"Bench31p3", "Bench31n3",
"Bench40p", "Bench40n",
"Bench40p1", "Bench40p2",
"Bench41p", "Bench41n",
"Bench41p1", "Bench41p2"
);
static Func<bool> LookupFunc(object o)
{
TypeInfo t = typeof(ConstantArgsInt).GetTypeInfo();
MethodInfo m = t.GetDeclaredMethod((string) o);
return m.CreateDelegate(typeof(Func<bool>)) as Func<bool>;
}
[Benchmark]
[MemberData(nameof(TestFuncs))]
public static void Test(object funcName)
{
Func<bool> f = LookupFunc(funcName);
foreach (var iteration in Benchmark.Iterations)
{
using (iteration.StartMeasurement())
{
for (int i = 0; i < Iterations; i++)
{
f();
}
}
}
}
static bool TestBase(Func<bool> f)
{
bool result = true;
for (int i = 0; i < Iterations; i++)
{
result &= f();
}
return result;
}
public static int Main()
{
bool result = true;
foreach(object[] o in TestFuncs)
{
string funcName = (string) o[0];
Func<bool> func = LookupFunc(funcName);
bool thisResult = TestBase(func);
if (!thisResult)
{
Console.WriteLine("{0} failed", funcName);
}
result &= thisResult;
}
return (result ? 100 : -1);
}
}
| |
#region License
/* **********************************************************************************
* Copyright (c) Roman Ivantsov
* This source code is subject to terms and conditions of the MIT License
* for Irony. A copy of the license can be found in the License.txt file
* at the root of this distribution.
* By using this source code in any fashion, you are agreeing to be bound by the terms of the
* MIT License.
* You must not remove this notice from this software.
* **********************************************************************************/
#endregion
using System;
using System.Collections.Generic;
using System.Text;
using System.Globalization;
namespace Irony.Parsing {
#region notes
//Identifier terminal. Matches alpha-numeric sequences that usually represent identifiers and keywords.
// c#: @ prefix signals to not interpret as a keyword; allows \u escapes
//
#endregion
[Flags]
public enum IdOptions : short {
None = 0,
AllowsEscapes = 0x01,
CanStartWithEscape = 0x03, //bit 2 with bit 1 together
IsNotKeyword = 0x10,
NameIncludesPrefix = 0x20,
}
public enum CaseRestriction {
None,
FirstUpper,
FirstLower,
AllUpper,
AllLower
}
public class UnicodeCategoryList : List<UnicodeCategory> { }
public class IdentifierTerminal : CompoundTerminalBase {
//Id flags for internal use
internal enum IdFlagsInternal : short {
HasEscapes = 0x100,
}
#region constructors and initialization
public IdentifierTerminal(string name) : this(name, IdOptions.None) {
}
public IdentifierTerminal(string name, IdOptions options) : this(name, "_", "_") {
Options = options;
}
public IdentifierTerminal(string name, string extraChars, string extraFirstChars = ""): base(name) {
AllFirstChars = Strings.AllLatinLetters + extraFirstChars;
AllChars = Strings.AllLatinLetters + Strings.DecimalDigits + extraChars;
}
public void AddPrefix(string prefix, IdOptions options) {
base.AddPrefixFlag(prefix, (short)options);
}
#endregion
#region properties: AllChars, AllFirstChars
CharHashSet _allCharsSet;
CharHashSet _allFirstCharsSet;
public string AllFirstChars;
public string AllChars;
public TokenEditorInfo KeywordEditorInfo = new TokenEditorInfo(TokenType.Keyword, TokenColor.Keyword, TokenTriggers.None);
public IdOptions Options; //flags for the case when there are no prefixes
public CaseRestriction CaseRestriction;
public readonly UnicodeCategoryList StartCharCategories = new UnicodeCategoryList(); //categories of first char
public readonly UnicodeCategoryList CharCategories = new UnicodeCategoryList(); //categories of all other chars
public readonly UnicodeCategoryList CharsToRemoveCategories = new UnicodeCategoryList(); //categories of chars to remove from final id, usually formatting category
#endregion
#region overrides
public override void Init(GrammarData grammarData) {
base.Init(grammarData);
_allCharsSet = new CharHashSet(Grammar.CaseSensitive);
_allCharsSet.UnionWith(AllChars.ToCharArray());
//Adjust case restriction. We adjust only first chars; if first char is ok, we will scan the rest without restriction
// and then check casing for entire identifier
switch(CaseRestriction) {
case CaseRestriction.AllLower:
case CaseRestriction.FirstLower:
_allFirstCharsSet = new CharHashSet(true);
_allFirstCharsSet.UnionWith(AllFirstChars.ToLowerInvariant().ToCharArray());
break;
case CaseRestriction.AllUpper:
case CaseRestriction.FirstUpper:
_allFirstCharsSet = new CharHashSet(true);
_allFirstCharsSet.UnionWith(AllFirstChars.ToUpperInvariant().ToCharArray());
break;
default: //None
_allFirstCharsSet = new CharHashSet(Grammar.CaseSensitive);
_allFirstCharsSet.UnionWith(AllFirstChars.ToCharArray());
break;
}
//if there are "first" chars defined by categories, add the terminal to FallbackTerminals
if (this.StartCharCategories.Count > 0)
grammarData.NoPrefixTerminals.Add(this);
if (this.EditorInfo == null)
this.EditorInfo = new TokenEditorInfo(TokenType.Identifier, TokenColor.Identifier, TokenTriggers.None);
}
//TODO: put into account non-Ascii aplhabets specified by means of Unicode categories!
public override IList<string> GetFirsts() {
var list = new StringList();
list.AddRange(Prefixes);
foreach (char ch in _allFirstCharsSet)
list.Add(ch.ToString());
if ((Options & IdOptions.CanStartWithEscape) != 0)
list.Add(this.EscapeChar.ToString());
return list;
}
protected override void InitDetails(ParsingContext context, CompoundTokenDetails details) {
base.InitDetails(context, details);
details.Flags = (short)Options;
}
//Override to assign IsKeyword flag to keyword tokens
protected override Token CreateToken(ParsingContext context, ISourceStream source, CompoundTokenDetails details) {
Token token = base.CreateToken(context, source, details);
if (details.IsSet((short)IdOptions.IsNotKeyword))
return token;
//check if it is keyword
CheckReservedWord(token);
return token;
}
private void CheckReservedWord(Token token) {
KeyTerm keyTerm;
if (Grammar.KeyTerms.TryGetValue(token.Text, out keyTerm)) {
token.KeyTerm = keyTerm;
//if it is reserved word, then overwrite terminal
if (keyTerm.Flags.IsSet(TermFlags.IsReservedWord))
token.SetTerminal(keyTerm);
}
}
protected override Token QuickParse(ParsingContext context, ISourceStream source) {
if (!_allFirstCharsSet.Contains(source.PreviewChar))
return null;
source.PreviewPosition++;
while (_allCharsSet.Contains(source.PreviewChar) && !source.EOF())
source.PreviewPosition++;
//if it is not a terminator then cancel; we need to go through full algorithm
if (!this.Grammar.IsWhitespaceOrDelimiter(source.PreviewChar))
return null;
var token = source.CreateToken(this.OutputTerminal);
if(CaseRestriction != CaseRestriction.None && !CheckCaseRestriction(token.ValueString))
return null;
//!!! Do not convert to common case (all-lower) for case-insensitive grammar. Let identifiers remain as is,
// it is responsibility of interpreter to provide case-insensitive read/write operations for identifiers
// if (!this.GrammarData.Grammar.CaseSensitive)
// token.Value = token.Text.ToLower(CultureInfo.InvariantCulture);
CheckReservedWord(token);
return token;
}
protected override bool ReadBody(ISourceStream source, CompoundTokenDetails details) {
int start = source.PreviewPosition;
bool allowEscapes = details.IsSet((short)IdOptions.AllowsEscapes);
CharList outputChars = new CharList();
while (!source.EOF()) {
char current = source.PreviewChar;
if (Grammar.IsWhitespaceOrDelimiter(current))
break;
if (allowEscapes && current == this.EscapeChar) {
current = ReadUnicodeEscape(source, details);
//We need to back off the position. ReadUnicodeEscape sets the position to symbol right after escape digits.
//This is the char that we should process in next iteration, so we must backup one char, to pretend the escaped
// char is at position of last digit of escape sequence.
source.PreviewPosition--;
if (details.Error != null)
return false;
}
//Check if current character is OK
if (!CharOk(current, source.PreviewPosition == start))
break;
//Check if we need to skip this char
UnicodeCategory currCat = char.GetUnicodeCategory(current); //I know, it suxx, we do it twice, fix it later
if (!this.CharsToRemoveCategories.Contains(currCat))
outputChars.Add(current); //add it to output (identifier)
source.PreviewPosition++;
}//while
if (outputChars.Count == 0)
return false;
//Convert collected chars to string
details.Body = new string(outputChars.ToArray());
if (!CheckCaseRestriction(details.Body))
return false;
return !string.IsNullOrEmpty(details.Body);
}
private bool CharOk(char ch, bool first) {
//first check char lists, then categories
var charSet = first? _allFirstCharsSet : _allCharsSet;
if(charSet.Contains(ch)) return true;
//check categories
if (CharCategories.Count > 0) {
UnicodeCategory chCat = char.GetUnicodeCategory(ch);
UnicodeCategoryList catList = first ? StartCharCategories : CharCategories;
if (catList.Contains(chCat)) return true;
}
return false;
}
private bool CheckCaseRestriction(string body) {
switch(CaseRestriction) {
case CaseRestriction.FirstLower: return Char.IsLower(body, 0);
case CaseRestriction.FirstUpper: return Char.IsUpper(body, 0);
case CaseRestriction.AllLower: return body.ToLower() == body;
case CaseRestriction.AllUpper: return body.ToUpper() == body;
default : return true;
}
}//method
private char ReadUnicodeEscape(ISourceStream source, CompoundTokenDetails details) {
//Position is currently at "\" symbol
source.PreviewPosition++; //move to U/u char
int len;
switch (source.PreviewChar) {
case 'u': len = 4; break;
case 'U': len = 8; break;
default:
details.Error = Resources.ErrInvEscSymbol; // "Invalid escape symbol, expected 'u' or 'U' only."
return '\0';
}
if (source.PreviewPosition + len > source.Text.Length) {
details.Error = Resources.ErrInvEscSeq; // "Invalid escape sequence";
return '\0';
}
source.PreviewPosition++; //move to the first digit
string digits = source.Text.Substring(source.PreviewPosition, len);
char result = (char)Convert.ToUInt32(digits, 16);
source.PreviewPosition += len;
details.Flags |= (int) IdFlagsInternal.HasEscapes;
return result;
}
protected override bool ConvertValue(CompoundTokenDetails details) {
if (details.IsSet((short)IdOptions.NameIncludesPrefix))
details.Value = details.Prefix + details.Body;
else
details.Value = details.Body;
return true;
}
#endregion
}//class
} //namespace
| |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System;
using System.Reflection;
namespace trinus{
public class TrinusCamera : MonoBehaviour
{
public enum CAMERA_MODE{
DISABLED,
SINGLE,
DUAL,
UNITY_VR
}
Camera leftCamera;
Camera rightCamera;
Camera splitCamera;
Camera uiCameraMain;
Camera uiCameraSub;
Vector3 offset;
Vector3 defaultRotation;
public delegate void cameraEnabled(TrinusCamera camera, bool toggle);
cameraEnabled cameraEnabledDelegate;
CAMERA_MODE activeMode = CAMERA_MODE.DISABLED;
[Tooltip("The Camera mode determines if the view should be monoscopic or stereosopic (using Unity VR mode or a two camera rig). Refer to the manual for details")]
public CAMERA_MODE defaultMode = CAMERA_MODE.UNITY_VR;
[Tooltip("Camera offset to better simulate neck rotation")]
public float neckHeight = 0.15f;
// [Tooltip("When using the auto camera switch in TrinusProcessor, the newly selected camera will be offset to look on this angle. This avoids having to call TrinusProcessor.resetView(float)")]
// public float defaultViewAngle = 0;
void Awake(){
defaultRotation = new Vector3(transform.localEulerAngles.x , transform.localEulerAngles.y, transform.localEulerAngles.z);
transform.position = new Vector3 (transform.position.x, transform.position.y - neckHeight, transform.position.z);
Transform t = transform.FindChild ("LeftCamera");
if (t != null) {
leftCamera = (Camera)t.GetComponent<Camera> ();
t.localPosition = new Vector3 (t.localPosition.x, neckHeight, t.localPosition.z);
}
t = transform.FindChild ("RightCamera");
if (t != null){
rightCamera = (Camera)t.GetComponent<Camera> ();
t.localPosition = new Vector3 (t.localPosition.x, neckHeight, t.localPosition.z);
}
t = transform.FindChild ("SplitCamera");
if (t != null) {
splitCamera = (Camera)t.GetComponent<Camera> ();
t.localPosition = new Vector3 (t.localPosition.x, neckHeight, t.localPosition.z);
}
if (splitCamera == null && transform.GetComponent<Camera>() != null) {
//TrinusCamera attached to a camera, ignore children and use that one as main
splitCamera = transform.GetComponent<Camera>();
//TODO spawn new left/right cams
if (leftCamera == null)
leftCamera = splitCamera;
if (rightCamera == null)
rightCamera = splitCamera;
defaultMode = CAMERA_MODE.SINGLE;
Debug.Log("TrinusCamera using external camera (" + splitCamera + "). Switching to single camera mode");
}
uiCameraMain = GameObject.Find ("TrinusUICamera").GetComponent<Camera>();
uiCameraSub = uiCameraMain.transform.FindChild ("Camera").GetComponent<Camera> ();
//int savedMode = PlayerPrefs.GetInt ("cameraMode", (int)defaultMode);
//setMode ((CAMERA_MODE)savedMode);
//setFov (getFov ());
setMode(defaultMode);
}
public void setFov(int f){
if (activeMode == CAMERA_MODE.DUAL) {
leftCamera.fieldOfView = f;
rightCamera.fieldOfView = f;
} else
splitCamera.fieldOfView = f;
PlayerPrefs.SetInt ("fov", f);
}
public Vector3 getDefaultRotation(){
return defaultRotation;
}
public Vector3 getOffset(){
return offset;
}
public void setOffset(Vector3 offset){
this.offset = offset;
}
public int getFov(){
return PlayerPrefs.GetInt ("fov", 100);
}
public void setConvergence(float c){
}
public float getConvergence(){
return 0;
}
public void setSeparation(float s){
}
public float getSeparation(){
return 0;
}
public Camera getMainCamera(){
if (activeMode == CAMERA_MODE.DUAL)
return leftCamera;
return splitCamera;
}
public Camera[] getMainDualCamera(){
return new Camera[]{ leftCamera, rightCamera };
}
public Camera getUICamera(){
return uiCameraMain;
}
public CAMERA_MODE getMode(){
return activeMode;
}
public void setDefaultMode(){
setMode (defaultMode);
}
public void setMode(CAMERA_MODE mode){
if (mode == activeMode)
return;
activeMode = mode;
// if (activeMode != CAMERA_MODE.DISABLED)
// PlayerPrefs.SetInt ("cameraMode", (int)activeMode);
switch (mode) {
case CAMERA_MODE.DISABLED:
leftCamera.gameObject.SetActive(false);
rightCamera.gameObject.SetActive(false);
splitCamera.gameObject.SetActive(false);
break;
case CAMERA_MODE.SINGLE:
leftCamera.gameObject.SetActive(false);
rightCamera.gameObject.SetActive(false);
splitCamera.gameObject.SetActive(true);
UnityEngine.VR.VRSettings.enabled = false;
//UnityEngine.VR.VRSettings.loadedDevice = UnityEngine.VR.VRDeviceType.None;
uiCameraSub.gameObject.SetActive (false);
uiCameraMain.rect = new Rect (0, 0, 1, 1);
break;
case CAMERA_MODE.UNITY_VR:
leftCamera.gameObject.SetActive (false);
rightCamera.gameObject.SetActive (false);
splitCamera.gameObject.SetActive (true);
UnityEngine.VR.VRSettings.loadedDevice = UnityEngine.VR.VRDeviceType.Split;
UnityEngine.VR.VRSettings.enabled = true;
uiCameraSub.gameObject.SetActive (false);
uiCameraMain.rect = new Rect (0, 0, 1, 1);
break;
case CAMERA_MODE.DUAL:
leftCamera.gameObject.SetActive (true);
rightCamera.gameObject.SetActive (true);
if (splitCamera != leftCamera)//TrinusCamera attached to external camera case
splitCamera.gameObject.SetActive (false);
//UnityEngine.VR.VRSettings.enabled = false;
//UnityEngine.VR.VRSettings.loadedDevice = UnityEngine.VR.VRDeviceType.None;
uiCameraSub.gameObject.SetActive (true);
uiCameraSub.gameObject.SetActive (true);
uiCameraSub.rect = new Rect (0.5f, 0, 0.5f, 1);
uiCameraMain.rect = new Rect (0, 0, 0.5f, 1);
break;
}
setFov (getFov ());
}
public void setCameraEnabledDelegate(cameraEnabled ce){
cameraEnabledDelegate = ce;
}
public void OnEnable(){
enabledCamera ();
}
public void enabledCamera(){
if (cameraEnabledDelegate != null)
cameraEnabledDelegate (this, false);
// if (trinusProcessor != null && trinusProcessor.autoSwitchCamera) {
// trinusProcessor.switchCamera (this, false);
//// trinusProcessor.resetView (-defaultViewAngle);
// }
}
public void syncCameras(){
if (leftCamera != null & rightCamera != null) {
syncComponents (leftCamera.gameObject, rightCamera.gameObject);
syncComponents (rightCamera.gameObject, leftCamera.gameObject);
}
}
private void syncComponents(GameObject source, GameObject dest){
List<Component> list = new List<Component>();
source.GetComponents (list);
foreach(Component component in list){
copyComponent(dest, component);
}
}
private static void copyComponent<T>(GameObject gameObject, T other) where T : Component
{
Type type = other.GetType();
// Debug.Log (gameObject + " has " + other + "? " + gameObject.GetComponent (type));
if (gameObject.GetComponent(type) != null)
return;//already exists
Component newComponent = gameObject.AddComponent (type);
if (other is Behaviour)
((Behaviour)newComponent).enabled = (other as Behaviour).enabled;
BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Default | BindingFlags.DeclaredOnly;
PropertyInfo[] pinfos = type.GetProperties(flags);
foreach (PropertyInfo pinfo in pinfos) {
if (pinfo.CanWrite) {
try {
pinfo.SetValue(newComponent, pinfo.GetValue(other, null), null);
}
catch { }
}
}
FieldInfo[] finfos = type.GetFields(flags);
foreach (FieldInfo finfo in finfos) {
finfo.SetValue(newComponent, finfo.GetValue(other));
}
}
}
}
| |
//*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the Apache License, Version 2.0.
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************
using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using System.Diagnostics;
using System.Collections;
using System.IO;
using System.Xml;
using System.Xml.Schema;
using Common;
using System.Collections.ObjectModel;
using System.Security;
namespace Randoop
{
public class PlanManager
{
RandoopConfiguration config;
// Counter used to print out a dot for every 1000 plans.
private int addCounter = 0;
private int redundantAdds = 0;
public int Plans
{
get
{
return addCounter;
}
}
public int RedundantAdds
{
get
{
return redundantAdds;
}
}
public readonly PlanDataBase exceptionPlans;
public readonly PlanDataBase builderPlans;
public readonly PlanDataBase observerPlans;
private ITestFileWriter testFileWriter;
public static int numContractViolatingPlans = 0; //to count number of exception + contract violating plans
public static int numDistinctContractViolPlans = 0; // counts the # of plans that violates contract (may violate same contract)
public PlanManager(RandoopConfiguration config)
{
this.config = config;
this.builderPlans = new PlanDataBase("builderPlans", config.typematchingmode);
this.exceptionPlans = new PlanDataBase("exceptionThrowingPlans", config.typematchingmode);
this.observerPlans = new PlanDataBase("observerPlans", config.typematchingmode);
Plan.uniqueIdCounter = config.planstartid;
if (config.singledir)
{
this.testFileWriter = new SingleDirTestWriter(new DirectoryInfo(config.outputdir), config.testPrefix);
}
else
{
DirectoryInfo outputDir = new DirectoryInfo(config.outputdir);
this.testFileWriter = new ClassifyingTestFileWriter(outputDir, config.testPrefix);
}
}
/// <summary>
/// Adds (if not already present) p to either fplanDB or fexceptionThrowingPlanDB,
/// by executing the plan to determine if it throws exceptions.
/// </summary>
/// <param name="v"></param>
public void AddMaybeExecutingIfNeeded(Plan p, StatsManager stats)
{
//foreach (string s in p.Codestring)
// Console.WriteLine(s);
if (builderPlans.Containsplan(p))
{
redundantAdds++;
stats.CreatedNew(CreationResult.Redundant);
}
else if (exceptionPlans.Containsplan(p))
{
redundantAdds++;
stats.CreatedNew(CreationResult.Redundant);
}
else
{
addCounter++;
if (addCounter % 1000 == 0)
{
Console.Write(".");
PrintPercentageExecuted();
}
stats.CreatedNew(CreationResult.New);
ResultTuple execResult;
TextWriter writer = new StringWriter();
////xiao.qu@us.abb.com changes for debuglog
//TextWriter writer
// = new StreamWriter("..\\..\\TestRandoopBare\\1ab1qkwm.jbd\\debug.log");
Exception exceptionThrown;
bool contractViolated;
this.testFileWriter.WriteTest(p);
if (config.executionmode == ExecutionMode.DontExecute)
{
builderPlans.AddPlan(p);
stats.ExecutionResult("normal");
}
else
{
Util.Assert(config.executionmode == ExecutionMode.Reflection);
//TextWriter executionLog = new StreamWriter(config.executionLog);
TextWriter executionLog = new StreamWriter(config.executionLog+addCounter.ToString()+".log"); //xiao.qu@us.abb.com changes
executionLog.WriteLine("LASTPLANID:" + p.uniqueId);
long startTime = 0;
Timer.QueryPerformanceCounter(ref startTime);
bool execSucceeded = p.Execute(out execResult,
executionLog, writer, out exceptionThrown,
out contractViolated, this.config.forbidnull,
config.monkey);
long endTime = 0;
Timer.QueryPerformanceCounter(ref endTime);
TimeTracking.timeSpentExecutingTestedCode += (endTime - startTime);
executionLog.Close();
//writer.Close(); //xiao.qu@us.abb.com adds for debuglog
/*
* New: Now the execution of plan might fail (recursively) if any of the output tuple
* objects violate the contract for ToString(), HashCode(), Equals(o)
*/
if (!execSucceeded)
{
stats.ExecutionResult(exceptionThrown == null ? "other" : exceptionThrown.GetType().FullName);
// TODO This should alway be true...
if (exceptionThrown != null)
{
p.exceptionThrown = exceptionThrown;
this.testFileWriter.Move(p, exceptionThrown);
if (exceptionThrown is AccessViolationException)
{
Console.WriteLine("SECOND-CHANCE ACCESS VIOLATION EXCEPTION.");
System.Environment.Exit(1);
}
}
//string exceptionMessage = writer.ToString(); //no use? xiao.qu@us.abb.com comments out
Util.Assert(p.exceptionThrown != null || contractViolated);
if (config.monkey)
{
builderPlans.AddPlan(p);
//exceptionPlans.AddPlan(p); //new: also add it to exceptions for monkey
}
else if (exceptionThrown != null)
{
exceptionPlans.AddPlan(p);
}
}
else
{
stats.ExecutionResult("normal");
if (config.outputnormalinputs)
{
this.testFileWriter.MoveNormalTermination(p);
}
else
{
this.testFileWriter.Remove(p);
}
// If forbidNull, then make inactive any result tuple elements that are null.
if (this.config.forbidnull)
{
Util.Assert(p.NumTupleElements == execResult.tuple.Length);
for (int i = 0; i < p.NumTupleElements; i++)
if (execResult.tuple[i] == null)
p.SetActiveTupleElement(i, false);
//Util.Assert(!allNull); What is the motivation behind this assertion?
}
//only allow the receivers to be arguments to future methods
if (config.forbidparamobj)
{
Util.Assert(p.NumTupleElements == execResult.tuple.Length);
for (int i = 1; i < p.NumTupleElements; i++)
p.SetActiveTupleElement(i, false);
}
builderPlans.AddPlan(p, execResult);
}
}
}
}
private void PrintPercentageExecuted()
{
long endTime = 0;
Timer.QueryPerformanceCounter(ref endTime);
long totalGenerationTime = endTime - TimeTracking.generationStartTime;
double ratioExecToGen =
(double)TimeTracking.timeSpentExecutingTestedCode / (double)totalGenerationTime;
}
}
}
| |
using System;
using ServiceStack.Common.Web;
using ServiceStack.ServiceHost;
namespace ServiceStack.ServiceInterface
{
/// <summary>
/// Base class for services that support HTTP verbs.
/// </summary>
/// <typeparam name="TRequest">The request class that the descendent class
/// is responsible for processing.</typeparam>
public abstract class RestServiceBase<TRequest>
: ServiceBase<TRequest>,
IRestGetService<TRequest>,
IRestPutService<TRequest>,
IRestPostService<TRequest>,
IRestDeleteService<TRequest>,
IRestPatchService<TRequest>
{
protected override object Run(TRequest request)
{
throw new NotImplementedException("This base method should be overridden but not called");
}
/// <summary>
/// The method may overriden by the descendent class to provide support for the
/// GET verb on <see cref="TRequest"/> objects.
/// </summary>
/// <param name="request">The request object containing parameters for the GET
/// operation.</param>
/// <returns>
/// A response object that the client expects, <see langword="null"/> if a response
/// object is not applicable, or an <see cref="HttpResult"/> object, to indicate an
/// error condition to the client. The <see cref="HttpResult"/> object allows the
/// implementation to control the exact HTTP status code returned to the client.
/// Any return value other than <see cref="HttpResult"/> causes the HTTP status code
/// of 200 to be returned to the client.
/// </returns>
public virtual object OnGet(TRequest request)
{
throw new NotImplementedException("This base method should be overridden but not called");
}
public object Get(TRequest request)
{
try
{
OnBeforeExecute(request);
return OnAfterExecute(OnGet(request));
}
catch (Exception ex)
{
var result = HandleException(request, ex);
if (result == null) throw;
return result;
}
}
/// <summary>
/// The method may overriden by the descendent class to provide support for the
/// PUT verb on <see cref="TRequest"/> objects.
/// </summary>
/// <param name="request">The request object containing parameters for the PUT
/// operation.</param>
/// <returns>
/// A response object that the client expects, <see langword="null"/> if a response
/// object is not applicable, or an <see cref="HttpResult"/> object, to indicate an
/// error condition to the client. The <see cref="HttpResult"/> object allows the
/// implementation to control the exact HTTP status code returned to the client.
/// Any return value other than <see cref="HttpResult"/> causes the HTTP status code
/// of 200 to be returned to the client.
/// </returns>
public virtual object OnPut(TRequest request)
{
throw new NotImplementedException("This base method should be overridden but not called");
}
public object Put(TRequest request)
{
try
{
OnBeforeExecute(request);
return OnAfterExecute(OnPut(request));
}
catch (Exception ex)
{
var result = HandleException(request, ex);
if (result == null) throw;
return result;
}
}
/// <summary>
/// The method may overriden by the descendent class to provide support for the
/// POST verb on <see cref="TRequest"/> objects.
/// </summary>
/// <param name="request">The request object containing parameters for the POST
/// operation.</param>
/// <returns>
/// A response object that the client expects, <see langword="null"/> if a response
/// object is not applicable, or an <see cref="HttpResult"/> object, to indicate an
/// error condition to the client. The <see cref="HttpResult"/> object allows the
/// implementation to control the exact HTTP status code returned to the client.
/// Any return value other than <see cref="HttpResult"/> causes the HTTP status code
/// of 200 to be returned to the client.
/// </returns>
public virtual object OnPost(TRequest request)
{
throw new NotImplementedException("This base method should be overridden but not called");
}
public object Post(TRequest request)
{
try
{
OnBeforeExecute(request);
return OnAfterExecute(OnPost(request));
}
catch (Exception ex)
{
var result = HandleException(request, ex);
if (result == null) throw;
return result;
}
}
/// <summary>
/// The method may overriden by the descendent class to provide support for the
/// DELETE verb on <see cref="TRequest"/> objects.
/// </summary>
/// <param name="request">The request object containing parameters for the DELETE
/// operation.</param>
/// <returns>
/// A response object that the client expects, <see langword="null"/> if a response
/// object is not applicable, or an <see cref="HttpResult"/> object, to indicate an
/// error condition to the client. The <see cref="HttpResult"/> object allows the
/// implementation to control the exact HTTP status code returned to the client.
/// Any return value other than <see cref="HttpResult"/> causes the HTTP status code
/// of 200 to be returned to the client.
/// </returns>
public virtual object OnDelete(TRequest request)
{
throw new NotImplementedException("This base method should be overridden but not called");
}
public object Delete(TRequest request)
{
try
{
OnBeforeExecute(request);
return OnAfterExecute(OnDelete(request));
}
catch (Exception ex)
{
var result = HandleException(request, ex);
if (result == null) throw;
return result;
}
}
/// <summary>
/// The method may overriden by the descendent class to provide support for the
/// PATCH verb on <see cref="TRequest"/> objects.
/// </summary>
/// <param name="request">The request object containing parameters for the PATCH
/// operation.</param>
/// <returns>
/// A response object that the client expects, <see langword="null"/> if a response
/// object is not applicable, or an <see cref="HttpResult"/> object, to indicate an
/// error condition to the client. The <see cref="HttpResult"/> object allows the
/// implementation to control the exact HTTP status code returned to the client.
/// Any return value other than <see cref="HttpResult"/> causes the HTTP status code
/// of 200 to be returned to the client.
/// </returns>
public virtual object OnPatch(TRequest request)
{
throw new NotImplementedException("This base method should be overridden but not called");
}
public object Patch(TRequest request)
{
try
{
OnBeforeExecute(request);
return OnAfterExecute(OnPatch(request));
}
catch (Exception ex)
{
var result = HandleException(request, ex);
if (result == null) throw;
return result;
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace ServicoDeBooking.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
internal const int DefaultCollectionSize = 2;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/protobuf/wrappers.proto
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace Google.Protobuf {
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public static partial class Wrappers {
#region Descriptor
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static Wrappers() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"Ch5nb29nbGUvcHJvdG9idWYvd3JhcHBlcnMucHJvdG8SD2dvb2dsZS5wcm90",
"b2J1ZiIcCgtEb3VibGVWYWx1ZRINCgV2YWx1ZRgBIAEoASIbCgpGbG9hdFZh",
"bHVlEg0KBXZhbHVlGAEgASgCIhsKCkludDY0VmFsdWUSDQoFdmFsdWUYASAB",
"KAMiHAoLVUludDY0VmFsdWUSDQoFdmFsdWUYASABKAQiGwoKSW50MzJWYWx1",
"ZRINCgV2YWx1ZRgBIAEoBSIcCgtVSW50MzJWYWx1ZRINCgV2YWx1ZRgBIAEo",
"DSIaCglCb29sVmFsdWUSDQoFdmFsdWUYASABKAgiHAoLU3RyaW5nVmFsdWUS",
"DQoFdmFsdWUYASABKAkiGwoKQnl0ZXNWYWx1ZRINCgV2YWx1ZRgBIAEoDEIm",
"ChNjb20uZ29vZ2xlLnByb3RvYnVmQg1XcmFwcGVyc1Byb3RvUAFiBnByb3Rv",
"Mw=="));
descriptor = pbr::FileDescriptor.InternalBuildGeneratedFileFrom(descriptorData,
new pbr::FileDescriptor[] { },
new pbr::GeneratedCodeInfo(null, new pbr::GeneratedCodeInfo[] {
new pbr::GeneratedCodeInfo(typeof(global::Google.Protobuf.DoubleValue), new[]{ "Value" }, null, null, null),
new pbr::GeneratedCodeInfo(typeof(global::Google.Protobuf.FloatValue), new[]{ "Value" }, null, null, null),
new pbr::GeneratedCodeInfo(typeof(global::Google.Protobuf.Int64Value), new[]{ "Value" }, null, null, null),
new pbr::GeneratedCodeInfo(typeof(global::Google.Protobuf.UInt64Value), new[]{ "Value" }, null, null, null),
new pbr::GeneratedCodeInfo(typeof(global::Google.Protobuf.Int32Value), new[]{ "Value" }, null, null, null),
new pbr::GeneratedCodeInfo(typeof(global::Google.Protobuf.UInt32Value), new[]{ "Value" }, null, null, null),
new pbr::GeneratedCodeInfo(typeof(global::Google.Protobuf.BoolValue), new[]{ "Value" }, null, null, null),
new pbr::GeneratedCodeInfo(typeof(global::Google.Protobuf.StringValue), new[]{ "Value" }, null, null, null),
new pbr::GeneratedCodeInfo(typeof(global::Google.Protobuf.BytesValue), new[]{ "Value" }, null, null, null)
}));
}
#endregion
}
#region Messages
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class DoubleValue : pb::IMessage<DoubleValue> {
private static readonly pb::MessageParser<DoubleValue> _parser = new pb::MessageParser<DoubleValue>(() => new DoubleValue());
public static pb::MessageParser<DoubleValue> Parser { get { return _parser; } }
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Protobuf.Wrappers.Descriptor.MessageTypes[0]; }
}
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
public DoubleValue() {
OnConstruction();
}
partial void OnConstruction();
public DoubleValue(DoubleValue other) : this() {
value_ = other.value_;
}
public DoubleValue Clone() {
return new DoubleValue(this);
}
public const int ValueFieldNumber = 1;
private double value_;
public double Value {
get { return value_; }
set {
value_ = value;
}
}
public override bool Equals(object other) {
return Equals(other as DoubleValue);
}
public bool Equals(DoubleValue other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Value != other.Value) return false;
return true;
}
public override int GetHashCode() {
int hash = 1;
if (Value != 0D) hash ^= Value.GetHashCode();
return hash;
}
public override string ToString() {
return pb::JsonFormatter.Default.Format(this);
}
public void WriteTo(pb::CodedOutputStream output) {
if (Value != 0D) {
output.WriteRawTag(9);
output.WriteDouble(Value);
}
}
public int CalculateSize() {
int size = 0;
if (Value != 0D) {
size += 1 + 8;
}
return size;
}
public void MergeFrom(DoubleValue other) {
if (other == null) {
return;
}
if (other.Value != 0D) {
Value = other.Value;
}
}
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 9: {
Value = input.ReadDouble();
break;
}
}
}
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class FloatValue : pb::IMessage<FloatValue> {
private static readonly pb::MessageParser<FloatValue> _parser = new pb::MessageParser<FloatValue>(() => new FloatValue());
public static pb::MessageParser<FloatValue> Parser { get { return _parser; } }
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Protobuf.Wrappers.Descriptor.MessageTypes[1]; }
}
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
public FloatValue() {
OnConstruction();
}
partial void OnConstruction();
public FloatValue(FloatValue other) : this() {
value_ = other.value_;
}
public FloatValue Clone() {
return new FloatValue(this);
}
public const int ValueFieldNumber = 1;
private float value_;
public float Value {
get { return value_; }
set {
value_ = value;
}
}
public override bool Equals(object other) {
return Equals(other as FloatValue);
}
public bool Equals(FloatValue other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Value != other.Value) return false;
return true;
}
public override int GetHashCode() {
int hash = 1;
if (Value != 0F) hash ^= Value.GetHashCode();
return hash;
}
public override string ToString() {
return pb::JsonFormatter.Default.Format(this);
}
public void WriteTo(pb::CodedOutputStream output) {
if (Value != 0F) {
output.WriteRawTag(13);
output.WriteFloat(Value);
}
}
public int CalculateSize() {
int size = 0;
if (Value != 0F) {
size += 1 + 4;
}
return size;
}
public void MergeFrom(FloatValue other) {
if (other == null) {
return;
}
if (other.Value != 0F) {
Value = other.Value;
}
}
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 13: {
Value = input.ReadFloat();
break;
}
}
}
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class Int64Value : pb::IMessage<Int64Value> {
private static readonly pb::MessageParser<Int64Value> _parser = new pb::MessageParser<Int64Value>(() => new Int64Value());
public static pb::MessageParser<Int64Value> Parser { get { return _parser; } }
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Protobuf.Wrappers.Descriptor.MessageTypes[2]; }
}
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
public Int64Value() {
OnConstruction();
}
partial void OnConstruction();
public Int64Value(Int64Value other) : this() {
value_ = other.value_;
}
public Int64Value Clone() {
return new Int64Value(this);
}
public const int ValueFieldNumber = 1;
private long value_;
public long Value {
get { return value_; }
set {
value_ = value;
}
}
public override bool Equals(object other) {
return Equals(other as Int64Value);
}
public bool Equals(Int64Value other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Value != other.Value) return false;
return true;
}
public override int GetHashCode() {
int hash = 1;
if (Value != 0L) hash ^= Value.GetHashCode();
return hash;
}
public override string ToString() {
return pb::JsonFormatter.Default.Format(this);
}
public void WriteTo(pb::CodedOutputStream output) {
if (Value != 0L) {
output.WriteRawTag(8);
output.WriteInt64(Value);
}
}
public int CalculateSize() {
int size = 0;
if (Value != 0L) {
size += 1 + pb::CodedOutputStream.ComputeInt64Size(Value);
}
return size;
}
public void MergeFrom(Int64Value other) {
if (other == null) {
return;
}
if (other.Value != 0L) {
Value = other.Value;
}
}
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 8: {
Value = input.ReadInt64();
break;
}
}
}
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class UInt64Value : pb::IMessage<UInt64Value> {
private static readonly pb::MessageParser<UInt64Value> _parser = new pb::MessageParser<UInt64Value>(() => new UInt64Value());
public static pb::MessageParser<UInt64Value> Parser { get { return _parser; } }
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Protobuf.Wrappers.Descriptor.MessageTypes[3]; }
}
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
public UInt64Value() {
OnConstruction();
}
partial void OnConstruction();
public UInt64Value(UInt64Value other) : this() {
value_ = other.value_;
}
public UInt64Value Clone() {
return new UInt64Value(this);
}
public const int ValueFieldNumber = 1;
private ulong value_;
public ulong Value {
get { return value_; }
set {
value_ = value;
}
}
public override bool Equals(object other) {
return Equals(other as UInt64Value);
}
public bool Equals(UInt64Value other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Value != other.Value) return false;
return true;
}
public override int GetHashCode() {
int hash = 1;
if (Value != 0UL) hash ^= Value.GetHashCode();
return hash;
}
public override string ToString() {
return pb::JsonFormatter.Default.Format(this);
}
public void WriteTo(pb::CodedOutputStream output) {
if (Value != 0UL) {
output.WriteRawTag(8);
output.WriteUInt64(Value);
}
}
public int CalculateSize() {
int size = 0;
if (Value != 0UL) {
size += 1 + pb::CodedOutputStream.ComputeUInt64Size(Value);
}
return size;
}
public void MergeFrom(UInt64Value other) {
if (other == null) {
return;
}
if (other.Value != 0UL) {
Value = other.Value;
}
}
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 8: {
Value = input.ReadUInt64();
break;
}
}
}
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class Int32Value : pb::IMessage<Int32Value> {
private static readonly pb::MessageParser<Int32Value> _parser = new pb::MessageParser<Int32Value>(() => new Int32Value());
public static pb::MessageParser<Int32Value> Parser { get { return _parser; } }
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Protobuf.Wrappers.Descriptor.MessageTypes[4]; }
}
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
public Int32Value() {
OnConstruction();
}
partial void OnConstruction();
public Int32Value(Int32Value other) : this() {
value_ = other.value_;
}
public Int32Value Clone() {
return new Int32Value(this);
}
public const int ValueFieldNumber = 1;
private int value_;
public int Value {
get { return value_; }
set {
value_ = value;
}
}
public override bool Equals(object other) {
return Equals(other as Int32Value);
}
public bool Equals(Int32Value other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Value != other.Value) return false;
return true;
}
public override int GetHashCode() {
int hash = 1;
if (Value != 0) hash ^= Value.GetHashCode();
return hash;
}
public override string ToString() {
return pb::JsonFormatter.Default.Format(this);
}
public void WriteTo(pb::CodedOutputStream output) {
if (Value != 0) {
output.WriteRawTag(8);
output.WriteInt32(Value);
}
}
public int CalculateSize() {
int size = 0;
if (Value != 0) {
size += 1 + pb::CodedOutputStream.ComputeInt32Size(Value);
}
return size;
}
public void MergeFrom(Int32Value other) {
if (other == null) {
return;
}
if (other.Value != 0) {
Value = other.Value;
}
}
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 8: {
Value = input.ReadInt32();
break;
}
}
}
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class UInt32Value : pb::IMessage<UInt32Value> {
private static readonly pb::MessageParser<UInt32Value> _parser = new pb::MessageParser<UInt32Value>(() => new UInt32Value());
public static pb::MessageParser<UInt32Value> Parser { get { return _parser; } }
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Protobuf.Wrappers.Descriptor.MessageTypes[5]; }
}
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
public UInt32Value() {
OnConstruction();
}
partial void OnConstruction();
public UInt32Value(UInt32Value other) : this() {
value_ = other.value_;
}
public UInt32Value Clone() {
return new UInt32Value(this);
}
public const int ValueFieldNumber = 1;
private uint value_;
public uint Value {
get { return value_; }
set {
value_ = value;
}
}
public override bool Equals(object other) {
return Equals(other as UInt32Value);
}
public bool Equals(UInt32Value other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Value != other.Value) return false;
return true;
}
public override int GetHashCode() {
int hash = 1;
if (Value != 0) hash ^= Value.GetHashCode();
return hash;
}
public override string ToString() {
return pb::JsonFormatter.Default.Format(this);
}
public void WriteTo(pb::CodedOutputStream output) {
if (Value != 0) {
output.WriteRawTag(8);
output.WriteUInt32(Value);
}
}
public int CalculateSize() {
int size = 0;
if (Value != 0) {
size += 1 + pb::CodedOutputStream.ComputeUInt32Size(Value);
}
return size;
}
public void MergeFrom(UInt32Value other) {
if (other == null) {
return;
}
if (other.Value != 0) {
Value = other.Value;
}
}
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 8: {
Value = input.ReadUInt32();
break;
}
}
}
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class BoolValue : pb::IMessage<BoolValue> {
private static readonly pb::MessageParser<BoolValue> _parser = new pb::MessageParser<BoolValue>(() => new BoolValue());
public static pb::MessageParser<BoolValue> Parser { get { return _parser; } }
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Protobuf.Wrappers.Descriptor.MessageTypes[6]; }
}
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
public BoolValue() {
OnConstruction();
}
partial void OnConstruction();
public BoolValue(BoolValue other) : this() {
value_ = other.value_;
}
public BoolValue Clone() {
return new BoolValue(this);
}
public const int ValueFieldNumber = 1;
private bool value_;
public bool Value {
get { return value_; }
set {
value_ = value;
}
}
public override bool Equals(object other) {
return Equals(other as BoolValue);
}
public bool Equals(BoolValue other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Value != other.Value) return false;
return true;
}
public override int GetHashCode() {
int hash = 1;
if (Value != false) hash ^= Value.GetHashCode();
return hash;
}
public override string ToString() {
return pb::JsonFormatter.Default.Format(this);
}
public void WriteTo(pb::CodedOutputStream output) {
if (Value != false) {
output.WriteRawTag(8);
output.WriteBool(Value);
}
}
public int CalculateSize() {
int size = 0;
if (Value != false) {
size += 1 + 1;
}
return size;
}
public void MergeFrom(BoolValue other) {
if (other == null) {
return;
}
if (other.Value != false) {
Value = other.Value;
}
}
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 8: {
Value = input.ReadBool();
break;
}
}
}
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class StringValue : pb::IMessage<StringValue> {
private static readonly pb::MessageParser<StringValue> _parser = new pb::MessageParser<StringValue>(() => new StringValue());
public static pb::MessageParser<StringValue> Parser { get { return _parser; } }
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Protobuf.Wrappers.Descriptor.MessageTypes[7]; }
}
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
public StringValue() {
OnConstruction();
}
partial void OnConstruction();
public StringValue(StringValue other) : this() {
value_ = other.value_;
}
public StringValue Clone() {
return new StringValue(this);
}
public const int ValueFieldNumber = 1;
private string value_ = "";
public string Value {
get { return value_; }
set {
value_ = pb::Preconditions.CheckNotNull(value, "value");
}
}
public override bool Equals(object other) {
return Equals(other as StringValue);
}
public bool Equals(StringValue other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Value != other.Value) return false;
return true;
}
public override int GetHashCode() {
int hash = 1;
if (Value.Length != 0) hash ^= Value.GetHashCode();
return hash;
}
public override string ToString() {
return pb::JsonFormatter.Default.Format(this);
}
public void WriteTo(pb::CodedOutputStream output) {
if (Value.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Value);
}
}
public int CalculateSize() {
int size = 0;
if (Value.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Value);
}
return size;
}
public void MergeFrom(StringValue other) {
if (other == null) {
return;
}
if (other.Value.Length != 0) {
Value = other.Value;
}
}
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
Value = input.ReadString();
break;
}
}
}
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class BytesValue : pb::IMessage<BytesValue> {
private static readonly pb::MessageParser<BytesValue> _parser = new pb::MessageParser<BytesValue>(() => new BytesValue());
public static pb::MessageParser<BytesValue> Parser { get { return _parser; } }
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Protobuf.Wrappers.Descriptor.MessageTypes[8]; }
}
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
public BytesValue() {
OnConstruction();
}
partial void OnConstruction();
public BytesValue(BytesValue other) : this() {
value_ = other.value_;
}
public BytesValue Clone() {
return new BytesValue(this);
}
public const int ValueFieldNumber = 1;
private pb::ByteString value_ = pb::ByteString.Empty;
public pb::ByteString Value {
get { return value_; }
set {
value_ = pb::Preconditions.CheckNotNull(value, "value");
}
}
public override bool Equals(object other) {
return Equals(other as BytesValue);
}
public bool Equals(BytesValue other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Value != other.Value) return false;
return true;
}
public override int GetHashCode() {
int hash = 1;
if (Value.Length != 0) hash ^= Value.GetHashCode();
return hash;
}
public override string ToString() {
return pb::JsonFormatter.Default.Format(this);
}
public void WriteTo(pb::CodedOutputStream output) {
if (Value.Length != 0) {
output.WriteRawTag(10);
output.WriteBytes(Value);
}
}
public int CalculateSize() {
int size = 0;
if (Value.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeBytesSize(Value);
}
return size;
}
public void MergeFrom(BytesValue other) {
if (other == null) {
return;
}
if (other.Value.Length != 0) {
Value = other.Value;
}
}
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
Value = input.ReadBytes();
break;
}
}
}
}
}
#endregion
}
#endregion Designer generated code
| |
using System;
using System.Text;
namespace NBitcoin.BouncyCastle.Math.EC.Abc
{
/**
* Class representing a simple version of a big decimal. A
* <code>SimpleBigDecimal</code> is basically a
* {@link java.math.BigInteger BigInteger} with a few digits on the right of
* the decimal point. The number of (binary) digits on the right of the decimal
* point is called the <code>scale</code> of the <code>SimpleBigDecimal</code>.
* Unlike in {@link java.math.BigDecimal BigDecimal}, the scale is not adjusted
* automatically, but must be set manually. All <code>SimpleBigDecimal</code>s
* taking part in the same arithmetic operation must have equal scale. The
* result of a multiplication of two <code>SimpleBigDecimal</code>s returns a
* <code>SimpleBigDecimal</code> with double scale.
*/
internal class SimpleBigDecimal
// : Number
{
// private static final long serialVersionUID = 1L;
private readonly BigInteger bigInt;
private readonly int scale;
/**
* Returns a <code>SimpleBigDecimal</code> representing the same numerical
* value as <code>value</code>.
* @param value The value of the <code>SimpleBigDecimal</code> to be
* created.
* @param scale The scale of the <code>SimpleBigDecimal</code> to be
* created.
* @return The such created <code>SimpleBigDecimal</code>.
*/
public static SimpleBigDecimal GetInstance(BigInteger val, int scale)
{
return new SimpleBigDecimal(val.ShiftLeft(scale), scale);
}
/**
* Constructor for <code>SimpleBigDecimal</code>. The value of the
* constructed <code>SimpleBigDecimal</code> Equals <code>bigInt /
* 2<sup>scale</sup></code>.
* @param bigInt The <code>bigInt</code> value parameter.
* @param scale The scale of the constructed <code>SimpleBigDecimal</code>.
*/
public SimpleBigDecimal(BigInteger bigInt, int scale)
{
if(scale < 0)
throw new ArgumentException("scale may not be negative");
this.bigInt = bigInt;
this.scale = scale;
}
private SimpleBigDecimal(SimpleBigDecimal limBigDec)
{
this.bigInt = limBigDec.bigInt;
this.scale = limBigDec.scale;
}
private void CheckScale(SimpleBigDecimal b)
{
if(this.scale != b.scale)
throw new ArgumentException("Only SimpleBigDecimal of same scale allowed in arithmetic operations");
}
public SimpleBigDecimal AdjustScale(int newScale)
{
if(newScale < 0)
throw new ArgumentException("scale may not be negative");
if(newScale == this.scale)
return this;
return new SimpleBigDecimal(this.bigInt.ShiftLeft(newScale - this.scale), newScale);
}
public SimpleBigDecimal Add(SimpleBigDecimal b)
{
CheckScale(b);
return new SimpleBigDecimal(this.bigInt.Add(b.bigInt), this.scale);
}
public SimpleBigDecimal Add(BigInteger b)
{
return new SimpleBigDecimal(this.bigInt.Add(b.ShiftLeft(this.scale)), this.scale);
}
public SimpleBigDecimal Negate()
{
return new SimpleBigDecimal(this.bigInt.Negate(), this.scale);
}
public SimpleBigDecimal Subtract(SimpleBigDecimal b)
{
return Add(b.Negate());
}
public SimpleBigDecimal Subtract(BigInteger b)
{
return new SimpleBigDecimal(this.bigInt.Subtract(b.ShiftLeft(this.scale)), this.scale);
}
public SimpleBigDecimal Multiply(SimpleBigDecimal b)
{
CheckScale(b);
return new SimpleBigDecimal(this.bigInt.Multiply(b.bigInt), this.scale + this.scale);
}
public SimpleBigDecimal Multiply(BigInteger b)
{
return new SimpleBigDecimal(this.bigInt.Multiply(b), this.scale);
}
public SimpleBigDecimal Divide(SimpleBigDecimal b)
{
CheckScale(b);
BigInteger dividend = this.bigInt.ShiftLeft(this.scale);
return new SimpleBigDecimal(dividend.Divide(b.bigInt), this.scale);
}
public SimpleBigDecimal Divide(BigInteger b)
{
return new SimpleBigDecimal(this.bigInt.Divide(b), this.scale);
}
public SimpleBigDecimal ShiftLeft(int n)
{
return new SimpleBigDecimal(this.bigInt.ShiftLeft(n), this.scale);
}
public int CompareTo(SimpleBigDecimal val)
{
CheckScale(val);
return this.bigInt.CompareTo(val.bigInt);
}
public int CompareTo(BigInteger val)
{
return this.bigInt.CompareTo(val.ShiftLeft(this.scale));
}
public BigInteger Floor()
{
return this.bigInt.ShiftRight(this.scale);
}
public BigInteger Round()
{
var oneHalf = new SimpleBigDecimal(BigInteger.One, 1);
return Add(oneHalf.AdjustScale(this.scale)).Floor();
}
public int IntValue
{
get
{
return Floor().IntValue;
}
}
public long LongValue
{
get
{
return Floor().LongValue;
}
}
// public double doubleValue()
// {
// return new Double(ToString()).doubleValue();
// }
//
// public float floatValue()
// {
// return new Float(ToString()).floatValue();
// }
public int Scale
{
get
{
return this.scale;
}
}
public override string ToString()
{
if(this.scale == 0)
return this.bigInt.ToString();
BigInteger floorBigInt = Floor();
BigInteger fract = this.bigInt.Subtract(floorBigInt.ShiftLeft(this.scale));
if(this.bigInt.SignValue < 0)
{
fract = BigInteger.One.ShiftLeft(this.scale).Subtract(fract);
}
if((floorBigInt.SignValue == -1) && (!(fract.Equals(BigInteger.Zero))))
{
floorBigInt = floorBigInt.Add(BigInteger.One);
}
string leftOfPoint = floorBigInt.ToString();
var fractCharArr = new char[this.scale];
string fractStr = fract.ToString(2);
int fractLen = fractStr.Length;
int zeroes = this.scale - fractLen;
for(int i = 0; i < zeroes; i++)
{
fractCharArr[i] = '0';
}
for(int j = 0; j < fractLen; j++)
{
fractCharArr[zeroes + j] = fractStr[j];
}
string rightOfPoint = new string(fractCharArr);
var sb = new StringBuilder(leftOfPoint);
sb.Append(".");
sb.Append(rightOfPoint);
return sb.ToString();
}
public override bool Equals(
object obj)
{
if(this == obj)
return true;
var other = obj as SimpleBigDecimal;
if(other == null)
return false;
return this.bigInt.Equals(other.bigInt)
&& this.scale == other.scale;
}
public override int GetHashCode()
{
return this.bigInt.GetHashCode() ^ this.scale;
}
}
}
| |
// The MIT License (MIT)
// Copyright 2015 Siney/Pangweiwei siney@yeah.net
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
namespace SLua
{
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System;
using System.Reflection;
using UnityEditor;
using LuaInterface;
using System.Text;
using System.Text.RegularExpressions;
public class LuaCodeGen : MonoBehaviour
{
public const string Path = "Assets/Slua/LuaObject/";
public delegate void ExportGenericDelegate(Type t, string ns);
static bool autoRefresh = true;
static bool IsCompiling {
get {
if (EditorApplication.isCompiling) {
Debug.Log("Unity Editor is compiling, please wait.");
}
return EditorApplication.isCompiling;
}
}
[InitializeOnLoad]
public class Startup
{
static Startup()
{
bool ok = System.IO.Directory.Exists(Path);
if (!ok && EditorUtility.DisplayDialog("Slua", "Not found lua interface for Unity, generate it now?", "Generate", "No"))
{
GenerateAll();
}
}
}
[MenuItem("SLua/All/Make")]
static public void GenerateAll()
{
autoRefresh = false;
Generate();
GenerateUI();
Custom();
Generate3rdDll();
autoRefresh = true;
AssetDatabase.Refresh();
}
[MenuItem("SLua/Unity/Make UnityEngine")]
static public void Generate()
{
if (IsCompiling) {
return;
}
Assembly assembly = Assembly.Load("UnityEngine");
Type[] types = assembly.GetExportedTypes();
List<string> uselist;
List<string> noUseList;
CustomExport.OnGetNoUseList(out noUseList);
CustomExport.OnGetUseList(out uselist);
List<Type> exports = new List<Type>();
string path = Path + "Unity/";
foreach (Type t in types)
{
bool export = true;
// check type in uselist
if (uselist != null && uselist.Count > 0)
{
export = false;
foreach (string str in uselist)
{
if (t.FullName == str)
{
export = true;
break;
}
}
}
else
{
// check type not in nouselist
foreach (string str in noUseList)
{
if (t.FullName.Contains(str))
{
export = false;
break;
}
}
}
if (export)
{
if (Generate(t,path))
exports.Add(t);
}
}
GenerateBind(exports, "BindUnity", 0,path);
if(autoRefresh)
AssetDatabase.Refresh();
Debug.Log("Generate engine interface finished");
}
[MenuItem("SLua/Unity/Make UI (for Unity4.6+)")]
static public void GenerateUI()
{
if (IsCompiling) {
return;
}
List<string> noUseList = new List<string>
{
"CoroutineTween",
"GraphicRebuildTracker",
};
Assembly assembly = Assembly.Load("UnityEngine.UI");
Type[] types = assembly.GetExportedTypes();
List<Type> exports = new List<Type>();
string path = Path + "Unity/";
foreach (Type t in types)
{
bool export = true;
foreach (string str in noUseList)
{
if (t.FullName.Contains(str))
export = false;
}
if (export)
{
if (Generate(t, path))
exports.Add(t);
}
}
GenerateBind(exports, "BindUnityUI", 1,path);
if(autoRefresh)
AssetDatabase.Refresh();
Debug.Log("Generate UI interface finished");
}
[MenuItem("SLua/Unity/Clear Uinty UI")]
static public void ClearUnity()
{
clear(new string[] { Path + "Unity" });
Debug.Log("Clear Unity & UI complete.");
}
static public bool IsObsolete(MemberInfo t)
{
return t.GetCustomAttributes(typeof(ObsoleteAttribute), false).Length > 0;
}
[MenuItem("SLua/Custom/Make")]
static public void Custom()
{
if (IsCompiling) {
return;
}
List<Type> exports = new List<Type>();
string path = Path + "Custom/";
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
ExportGenericDelegate fun = (Type t, string ns) =>
{
if (Generate(t, ns, path))
exports.Add(t);
};
// export self-dll
Assembly assembly = Assembly.Load("Assembly-CSharp");
Type[] types = assembly.GetExportedTypes();
foreach (Type t in types)
{
if (t.GetCustomAttributes(typeof(CustomLuaClassAttribute), false).Length > 0)
{
fun(t, null);
}
}
CustomExport.OnAddCustomClass(fun);
GenerateBind(exports, "BindCustom", 3,path);
if(autoRefresh)
AssetDatabase.Refresh();
Debug.Log("Generate custom interface finished");
}
[MenuItem("SLua/3rdDll/Make")]
static public void Generate3rdDll()
{
if (IsCompiling) {
return;
}
List<Type> cust = new List<Type>();
Assembly assembly = Assembly.Load("Assembly-CSharp");
Type[] types = assembly.GetExportedTypes();
List<string> assemblyList = new List<string>();
CustomExport.OnAddCustomAssembly(ref assemblyList);
foreach (string assemblyItem in assemblyList)
{
assembly = Assembly.Load(assemblyItem);
types = assembly.GetExportedTypes();
foreach (Type t in types)
{
cust.Add(t);
}
}
if (cust.Count > 0)
{
List<Type> exports = new List<Type>();
string path = Path + "Dll/";
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
foreach (Type t in cust)
{
if (Generate(t,path))
exports.Add(t);
}
GenerateBind(exports, "BindDll", 2, path);
if(autoRefresh)
AssetDatabase.Refresh();
Debug.Log("Generate 3rdDll interface finished");
}
}
[MenuItem("SLua/3rdDll/Clear")]
static public void Clear3rdDll()
{
clear(new string[] { Path + "Dll" });
Debug.Log("Clear AssemblyDll complete.");
}
[MenuItem("SLua/Custom/Clear")]
static public void ClearCustom()
{
clear(new string[] { Path + "Custom" });
Debug.Log("Clear custom complete.");
}
[MenuItem("SLua/All/Clear")]
static public void ClearALL()
{
clear(new string[] { Path.Substring(0, Path.Length - 1) });
Debug.Log("Clear all complete.");
}
static void clear(string[] paths)
{
try
{
foreach (string path in paths)
{
System.IO.Directory.Delete(path, true);
}
}
catch
{
}
AssetDatabase.Refresh();
}
static bool Generate(Type t, string path)
{
return Generate(t, null, path);
}
static bool Generate(Type t, string ns, string path)
{
if (t.IsInterface)
return false;
CodeGenerator cg = new CodeGenerator();
cg.givenNamespace = ns;
cg.path = path;
return cg.Generate(t);
}
static void GenerateBind(List<Type> list, string name, int order,string path)
{
CodeGenerator cg = new CodeGenerator();
cg.path = path;
cg.GenerateBind(list, name, order);
}
}
class CodeGenerator
{
static List<string> memberFilter = new List<string>
{
"AnimationClip.averageDuration",
"AnimationClip.averageAngularSpeed",
"AnimationClip.averageSpeed",
"AnimationClip.apparentSpeed",
"AnimationClip.isLooping",
"AnimationClip.isAnimatorMotion",
"AnimationClip.isHumanMotion",
"AnimatorOverrideController.PerformOverrideClipListCleanup",
"Caching.SetNoBackupFlag",
"Caching.ResetNoBackupFlag",
"Light.areaSize",
"Security.GetChainOfTrustValue",
"Texture2D.alphaIsTransparency",
"WWW.movie",
"WebCamTexture.MarkNonReadable",
"WebCamTexture.isReadable",
// i don't why below 2 functions missed in iOS platform
"Graphic.OnRebuildRequested",
"Text.OnRebuildRequested",
// il2cpp not exixts
"Application.ExternalEval",
"GameObject.networkView",
"Component.networkView",
// unity5
"AnimatorControllerParameter.name",
"Input.IsJoystickPreconfigured",
"Resources.LoadAssetAtPath",
#if UNITY_4_6
"Motion.ValidateIfRetargetable",
"Motion.averageDuration",
"Motion.averageAngularSpeed",
"Motion.averageSpeed",
"Motion.apparentSpeed",
"Motion.isLooping",
"Motion.isAnimatorMotion",
"Motion.isHumanMotion",
#endif
};
HashSet<string> funcname = new HashSet<string>();
Dictionary<string, bool> directfunc = new Dictionary<string, bool>();
public string givenNamespace;
public string path;
class PropPair
{
public string get = "null";
public string set = "null";
public bool isInstance = true;
}
Dictionary<string, PropPair> propname = new Dictionary<string, PropPair>();
int indent = 0;
public void GenerateBind(List<Type> list, string name, int order)
{
HashSet<Type> exported = new HashSet<Type>();
string f = path + name + ".cs";
StreamWriter file = new StreamWriter(f, false, Encoding.UTF8);
Write(file, "using System;");
Write(file, "namespace SLua {");
Write(file, "[LuaBinder({0})]", order);
Write(file, "public class {0} {{", name);
Write(file, "public static void Bind(IntPtr l) {");
foreach (Type t in list)
{
WriteBindType(file, t, list, exported);
}
Write(file, "}");
Write(file, "}");
Write(file, "}");
file.Close();
}
void WriteBindType(StreamWriter file, Type t, List<Type> exported, HashSet<Type> binded)
{
if (t == null || binded.Contains(t) || !exported.Contains(t))
return;
WriteBindType(file, t.BaseType, exported, binded);
Write(file, "{0}.reg(l);", ExportName(t), binded);
binded.Add(t);
}
public bool Generate(Type t)
{
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
if (!t.IsGenericTypeDefinition && (!IsObsolete(t) && t != typeof(YieldInstruction) && t != typeof(Coroutine))
|| (t.BaseType != null && t.BaseType == typeof(System.MulticastDelegate)))
{
if (t.IsEnum)
{
StreamWriter file = Begin(t);
WriteHead(t, file);
RegEnumFunction(t, file);
End(file);
}
else if (t.BaseType == typeof(System.MulticastDelegate))
{
string f;
if (t.IsGenericType)
{
if (t.ContainsGenericParameters)
return false;
f = path + string.Format("Lua{0}_{1}.cs", _Name(GenericBaseName(t)), _Name(GenericName(t)));
}
else
{
f = path + "LuaDelegate_" + _Name(t.FullName) + ".cs";
}
StreamWriter file = new StreamWriter(f, false, Encoding.UTF8);
WriteDelegate(t, file);
file.Close();
return false;
}
else
{
funcname.Clear();
propname.Clear();
directfunc.Clear();
StreamWriter file = Begin(t);
WriteHead(t, file);
WriteConstructor(t, file);
WriteFunction(t, file);
WriteFunction(t, file, true);
WriteField(t, file);
RegFunction(t, file);
End(file);
if (t.BaseType != null && t.BaseType.Name == "UnityEvent`1")
{
string f = path + "LuaUnityEvent_" + _Name(GenericName(t.BaseType)) + ".cs";
file = new StreamWriter(f, false, Encoding.UTF8);
WriteEvent(t, file);
file.Close();
}
}
return true;
}
return false;
}
void WriteDelegate(Type t, StreamWriter file)
{
string temp = @"
using System;
using System.Collections.Generic;
using LuaInterface;
using UnityEngine;
namespace SLua
{
public partial class LuaDelegation : LuaObject
{
static internal int checkDelegate(IntPtr l,int p,out $FN ua) {
int op = extractFunction(l,p);
if(LuaDLL.lua_isnil(l,p)) {
ua=null;
return op;
}
else if (LuaDLL.lua_isuserdata(l, p)==1)
{
ua = ($FN)checkObj(l, p);
return op;
}
LuaDelegate ld;
checkType(l, -1, out ld);
if(ld.d!=null)
{
ua = ($FN)ld.d;
return op;
}
LuaDLL.lua_pop(l,1);
l = LuaState.get(l).L;
ua = ($ARGS) =>
{
int error = pushTry(l);
";
temp = temp.Replace("$TN", t.Name);
temp = temp.Replace("$FN", SimpleType(t));
MethodInfo mi = t.GetMethod("Invoke");
List<int> outindex = new List<int>();
List<int> refindex = new List<int>();
temp = temp.Replace("$ARGS", ArgsList(mi, ref outindex, ref refindex));
Write(file, temp);
this.indent = 4;
for (int n = 0; n < mi.GetParameters().Length; n++)
{
if (!outindex.Contains(n))
Write(file, "pushValue(l,a{0});", n + 1);
}
Write(file, "ld.call({0}, error);", mi.GetParameters().Length - outindex.Count);
if (mi.ReturnType != typeof(void))
WriteValueCheck(file, mi.ReturnType, 1, "ret", "error+");
foreach (int i in outindex)
{
string a = string.Format("a{0}", i + 1);
WriteCheckType(file, mi.GetParameters()[i].ParameterType, i + 1, a, "error+");
}
foreach (int i in refindex)
{
string a = string.Format("a{0}", i + 1);
WriteCheckType(file, mi.GetParameters()[i].ParameterType, i + 1, a, "error+");
}
Write(file, "LuaDLL.lua_settop(l, error-1);");
if (mi.ReturnType != typeof(void))
Write(file, "return ret;");
Write(file, "};");
Write(file, "ld.d=ua;");
Write(file, "return op;");
Write(file, "}");
Write(file, "}");
Write(file, "}");
}
string ArgsList(MethodInfo m, ref List<int> outindex, ref List<int> refindex)
{
string str = "";
ParameterInfo[] pars = m.GetParameters();
for (int n = 0; n < pars.Length; n++)
{
string t = SimpleType(pars[n].ParameterType);
ParameterInfo p = pars[n];
if (p.ParameterType.IsByRef && p.IsOut)
{
str += string.Format("out {0} a{1}", t, n + 1);
outindex.Add(n);
}
else if (p.ParameterType.IsByRef)
{
str += string.Format("ref {0} a{1}", t, n + 1);
refindex.Add(n);
}
else
str += string.Format("{0} a{1}", t, n + 1);
if (n < pars.Length - 1)
str += ",";
}
return str;
}
void tryMake(Type t)
{
if (t.BaseType == typeof(System.MulticastDelegate))
{
CodeGenerator cg = new CodeGenerator();
cg.path = this.path;
cg.Generate(t);
}
}
void WriteEvent(Type t, StreamWriter file)
{
string temp = @"
using System;
using System.Collections.Generic;
using LuaInterface;
using UnityEngine;
using UnityEngine.EventSystems;
namespace SLua
{
public class LuaUnityEvent_$CLS : LuaObject
{
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static public int AddListener(IntPtr l)
{
try
{
UnityEngine.Events.UnityEvent<$GN> self = checkSelf<UnityEngine.Events.UnityEvent<$GN>>(l);
UnityEngine.Events.UnityAction<$GN> a1;
checkType(l, 2, out a1);
self.AddListener(a1);
return 0;
}
catch (Exception e)
{
LuaDLL.luaL_error(l, e.ToString());
return 0;
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static public int RemoveListener(IntPtr l)
{
try
{
UnityEngine.Events.UnityEvent<$GN> self = checkSelf<UnityEngine.Events.UnityEvent<$GN>>(l);
UnityEngine.Events.UnityAction<$GN> a1;
checkType(l, 2, out a1);
self.RemoveListener(a1);
return 0;
}
catch (Exception e)
{
LuaDLL.luaL_error(l, e.ToString());
return 0;
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static public int Invoke(IntPtr l)
{
try
{
UnityEngine.Events.UnityEvent<$GN> self = checkSelf<UnityEngine.Events.UnityEvent<$GN>>(l);
$GN o;
checkType(l,2,out o);
self.Invoke(o);
return 0;
}
catch (Exception e)
{
LuaDLL.luaL_error(l, e.ToString());
return 0;
}
}
static public void reg(IntPtr l)
{
getTypeTable(l, typeof(LuaUnityEvent_$CLS).FullName);
addMember(l, AddListener);
addMember(l, RemoveListener);
addMember(l, Invoke);
createTypeMetatable(l, null, typeof(LuaUnityEvent_$CLS), typeof(UnityEngine.Events.UnityEventBase));
}
static bool checkType(IntPtr l,int p,out UnityEngine.Events.UnityAction<$GN> ua) {
LuaDLL.luaL_checktype(l, p, LuaTypes.LUA_TFUNCTION);
LuaDelegate ld;
checkType(l, p, out ld);
if (ld.d != null)
{
ua = (UnityEngine.Events.UnityAction<$GN>)ld.d;
return true;
}
l = LuaState.get(l).L;
ua = ($GN v) =>
{
int error = pushTry(l);
pushValue(l, v);
ld.call(1, error);
LuaDLL.lua_settop(l,error - 1);
};
ld.d = ua;
return true;
}
}
}";
temp = temp.Replace("$CLS", _Name(GenericName(t.BaseType)));
temp = temp.Replace("$FNAME", FullName(t));
temp = temp.Replace("$GN", GenericName(t.BaseType));
Write(file, temp);
}
void RegEnumFunction(Type t, StreamWriter file)
{
// Write export function
Write(file, "static public void reg(IntPtr l) {");
Write(file, "getEnumTable(l,\"{0}\");", string.IsNullOrEmpty(givenNamespace) ? FullName(t) : givenNamespace);
FieldInfo[] fields = t.GetFields();
foreach (FieldInfo f in fields)
{
if (f.Name == "value__") continue;
Write(file, "addMember(l,{0},\"{1}\");", (int)f.GetValue(null), f.Name);
}
Write(file, "LuaDLL.lua_pop(l, 1);");
Write(file, "}");
}
StreamWriter Begin(Type t)
{
string clsname = ExportName(t);
string f = path + clsname + ".cs";
StreamWriter file = new StreamWriter(f, false, Encoding.UTF8);
return file;
}
private void End(StreamWriter file)
{
Write(file, "}");
file.Flush();
file.Close();
}
private void WriteHead(Type t, StreamWriter file)
{
Write(file, "using UnityEngine;");
Write(file, "using System;");
Write(file, "using LuaInterface;");
Write(file, "using SLua;");
Write(file, "using System.Collections.Generic;");
Write(file, "public class {0} : LuaObject {{", ExportName(t));
}
private void WriteFunction(Type t, StreamWriter file, bool writeStatic = false)
{
BindingFlags bf = BindingFlags.Public | BindingFlags.DeclaredOnly;
if (writeStatic)
bf |= BindingFlags.Static;
else
bf |= BindingFlags.Instance;
MethodInfo[] members = t.GetMethods(bf);
foreach (MethodInfo mi in members)
{
bool instanceFunc;
if (writeStatic && isPInvoke(mi, out instanceFunc))
{
directfunc.Add(t.FullName + "." + mi.Name, instanceFunc);
continue;
}
string fn = writeStatic ? staticName(mi.Name) : mi.Name;
if (mi.MemberType == MemberTypes.Method
&& !IsObsolete(mi)
&& !DontExport(mi)
&& !funcname.Contains(fn)
&& isUsefullMethod(mi)
&& !MemberInFilter(t, mi))
{
WriteFunctionDec(file, fn);
WriteFunctionImpl(file, mi, t, bf);
funcname.Add(fn);
}
}
}
bool isPInvoke(MethodInfo mi, out bool instanceFunc)
{
object[] attrs = mi.GetCustomAttributes(typeof(MonoPInvokeCallbackAttribute), false);
if (attrs.Length > 0)
{
instanceFunc = mi.GetCustomAttributes(typeof(StaticExportAttribute), false).Length == 0;
return true;
}
instanceFunc = true;
return false;
}
string staticName(string name)
{
if (name.StartsWith("op_"))
return name;
return name + "_s";
}
bool MemberInFilter(Type t, MemberInfo mi)
{
return memberFilter.Contains(t.Name + "." + mi.Name);
}
bool IsObsolete(MemberInfo mi)
{
return LuaCodeGen.IsObsolete(mi);
}
void RegFunction(Type t, StreamWriter file)
{
// Write export function
Write(file, "static public void reg(IntPtr l) {");
if (t.BaseType != null && t.BaseType.Name.Contains("UnityEvent`"))
{
Write(file, "LuaUnityEvent_{1}.reg(l);", FullName(t), _Name((GenericName(t.BaseType))));
}
Write(file, "getTypeTable(l,\"{0}\");", string.IsNullOrEmpty(givenNamespace) ? FullName(t) : givenNamespace);
foreach (string f in funcname)
{
Write(file, "addMember(l,{0});", f);
}
foreach (string f in directfunc.Keys)
{
bool instance = directfunc[f];
Write(file, "addMember(l,{0},{1});", f, instance ? "true" : "false");
}
foreach (string f in propname.Keys)
{
PropPair pp = propname[f];
Write(file, "addMember(l,\"{0}\",{1},{2},{3});", f, pp.get, pp.set, pp.isInstance ? "true" : "false");
}
if (t.BaseType != null && !CutBase(t.BaseType))
{
if (t.BaseType.Name.Contains("UnityEvent`1"))
Write(file, "createTypeMetatable(l,{2}, typeof({0}),typeof(LuaUnityEvent_{1}));", TypeDecl(t), _Name(GenericName(t.BaseType)), constructorOrNot(t));
else
Write(file, "createTypeMetatable(l,{2}, typeof({0}),typeof({1}));", TypeDecl(t), TypeDecl(t.BaseType), constructorOrNot(t));
}
else
Write(file, "createTypeMetatable(l,{1}, typeof({0}));", TypeDecl(t), constructorOrNot(t));
Write(file, "}");
}
string constructorOrNot(Type t)
{
ConstructorInfo[] cons = GetValidConstructor(t);
if (cons.Length > 0 || t.IsValueType)
return "constructor";
return "null";
}
bool CutBase(Type t)
{
if (t.FullName.StartsWith("System.Object"))
return true;
return false;
}
void WriteSet(StreamWriter file, Type t, string cls, string fn, bool isstatic = false)
{
if (t.BaseType == typeof(MulticastDelegate))
{
if (isstatic)
{
Write(file, "if(op==0) {0}.{1}=v;", cls, fn);
Write(file, "else if(op==1) {0}.{1}+=v;", cls, fn);
Write(file, "else if(op==2) {0}.{1}-=v;", cls, fn);
}
else
{
Write(file, "if(op==0) self.{0}=v;", fn);
Write(file, "else if(op==1) self.{0}+=v;", fn);
Write(file, "else if(op==2) self.{0}-=v;", fn);
}
}
else
{
if (isstatic)
{
Write(file, "{0}.{1}=v;", cls, fn);
}
else
{
Write(file, "self.{0}=v;", fn);
}
}
}
private void WriteField(Type t, StreamWriter file)
{
// Write field set/get
FieldInfo[] fields = t.GetFields(BindingFlags.Static | BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);
foreach (FieldInfo fi in fields)
{
if (DontExport(fi) || IsObsolete(fi))
continue;
PropPair pp = new PropPair();
pp.isInstance = !fi.IsStatic;
if (fi.FieldType.BaseType != typeof(MulticastDelegate))
{
WriteFunctionAttr(file);
Write(file, "static public int get_{0}(IntPtr l) {{", fi.Name);
WriteTry(file);
if (fi.IsStatic)
{
WritePushValue(fi.FieldType, file, string.Format("{0}.{1}", TypeDecl(t), fi.Name));
}
else
{
WriteCheckSelf(file, t);
WritePushValue(fi.FieldType, file, string.Format("self.{0}", fi.Name));
}
Write(file, "return 1;");
WriteCatchExecption(file);
Write(file, "}");
pp.get = "get_" + fi.Name;
}
if (!fi.IsLiteral && !fi.IsInitOnly)
{
WriteFunctionAttr(file);
Write(file, "static public int set_{0}(IntPtr l) {{", fi.Name);
WriteTry(file);
if (fi.IsStatic)
{
Write(file, "{0} v;", TypeDecl(fi.FieldType));
WriteCheckType(file, fi.FieldType, 2);
WriteSet(file, fi.FieldType, TypeDecl(t), fi.Name, true);
}
else
{
WriteCheckSelf(file, t);
Write(file, "{0} v;", TypeDecl(fi.FieldType));
WriteCheckType(file, fi.FieldType, 2);
WriteSet(file, fi.FieldType, t.FullName, fi.Name);
}
if (t.IsValueType && !fi.IsStatic)
Write(file, "setBack(l,self);");
Write(file, "return 0;");
WriteCatchExecption(file);
Write(file, "}");
pp.set = "set_" + fi.Name;
}
propname.Add(fi.Name, pp);
tryMake(fi.FieldType);
}
//for this[]
List<PropertyInfo> getter = new List<PropertyInfo>();
List<PropertyInfo> setter = new List<PropertyInfo>();
// Write property set/get
PropertyInfo[] props = t.GetProperties(BindingFlags.Static | BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);
foreach (PropertyInfo fi in props)
{
//if (fi.Name == "Item" || IsObsolete(fi) || MemberInFilter(t,fi) || DontExport(fi))
if (IsObsolete(fi) || MemberInFilter(t, fi) || DontExport(fi))
continue;
if (fi.Name == "Item"
|| (t.Name == "String" && fi.Name == "Chars")) // for string[]
{
//for this[]
if (!fi.GetGetMethod().IsStatic && fi.GetIndexParameters().Length == 1)
{
if (fi.CanRead && !IsNotSupport(fi.PropertyType))
getter.Add(fi);
if (fi.CanWrite && fi.GetSetMethod() != null)
setter.Add(fi);
}
continue;
}
PropPair pp = new PropPair();
bool isInstance = true;
if (fi.CanRead && fi.GetGetMethod() != null)
{
if (!IsNotSupport(fi.PropertyType))
{
WriteFunctionAttr(file);
Write(file, "static public int get_{0}(IntPtr l) {{", fi.Name);
WriteTry(file);
if (fi.GetGetMethod().IsStatic)
{
isInstance = false;
WritePushValue(fi.PropertyType, file, string.Format("{0}.{1}", TypeDecl(t), fi.Name));
}
else
{
WriteCheckSelf(file, t);
WritePushValue(fi.PropertyType, file, string.Format("self.{0}", fi.Name));
}
Write(file, "return 1;");
WriteCatchExecption(file);
Write(file, "}");
pp.get = "get_" + fi.Name;
}
}
if (fi.CanWrite && fi.GetSetMethod() != null)
{
WriteFunctionAttr(file);
Write(file, "static public int set_{0}(IntPtr l) {{", fi.Name);
WriteTry(file);
if (fi.GetSetMethod().IsStatic)
{
WriteValueCheck(file, fi.PropertyType, 2);
WriteSet(file, fi.PropertyType, TypeDecl(t), fi.Name, true);
isInstance = false;
}
else
{
WriteCheckSelf(file, t);
WriteValueCheck(file, fi.PropertyType, 2);
WriteSet(file, fi.PropertyType, TypeDecl(t), fi.Name);
}
if (t.IsValueType)
Write(file, "setBack(l,self);");
Write(file, "return 0;");
WriteCatchExecption(file);
Write(file, "}");
pp.set = "set_" + fi.Name;
}
pp.isInstance = isInstance;
propname.Add(fi.Name, pp);
tryMake(fi.PropertyType);
}
//for this[]
WriteItemFunc(t, file, getter, setter);
}
void WriteItemFunc(Type t, StreamWriter file, List<PropertyInfo> getter, List<PropertyInfo> setter)
{
//Write property this[] set/get
if (getter.Count > 0)
{
//get
bool first_get = true;
WriteFunctionAttr(file);
Write(file, "static public int getItem(IntPtr l) {");
WriteTry(file);
WriteCheckSelf(file, t);
if (getter.Count == 1)
{
PropertyInfo _get = getter[0];
ParameterInfo[] infos = _get.GetIndexParameters();
WriteValueCheck(file, infos[0].ParameterType, 2, "v");
Write(file, "var ret = self[v];");
WritePushValue(_get.PropertyType, file, "ret");
Write(file, "return 1;");
}
else
{
Write(file, "LuaTypes t = LuaDLL.lua_type(l, 2);");
for (int i = 0; i < getter.Count; i++)
{
PropertyInfo fii = getter[i];
ParameterInfo[] infos = fii.GetIndexParameters();
Write(file, "{0}(matchType(l,2,t,typeof({1}))){{", first_get ? "if" : "else if", infos[0].ParameterType);
WriteValueCheck(file, infos[0].ParameterType, 2, "v");
Write(file, "var ret = self[v];");
WritePushValue(fii.PropertyType, file, "ret");
Write(file, "return 1;");
Write(file, "}");
first_get = false;
}
Write(file, "LuaDLL.luaL_error(l,\"No matched override function to call\");");
Write(file, "return 0;");
}
WriteCatchExecption(file);
Write(file, "}");
funcname.Add("getItem");
}
if (setter.Count > 0)
{
bool first_set = true;
WriteFunctionAttr(file);
Write(file, "static public int setItem(IntPtr l) {");
WriteTry(file);
WriteCheckSelf(file, t);
if (setter.Count == 1)
{
PropertyInfo _set = setter[0];
ParameterInfo[] infos = _set.GetIndexParameters();
WriteValueCheck(file, infos[0].ParameterType, 2);
WriteValueCheck(file, _set.PropertyType, 3, "c");
Write(file, "self[v]=c;");
}
else
{
Write(file, "LuaTypes t = LuaDLL.lua_type(l, 2);");
for (int i = 0; i < setter.Count; i++)
{
PropertyInfo fii = setter[i];
if (t.BaseType != typeof(MulticastDelegate))
{
ParameterInfo[] infos = fii.GetIndexParameters();
Write(file, "{0}(matchType(l,2,t,typeof({1}))){{", first_set ? "if" : "else if", infos[0].ParameterType);
WriteValueCheck(file, infos[0].ParameterType, 2, "v");
WriteValueCheck(file, fii.PropertyType, 3, "c");
Write(file, "self[v]=c;");
Write(file, "return 0;");
Write(file, "}");
first_set = false;
}
if (t.IsValueType)
Write(file, "setBack(l,self);");
}
Write(file, "LuaDLL.luaL_error(l,\"No matched override function to call\");");
}
Write(file, "return 0;");
WriteCatchExecption(file);
Write(file, "}");
funcname.Add("setItem");
}
}
void WriteTry(StreamWriter file)
{
Write(file, "try {");
}
void WriteCatchExecption(StreamWriter file)
{
Write(file, "}");
Write(file, "catch(Exception e) {");
Write(file, "LuaDLL.luaL_error(l, e.ToString());");
Write(file, "return 0;");
Write(file, "}");
}
void WriteCheckType(StreamWriter file, Type t, int n, string v = "v", string nprefix = "")
{
if (t.IsEnum)
Write(file, "checkEnum(l,{2}{0},out {1});", n, v, nprefix);
else if (t.BaseType == typeof(System.MulticastDelegate))
Write(file, "int op=LuaDelegation.checkDelegate(l,{2}{0},out {1});", n, v, nprefix);
else
Write(file, "checkType(l,{2}{0},out {1});", n, v, nprefix);
}
void WriteValueCheck(StreamWriter file, Type t, int n, string v = "v", string nprefix = "")
{
Write(file, "{0} {1};", SimpleType(t), v);
WriteCheckType(file, t, n, v, nprefix);
}
private void WriteFunctionAttr(StreamWriter file)
{
Write(file, "[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]");
}
ConstructorInfo[] GetValidConstructor(Type t)
{
List<ConstructorInfo> ret = new List<ConstructorInfo>();
if (t.GetConstructor(Type.EmptyTypes) == null && t.IsAbstract && t.IsSealed)
return ret.ToArray();
if (t.BaseType != null && t.BaseType.Name == "MonoBehaviour")
return ret.ToArray();
ConstructorInfo[] cons = t.GetConstructors(BindingFlags.Instance | BindingFlags.Public);
foreach (ConstructorInfo ci in cons)
{
if (!IsObsolete(ci) && !DontExport(ci) && !ContainUnsafe(ci))
ret.Add(ci);
}
return ret.ToArray();
}
bool ContainUnsafe(MethodBase mi)
{
foreach (ParameterInfo p in mi.GetParameters())
{
if (p.ParameterType.FullName.Contains("*"))
return true;
}
return false;
}
bool DontExport(MemberInfo mi)
{
return mi.GetCustomAttributes(typeof(DoNotToLuaAttribute), false).Length > 0;
}
private void WriteConstructor(Type t, StreamWriter file)
{
ConstructorInfo[] cons = GetValidConstructor(t);
if (cons.Length > 0)
{
WriteFunctionAttr(file);
Write(file, "static public int constructor(IntPtr l) {");
WriteTry(file);
if (cons.Length > 1)
Write(file, "int argc = LuaDLL.lua_gettop(l);");
Write(file, "{0} o;", TypeDecl(t));
bool first = true;
for (int n = 0; n < cons.Length; n++)
{
ConstructorInfo ci = cons[n];
ParameterInfo[] pars = ci.GetParameters();
if (cons.Length > 1)
{
if (isUniqueArgsCount(cons, ci))
Write(file, "{0}(argc=={1}){{", first ? "if" : "else if", ci.GetParameters().Length + 1);
else
Write(file, "{0}(matchType(l,argc,2{1})){{", first ? "if" : "else if", TypeDecl(pars));
}
for (int k = 0; k < pars.Length; k++)
{
ParameterInfo p = pars[k];
bool hasParams = p.GetCustomAttributes(typeof(ParamArrayAttribute), false).Length > 0;
CheckArgument(file, p.ParameterType, k, 2, p.IsOut, hasParams);
}
Write(file, "o=new {0}({1});", TypeDecl(t), FuncCall(ci));
if (t.Name == "String") // if export system.string, push string as ud not lua string
Write(file, "pushObject(l,o);");
else
Write(file, "pushValue(l,o);");
Write(file, "return 1;");
if (cons.Length == 1)
WriteCatchExecption(file);
Write(file, "}");
first = false;
}
if (cons.Length > 1)
{
Write(file, "LuaDLL.luaL_error(l,\"New object failed.\");");
Write(file, "return 0;");
WriteCatchExecption(file);
Write(file, "}");
}
}
else if (t.IsValueType) // default constructor
{
WriteFunctionAttr(file);
Write(file, "static public int constructor(IntPtr l) {");
WriteTry(file);
Write(file, "{0} o;", FullName(t));
Write(file, "o=new {0}();", FullName(t));
Write(file, "pushValue(l,o);");
Write(file, "return 1;");
WriteCatchExecption(file);
Write(file, "}");
}
}
bool IsNotSupport(Type t)
{
if (t.IsSubclassOf(typeof(Delegate)))
return true;
return false;
}
string[] prefix = new string[] { "System.Collections.Generic" };
string RemoveRef(string s, bool removearray = true)
{
if (s.EndsWith("&")) s = s.Substring(0, s.Length - 1);
if (s.EndsWith("[]") && removearray) s = s.Substring(0, s.Length - 2);
if (s.StartsWith(prefix[0])) s = s.Substring(prefix[0].Length + 1, s.Length - prefix[0].Length - 1);
s = s.Replace("+", ".");
if (s.Contains("`"))
{
string regstr = @"`\d";
Regex r = new Regex(regstr, RegexOptions.None);
s = r.Replace(s, "");
s = s.Replace("[", "<");
s = s.Replace("]", ">");
}
return s;
}
string GenericBaseName(Type t)
{
string n = t.FullName;
if (n.IndexOf('[') > 0)
{
n = n.Substring(0, n.IndexOf('['));
}
return n.Replace("+", ".");
}
string GenericName(Type t)
{
try
{
Type[] tt = t.GetGenericArguments();
string ret = "";
for (int n = 0; n < tt.Length; n++)
{
string dt = SimpleType(tt[n]);
ret += dt;
if (n < tt.Length - 1)
ret += "_";
}
return ret;
}
catch (Exception e)
{
Debug.Log(e.ToString());
return "";
}
}
string _Name(string n)
{
string ret = "";
for (int i = 0; i < n.Length; i++)
{
if (char.IsLetterOrDigit(n[i]))
ret += n[i];
else
ret += "_";
}
return ret;
}
string TypeDecl(ParameterInfo[] pars)
{
string ret = "";
for (int n = 0; n < pars.Length; n++)
{
ret += ",typeof(";
if (pars[n].IsOut)
ret += "LuaOut";
else
ret += SimpleType(pars[n].ParameterType);
ret += ")";
}
return ret;
}
bool isUsefullMethod(MethodInfo method)
{
if (method.Name != "GetType" && method.Name != "GetHashCode" && method.Name != "Equals" &&
method.Name != "ToString" && method.Name != "Clone" &&
method.Name != "GetEnumerator" && method.Name != "CopyTo" &&
method.Name != "op_Implicit" &&
!method.Name.StartsWith("get_", StringComparison.Ordinal) &&
!method.Name.StartsWith("set_", StringComparison.Ordinal) &&
!method.Name.StartsWith("add_", StringComparison.Ordinal) &&
!IsObsolete(method) && !method.IsGenericMethod &&
//!method.Name.StartsWith("op_", StringComparison.Ordinal) &&
!method.Name.StartsWith("remove_", StringComparison.Ordinal))
{
return true;
}
return false;
}
void WriteFunctionDec(StreamWriter file, string name)
{
WriteFunctionAttr(file);
Write(file, "static public int {0}(IntPtr l) {{", name);
}
MethodBase[] GetMethods(Type t, string name, BindingFlags bf)
{
List<MethodBase> methods = new List<MethodBase>();
MemberInfo[] cons = t.GetMember(name, bf);
foreach (MemberInfo m in cons)
{
if (m.MemberType == MemberTypes.Method
&& !IsObsolete(m)
&& !DontExport(m)
&& isUsefullMethod((MethodInfo)m))
methods.Add((MethodBase)m);
}
methods.Sort((a, b) =>
{
return a.GetParameters().Length - b.GetParameters().Length;
});
return methods.ToArray();
}
void WriteFunctionImpl(StreamWriter file, MethodInfo m, Type t, BindingFlags bf)
{
WriteTry(file);
MethodBase[] cons = GetMethods(t, m.Name, bf);
if (cons.Length == 1) // no override function
{
if (isUsefullMethod(m) && !m.ReturnType.ContainsGenericParameters && !m.ContainsGenericParameters) // don't support generic method
WriteFunctionCall(m, file, t);
else
{
Write(file, "LuaDLL.luaL_error(l,\"No matched override function to call\");");
Write(file, "return 0;");
}
}
else // 2 or more override function
{
Write(file, "int argc = LuaDLL.lua_gettop(l);");
bool first = true;
for (int n = 0; n < cons.Length; n++)
{
if (cons[n].MemberType == MemberTypes.Method)
{
MethodInfo mi = cons[n] as MethodInfo;
ParameterInfo[] pars = mi.GetParameters();
if (isUsefullMethod(mi)
&& !mi.ReturnType.ContainsGenericParameters
/*&& !ContainGeneric(pars)*/) // don't support generic method
{
if (isUniqueArgsCount(cons, mi))
Write(file, "{0}(argc=={1}){{", first ? "if" : "else if", mi.IsStatic ? mi.GetParameters().Length : mi.GetParameters().Length + 1);
else
Write(file, "{0}(matchType(l,argc,{1}{2})){{", first ? "if" : "else if", mi.IsStatic ? 1 : 2, TypeDecl(pars));
WriteFunctionCall(mi, file, t);
Write(file, "}");
first = false;
}
}
}
Write(file, "LuaDLL.luaL_error(l,\"No matched override function to call\");");
Write(file, "return 0;");
}
WriteCatchExecption(file);
Write(file, "}");
}
bool isUniqueArgsCount(MethodBase[] cons, MethodBase mi)
{
foreach (MethodBase member in cons)
{
MethodBase m = (MethodBase)member;
if (m != mi && mi.GetParameters().Length == m.GetParameters().Length)
return false;
}
return true;
}
bool ContainGeneric(ParameterInfo[] pars)
{
foreach (ParameterInfo p in pars)
{
if (p.ParameterType.IsGenericType || p.ParameterType.IsGenericParameter || p.ParameterType.IsGenericTypeDefinition)
return true;
}
return false;
}
void WriteCheckSelf(StreamWriter file, Type t)
{
if (t.IsValueType)
{
Write(file, "{0} self;", TypeDecl(t));
Write(file, "checkType(l,1,out self);");
}
else
Write(file, "{0} self=({0})checkSelf(l);", TypeDecl(t));
}
private void WriteFunctionCall(MethodInfo m, StreamWriter file, Type t)
{
bool hasref = false;
ParameterInfo[] pars = m.GetParameters();
int argIndex = 1;
if (!m.IsStatic)
{
WriteCheckSelf(file, t);
argIndex++;
}
for (int n = 0; n < pars.Length; n++)
{
ParameterInfo p = pars[n];
string pn = p.ParameterType.Name;
if (pn.EndsWith("&"))
{
hasref = true;
}
bool hasParams = p.GetCustomAttributes(typeof(ParamArrayAttribute), false).Length > 0;
CheckArgument(file, p.ParameterType, n, argIndex, p.IsOut, hasParams);
}
string ret = "";
if (m.ReturnType != typeof(void))
{
ret = "var ret=";
}
if (m.IsStatic)
{
if (m.Name == "op_Multiply")
Write(file, "{0}a1*a2;", ret);
else if (m.Name == "op_Subtraction")
Write(file, "{0}a1-a2;", ret);
else if (m.Name == "op_Addition")
Write(file, "{0}a1+a2;", ret);
else if (m.Name == "op_Division")
Write(file, "{0}a1/a2;", ret);
else if (m.Name == "op_UnaryNegation")
Write(file, "{0}-a1;", ret);
else if (m.Name == "op_Equality")
Write(file, "{0}(a1==a2);", ret);
else if (m.Name == "op_Inequality")
Write(file, "{0}(a1!=a2);", ret);
else if (m.Name == "op_LessThan")
Write(file, "{0}(a1<a2);", ret);
else if (m.Name == "op_GreaterThan")
Write(file, "{0}(a2<a1);", ret);
else if (m.Name == "op_LessThanOrEqual")
Write(file, "{0}(a1<=a2);", ret);
else if (m.Name == "op_GreaterThanOrEqual")
Write(file, "{0}(a2<=a1);", ret);
else
Write(file, "{3}{2}.{0}({1});", m.Name, FuncCall(m), TypeDecl(t), ret);
}
else
Write(file, "{2}self.{0}({1});", m.Name, FuncCall(m), ret);
int retcount = 0;
if (m.ReturnType != typeof(void))
{
WritePushValue(m.ReturnType, file);
retcount = 1;
}
// push out/ref value for return value
if (hasref)
{
for (int n = 0; n < pars.Length; n++)
{
ParameterInfo p = pars[n];
if (p.ParameterType.IsByRef)
{
WritePushValue(p.ParameterType, file, string.Format("a{0}", n + 1));
retcount++;
}
}
}
if (t.IsValueType && m.ReturnType == typeof(void) && !m.IsStatic)
Write(file, "setBack(l,self);");
Write(file, "return {0};", retcount);
}
string SimpleType_(Type t)
{
string tn = t.Name;
switch (tn)
{
case "Single":
return "float";
case "String":
return "string";
case "Double":
return "double";
case "Boolean":
return "bool";
case "Int32":
return "int";
case "Object":
return FullName(t);
default:
tn = TypeDecl(t);
tn = tn.Replace("System.Collections.Generic.", "");
tn = tn.Replace("System.Object", "object");
return tn;
}
}
string SimpleType(Type t)
{
string ret = SimpleType_(t);
return ret;
}
void WritePushValue(Type t, StreamWriter file)
{
if (t.IsEnum)
Write(file, "pushEnum(l,(int)ret);");
else
Write(file, "pushValue(l,ret);");
}
void WritePushValue(Type t, StreamWriter file, string ret)
{
if (t.IsEnum)
Write(file, "pushEnum(l,(int){0});", ret);
else
Write(file, "pushValue(l,{0});", ret);
}
void Write(StreamWriter file, string fmt, params object[] args)
{
if (fmt.StartsWith("}")) indent--;
for (int n = 0; n < indent; n++)
file.Write("\t");
if (args.Length == 0)
file.WriteLine(fmt);
else
{
string line = string.Format(fmt, args);
file.WriteLine(line);
}
if (fmt.EndsWith("{")) indent++;
}
private void CheckArgument(StreamWriter file, Type t, int n, int argstart, bool isout, bool isparams)
{
Write(file, "{0} a{1};", TypeDecl(t), n + 1);
if (!isout)
{
if (t.IsEnum)
Write(file, "checkEnum(l,{0},out a{1});", n + argstart, n + 1);
else if (t.BaseType == typeof(System.MulticastDelegate))
{
tryMake(t);
Write(file, "LuaDelegation.checkDelegate(l,{0},out a{1});", n + argstart, n + 1);
}
else if (isparams)
Write(file, "checkParams(l,{0},out a{1});", n + argstart, n + 1);
else
Write(file, "checkType(l,{0},out a{1});", n + argstart, n + 1);
}
}
string FullName(string str)
{
if (str == null)
{
throw new NullReferenceException();
}
return RemoveRef(str.Replace("+", "."));
}
string TypeDecl(Type t)
{
if (t.IsGenericType)
{
string ret = GenericBaseName(t);
string gs = "";
gs += "<";
Type[] types = t.GetGenericArguments();
for (int n = 0; n < types.Length; n++)
{
gs += TypeDecl(types[n]);
if (n < types.Length - 1)
gs += ",";
}
gs += ">";
ret = Regex.Replace(ret, @"`\d", gs);
return ret;
}
if (t.IsArray)
{
return TypeDecl(t.GetElementType()) + "[]";
}
else
return RemoveRef(t.ToString(), false);
}
string ExportName(Type t)
{
if (t.IsGenericType)
{
return string.Format("Lua_{0}_{1}", _Name(GenericBaseName(t)), _Name(GenericName(t)));
}
else
{
string name = RemoveRef(t.FullName, true);
name = "Lua_" + name;
return name.Replace(".", "_");
}
}
string FullName(Type t)
{
if (t.FullName == null)
{
Debug.Log(t.Name);
return t.Name;
}
return FullName(t.FullName);
}
string FuncCall(MethodBase m)
{
string str = "";
ParameterInfo[] pars = m.GetParameters();
for (int n = 0; n < pars.Length; n++)
{
ParameterInfo p = pars[n];
if (p.ParameterType.IsByRef && p.IsOut)
str += string.Format("out a{0}", n + 1);
else if (p.ParameterType.IsByRef)
str += string.Format("ref a{0}", n + 1);
else
str += string.Format("a{0}", n + 1);
if (n < pars.Length - 1)
str += ",";
}
return str;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Threading;
using Corelicious;
using Corelicious.Extensions;
using JetBrains.Annotations;
using Lucene.Net.Index;
using Lucene.Net.Support;
namespace Corelicious.Lucene {
/// <summary>
/// Singleton that holds several field-cache implementations that support
/// typed values.
/// </summary>
public sealed class MultiFieldCache {
/// <summary>
/// The default instance.
/// </summary>
[NotNull]
public static readonly MultiFieldCache Default = new MultiFieldCache();
private readonly MultiStringFieldCache _stringCache = new MultiStringFieldCache();
private readonly MultiGuidFieldCache _guidCache = new MultiGuidFieldCache();
private readonly MultiInt32FieldCache _int32Cache = new MultiInt32FieldCache();
#region Strings
/// <summary>
/// Retrieves all terms for a field within a document.
/// </summary>
[CanBeNull]
public String[] GetStrings([NotNull] IndexReader reader, [NotNull] String field, Int32 documentId) {
var values = _stringCache.Get(reader, field);
if (values.Length < documentId)
return null;
return values[documentId];
}
/// <summary>
/// Retrieves an jagged array where the outer index represents the document id,
/// and the inner array all terms found in the specified <param name="field" />
/// within that document.
/// </summary>
public String[][] GetStrings([NotNull] IndexReader reader, [NotNull] String field) {
return _stringCache.Get(reader, field);
}
#endregion
#region Guids
/// <summary>
/// Retrieves all terms for a field within a document.
/// </summary>
[CanBeNull]
public Guid[] GetGuids([NotNull] IndexReader reader, [NotNull] String field, Int32 documentId) {
var values = _guidCache.Get(reader, field);
if (values.Length < documentId)
return null;
return values[documentId];
}
/// <summary>
/// Retrieves an jagged array where the outer index represents the document id,
/// and the inner array all terms found in the specified <param name="field" />
/// within that document.
/// </summary>
public Guid[][] GetGuids([NotNull] IndexReader reader, [NotNull] String field) {
return _guidCache.Get(reader, field);
}
#endregion
#region Int32
[CanBeNull]
public Int32[] GetInt32([NotNull] IndexReader reader, [NotNull] String field, Int32 documentId) {
var values = _int32Cache.Get(reader, field);
if (values.Length < documentId)
return null;
return values[documentId];
}
public Int32[][] GetInt32s([NotNull] IndexReader reader, [NotNull] String field) {
return _int32Cache.Get(reader, field);
}
#endregion
}
public abstract class MultiFieldCache<T> {
/// <summary>
/// FieldCacheKey => Field => Values[][]
/// </summary>
private readonly WeakDictionary<Object, IDictionary<String, Object>> _readerCache = new WeakDictionary<Object, IDictionary<String, Object>>();
private readonly ReaderWriterLockSlim _readerCacheLock = new ReaderWriterLockSlim();
public T[][] Get([NotNull] IndexReader reader, [NotNull] String field) {
var cacheKey = reader.FieldCacheKey;
Check.NotNull(cacheKey, "cacheKey == null");
IDictionary<String, Object> innerCache;
Object value;
using (_readerCacheLock.GetReadLock()) {
if (_readerCache.TryGetValue(cacheKey, out innerCache) && innerCache != null) {
if (innerCache.TryGetValue(field, out value)) {
var values = value as T[][];
if (values != null)
return values;
}
}
}
using (_readerCacheLock.GetWriteLock()) {
if (!_readerCache.TryGetValue(cacheKey, out innerCache)) {
innerCache = new Dictionary<String, Object>();
_readerCache[cacheKey] = innerCache;
}
Check.NotNull(innerCache, "innerCache == null");
innerCache.TryGetValue(field, out value);
if (value == null) {
value = new Placeholder();
innerCache[field] = value;
}
}
if (value is Placeholder) {
lock (value) {
var progress = (Placeholder)value;
if (progress.Value == null) {
progress.Value = ReadValues(reader, field);
using (_readerCacheLock.GetWriteLock()) {
innerCache[field] = progress.Value;
}
}
return progress.Value;
}
}
return (T[][])value;
}
private class Placeholder {
public T[][] Value { get; set; }
}
protected virtual T[][] ReadValues([NotNull] IndexReader reader, [NotNull] String field) {
var docCount = reader.MaxDoc;
var resultLists = new List<T>[docCount];
using (var termDocs = reader.TermDocs())
using (var termEnum = reader.Terms(new Term(field))) {
do {
var term = termEnum.Term;
if (term == null) break;
if (term.Field != field) break;
var termValue = term.Text;
if (termValue != null) {
T realValue;
if (!TryParse(termValue, out realValue))
continue;
termDocs.Seek(termEnum);
while (termDocs.Next()) {
var docId = termDocs.Doc;
var docList = resultLists[docId];
if (docList == null) {
docList = new List<T>();
resultLists[docId] = docList;
}
docList.Add(realValue);
}
}
} while (termEnum.Next());
}
var result = new T[docCount][];
for(var docId = 0; docId < docCount; ++docId) {
var docList = resultLists[docId];
if (docList != null)
result[docId] = docList.ToArray();
}
return result;
}
private static Int32? FindLowestIndex([NotNull] T[] docArr) {
for (var idx = 0; idx < docArr.Length; ++idx) {
if (docArr[idx] == null)
return idx;
}
return null;
}
protected abstract Boolean TryParse([NotNull] String value, out T result);
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 1.1.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.EventHub
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// ConsumerGroupsOperations operations.
/// </summary>
internal partial class ConsumerGroupsOperations : IServiceOperations<EventHubManagementClient>, IConsumerGroupsOperations
{
/// <summary>
/// Initializes a new instance of the ConsumerGroupsOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal ConsumerGroupsOperations(EventHubManagementClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the EventHubManagementClient
/// </summary>
public EventHubManagementClient Client { get; private set; }
/// <summary>
/// Creates or updates an Event Hubs consumer group as a nested resource within
/// a Namespace.
/// </summary>
/// <param name='resourceGroupName'>
/// Name of the resource group within the azure subscription.
/// </param>
/// <param name='namespaceName'>
/// The Namespace name
/// </param>
/// <param name='eventHubName'>
/// The Event Hub name
/// </param>
/// <param name='consumerGroupName'>
/// The consumer group name
/// </param>
/// <param name='parameters'>
/// Parameters supplied to create or update a consumer group resource.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<ConsumerGroup>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string eventHubName, string consumerGroupName, ConsumerGroup parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (resourceGroupName != null)
{
if (resourceGroupName.Length > 90)
{
throw new ValidationException(ValidationRules.MaxLength, "resourceGroupName", 90);
}
if (resourceGroupName.Length < 1)
{
throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 1);
}
}
if (namespaceName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "namespaceName");
}
if (namespaceName != null)
{
if (namespaceName.Length > 50)
{
throw new ValidationException(ValidationRules.MaxLength, "namespaceName", 50);
}
if (namespaceName.Length < 6)
{
throw new ValidationException(ValidationRules.MinLength, "namespaceName", 6);
}
}
if (eventHubName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "eventHubName");
}
if (eventHubName != null)
{
if (eventHubName.Length > 50)
{
throw new ValidationException(ValidationRules.MaxLength, "eventHubName", 50);
}
if (eventHubName.Length < 1)
{
throw new ValidationException(ValidationRules.MinLength, "eventHubName", 1);
}
}
if (consumerGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "consumerGroupName");
}
if (consumerGroupName != null)
{
if (consumerGroupName.Length > 50)
{
throw new ValidationException(ValidationRules.MaxLength, "consumerGroupName", 50);
}
if (consumerGroupName.Length < 1)
{
throw new ValidationException(ValidationRules.MinLength, "consumerGroupName", 1);
}
}
if (parameters == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "parameters");
}
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("namespaceName", namespaceName);
tracingParameters.Add("eventHubName", eventHubName);
tracingParameters.Add("consumerGroupName", consumerGroupName);
tracingParameters.Add("parameters", parameters);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "CreateOrUpdate", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.EventHub/namespaces/{namespaceName}/eventhubs/{eventHubName}/consumergroups/{consumerGroupName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{namespaceName}", System.Uri.EscapeDataString(namespaceName));
_url = _url.Replace("{eventHubName}", System.Uri.EscapeDataString(eventHubName));
_url = _url.Replace("{consumerGroupName}", System.Uri.EscapeDataString(consumerGroupName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PUT");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(parameters != null)
{
_requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<ConsumerGroup>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<ConsumerGroup>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Deletes a consumer group from the specified Event Hub and resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// Name of the resource group within the azure subscription.
/// </param>
/// <param name='namespaceName'>
/// The Namespace name
/// </param>
/// <param name='eventHubName'>
/// The Event Hub name
/// </param>
/// <param name='consumerGroupName'>
/// The consumer group name
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string eventHubName, string consumerGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (resourceGroupName != null)
{
if (resourceGroupName.Length > 90)
{
throw new ValidationException(ValidationRules.MaxLength, "resourceGroupName", 90);
}
if (resourceGroupName.Length < 1)
{
throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 1);
}
}
if (namespaceName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "namespaceName");
}
if (namespaceName != null)
{
if (namespaceName.Length > 50)
{
throw new ValidationException(ValidationRules.MaxLength, "namespaceName", 50);
}
if (namespaceName.Length < 6)
{
throw new ValidationException(ValidationRules.MinLength, "namespaceName", 6);
}
}
if (eventHubName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "eventHubName");
}
if (eventHubName != null)
{
if (eventHubName.Length > 50)
{
throw new ValidationException(ValidationRules.MaxLength, "eventHubName", 50);
}
if (eventHubName.Length < 1)
{
throw new ValidationException(ValidationRules.MinLength, "eventHubName", 1);
}
}
if (consumerGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "consumerGroupName");
}
if (consumerGroupName != null)
{
if (consumerGroupName.Length > 50)
{
throw new ValidationException(ValidationRules.MaxLength, "consumerGroupName", 50);
}
if (consumerGroupName.Length < 1)
{
throw new ValidationException(ValidationRules.MinLength, "consumerGroupName", 1);
}
}
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("namespaceName", namespaceName);
tracingParameters.Add("eventHubName", eventHubName);
tracingParameters.Add("consumerGroupName", consumerGroupName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Delete", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.EventHub/namespaces/{namespaceName}/eventhubs/{eventHubName}/consumergroups/{consumerGroupName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{namespaceName}", System.Uri.EscapeDataString(namespaceName));
_url = _url.Replace("{eventHubName}", System.Uri.EscapeDataString(eventHubName));
_url = _url.Replace("{consumerGroupName}", System.Uri.EscapeDataString(consumerGroupName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("DELETE");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 204 && (int)_statusCode != 200)
{
var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets a description for the specified consumer group.
/// </summary>
/// <param name='resourceGroupName'>
/// Name of the resource group within the azure subscription.
/// </param>
/// <param name='namespaceName'>
/// The Namespace name
/// </param>
/// <param name='eventHubName'>
/// The Event Hub name
/// </param>
/// <param name='consumerGroupName'>
/// The consumer group name
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<ConsumerGroup>> GetWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string eventHubName, string consumerGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (resourceGroupName != null)
{
if (resourceGroupName.Length > 90)
{
throw new ValidationException(ValidationRules.MaxLength, "resourceGroupName", 90);
}
if (resourceGroupName.Length < 1)
{
throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 1);
}
}
if (namespaceName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "namespaceName");
}
if (namespaceName != null)
{
if (namespaceName.Length > 50)
{
throw new ValidationException(ValidationRules.MaxLength, "namespaceName", 50);
}
if (namespaceName.Length < 6)
{
throw new ValidationException(ValidationRules.MinLength, "namespaceName", 6);
}
}
if (eventHubName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "eventHubName");
}
if (eventHubName != null)
{
if (eventHubName.Length > 50)
{
throw new ValidationException(ValidationRules.MaxLength, "eventHubName", 50);
}
if (eventHubName.Length < 1)
{
throw new ValidationException(ValidationRules.MinLength, "eventHubName", 1);
}
}
if (consumerGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "consumerGroupName");
}
if (consumerGroupName != null)
{
if (consumerGroupName.Length > 50)
{
throw new ValidationException(ValidationRules.MaxLength, "consumerGroupName", 50);
}
if (consumerGroupName.Length < 1)
{
throw new ValidationException(ValidationRules.MinLength, "consumerGroupName", 1);
}
}
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("namespaceName", namespaceName);
tracingParameters.Add("eventHubName", eventHubName);
tracingParameters.Add("consumerGroupName", consumerGroupName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.EventHub/namespaces/{namespaceName}/eventhubs/{eventHubName}/consumergroups/{consumerGroupName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{namespaceName}", System.Uri.EscapeDataString(namespaceName));
_url = _url.Replace("{eventHubName}", System.Uri.EscapeDataString(eventHubName));
_url = _url.Replace("{consumerGroupName}", System.Uri.EscapeDataString(consumerGroupName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<ConsumerGroup>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<ConsumerGroup>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets all the consumer groups in a Namespace. An empty feed is returned if
/// no consumer group exists in the Namespace.
/// </summary>
/// <param name='resourceGroupName'>
/// Name of the resource group within the azure subscription.
/// </param>
/// <param name='namespaceName'>
/// The Namespace name
/// </param>
/// <param name='eventHubName'>
/// The Event Hub name
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<ConsumerGroup>>> ListByEventHubWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string eventHubName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (resourceGroupName != null)
{
if (resourceGroupName.Length > 90)
{
throw new ValidationException(ValidationRules.MaxLength, "resourceGroupName", 90);
}
if (resourceGroupName.Length < 1)
{
throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 1);
}
}
if (namespaceName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "namespaceName");
}
if (namespaceName != null)
{
if (namespaceName.Length > 50)
{
throw new ValidationException(ValidationRules.MaxLength, "namespaceName", 50);
}
if (namespaceName.Length < 6)
{
throw new ValidationException(ValidationRules.MinLength, "namespaceName", 6);
}
}
if (eventHubName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "eventHubName");
}
if (eventHubName != null)
{
if (eventHubName.Length > 50)
{
throw new ValidationException(ValidationRules.MaxLength, "eventHubName", 50);
}
if (eventHubName.Length < 1)
{
throw new ValidationException(ValidationRules.MinLength, "eventHubName", 1);
}
}
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("namespaceName", namespaceName);
tracingParameters.Add("eventHubName", eventHubName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListByEventHub", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.EventHub/namespaces/{namespaceName}/eventhubs/{eventHubName}/consumergroups").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{namespaceName}", System.Uri.EscapeDataString(namespaceName));
_url = _url.Replace("{eventHubName}", System.Uri.EscapeDataString(eventHubName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<ConsumerGroup>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<ConsumerGroup>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets all the consumer groups in a Namespace. An empty feed is returned if
/// no consumer group exists in the Namespace.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<ConsumerGroup>>> ListByEventHubNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (nextPageLink == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextPageLink", nextPageLink);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListByEventHubNext", tracingParameters);
}
// Construct URL
string _url = "{nextLink}";
_url = _url.Replace("{nextLink}", nextPageLink);
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<ConsumerGroup>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<ConsumerGroup>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Android.Accounts;
using Android.App;
using Android.Content;
using Android.Content.PM;
using Android.Gms.Auth;
using Android.Gms.Common;
using Android.OS;
using Android.Text;
using Android.Text.Style;
using Android.Views;
using Android.Widget;
using Toggl.Joey.UI.Utils;
using Toggl.Joey.UI.Views;
using Toggl.Phoebe.Analytics;
using Toggl.Phoebe.Logging;
using Toggl.Phoebe.Net;
using XPlatUtils;
using DialogFragment = Android.Support.V4.App.DialogFragment;
using Fragment = Android.Support.V4.App.Fragment;
using FragmentManager = Android.Support.V4.App.FragmentManager;
namespace Toggl.Joey.UI.Activities
{
[Activity (
Exported = false,
ScreenOrientation = ScreenOrientation.Portrait,
WindowSoftInputMode = SoftInput.StateHidden,
Theme = "@style/Theme.Toggl.Login")]
public class LoginActivity : BaseActivity, ViewTreeObserver.IOnGlobalLayoutListener
{
private const string LogTag = "LoginActivity";
private static readonly string ExtraShowPassword = "com.toggl.timer.show_password";
private Mode? lastScreen;
private bool hasGoogleAccounts;
private bool showPassword;
private bool isAuthenticating;
private ISpannable formattedLegalText;
private int topLogoPosition;
private ImageView bigLogo;
protected ScrollView ScrollView { get; private set; }
protected Button SwitchModeButton { get; private set; }
protected AutoCompleteTextView EmailEditText { get; private set; }
protected EditText PasswordEditText { get; private set; }
protected Button PasswordToggleButton { get; private set; }
protected Button LoginButton { get; private set; }
protected TextView LegalTextView { get; private set; }
protected Button GoogleLoginButton { get; private set; }
private void FindViews ()
{
ScrollView = FindViewById<ScrollView> (Resource.Id.ScrollView);
FindViewById<TextView> (Resource.Id.SwitchViewText).SetFont (Font.RobotoLight);
bigLogo = FindViewById<ImageView> (Resource.Id.MainLogoLoginScreen);
SwitchModeButton = FindViewById<Button> (Resource.Id.SwitchViewButton);
EmailEditText = FindViewById<AutoCompleteTextView> (Resource.Id.EmailAutoCompleteTextView).SetFont (Font.RobotoLight);
PasswordEditText = FindViewById<EditText> (Resource.Id.PasswordEditText).SetFont (Font.RobotoLight);
PasswordToggleButton = FindViewById<Button> (Resource.Id.PasswordToggleButton).SetFont (Font.Roboto);
LoginButton = FindViewById<Button> (Resource.Id.LoginButton).SetFont (Font.Roboto);
LegalTextView = FindViewById<TextView> (Resource.Id.LegalTextView).SetFont (Font.RobotoLight);
GoogleLoginButton = FindViewById<Button> (Resource.Id.GoogleLoginButton).SetFont (Font.Roboto);
}
protected override bool StartAuthActivity ()
{
var authManager = ServiceContainer.Resolve<AuthManager> ();
if (authManager.IsAuthenticated) {
// Try to avoid flickering of buttons during activity transition by
// faking that we're still authenticating
IsAuthenticating = true;
var intent = new Intent (this, typeof (MainDrawerActivity));
intent.AddFlags (ActivityFlags.ClearTop);
StartActivity (intent);
Finish ();
return true;
}
return false;
}
private ArrayAdapter<string> MakeEmailsAdapter ()
{
var am = AccountManager.Get (this);
var emails = am.GetAccounts ()
.Select ((a) => a.Name)
.Where ((a) => a.Contains ("@"))
.Distinct ()
.ToList ();
return new ArrayAdapter<string> (this, Android.Resource.Layout.SelectDialogItem, emails);
}
void ViewTreeObserver.IOnGlobalLayoutListener.OnGlobalLayout ()
{
// Move scroll and let the logo visible.
var position = new int[2];
bigLogo.GetLocationInWindow (position);
if (topLogoPosition == 0 && position[1] != 0) {
topLogoPosition = position[1] + Convert.ToInt32 (bigLogo.Height * 0.2);
}
ScrollView.SmoothScrollTo (0, topLogoPosition);
}
protected override void OnCreateActivity (Bundle state)
{
base.OnCreateActivity (state);
SetContentView (Resource.Layout.LoginActivity);
FindViews ();
ScrollView.ViewTreeObserver.AddOnGlobalLayoutListener (this);
LoginButton.Click += OnLoginButtonClick;
GoogleLoginButton.Click += OnGoogleLoginButtonClick;
EmailEditText.Adapter = MakeEmailsAdapter ();
EmailEditText.Threshold = 1;
EmailEditText.TextChanged += OnEmailEditTextTextChanged;
PasswordEditText.TextChanged += OnPasswordEditTextTextChanged;
PasswordToggleButton.Click += OnPasswordToggleButtonClick;
SwitchModeButton.Click += OnModeToggleButtonClick;
hasGoogleAccounts = GoogleAccounts.Count > 0;
GoogleLoginButton.Visibility = hasGoogleAccounts ? ViewStates.Visible : ViewStates.Gone;
if (state != null) {
showPassword = state.GetBoolean (ExtraShowPassword);
}
SyncContent ();
SyncPasswordVisibility ();
}
protected override void OnSaveInstanceState (Bundle outState)
{
base.OnSaveInstanceState (outState);
outState.PutBoolean (ExtraShowPassword, showPassword);
}
protected override void OnStart ()
{
base.OnStart ();
SyncCurrentScreen ();
}
private void SyncCurrentScreen()
{
// Just to make sure we don't double count screens should this funciton be called multiple times in a row
var currentScreen = CurrentMode;
if (lastScreen == currentScreen) {
return;
}
switch (currentScreen) {
case Mode.Login:
ServiceContainer.Resolve<ITracker> ().CurrentScreen = "Login";
break;
default:
ServiceContainer.Resolve<ITracker> ().CurrentScreen = "Signup";
break;
}
lastScreen = currentScreen;
}
private void SyncContent ()
{
// Views not loaded yet/anymore?
if (LoginButton == null) {
return;
}
if (CurrentMode == Mode.Login) {
LoginButton.SetText (isAuthenticating ? Resource.String.LoginButtonProgressText : Resource.String.LoginButtonText);
LegalTextView.Visibility = ViewStates.Gone;
GoogleLoginButton.SetText (Resource.String.LoginGoogleButtonText);
SwitchModeButton.SetText (Resource.String.SignupViewButtonText);
} else {
LoginButton.SetText (isAuthenticating ? Resource.String.LoginButtonSignupProgressText : Resource.String.LoginSignupButtonText);
LegalTextView.SetText (FormattedLegalText, TextView.BufferType.Spannable);
LegalTextView.MovementMethod = Android.Text.Method.LinkMovementMethod.Instance;
LegalTextView.Visibility = ViewStates.Visible;
GoogleLoginButton.SetText (Resource.String.LoginSignupGoogleButtonText);
SwitchModeButton.SetText (Resource.String.LoginViewButtonText);
}
EmailEditText.Enabled = !isAuthenticating;
PasswordEditText.Enabled = !isAuthenticating;
GoogleLoginButton.Enabled = !isAuthenticating;
SyncLoginButton ();
}
private void SyncLoginButton ()
{
var enabled = !isAuthenticating;
if (CurrentMode == Mode.Signup) {
if (String.IsNullOrWhiteSpace (EmailEditText.Text) || !EmailEditText.Text.Contains ('@')) {
enabled = false;
} else if (String.IsNullOrWhiteSpace (PasswordEditText.Text) || PasswordEditText.Text.Length < 6) {
enabled = false;
}
}
LoginButton.Enabled = enabled;
}
private void SyncPasswordVisibility ()
{
if (PasswordEditText.Text.Length == 0) {
// Reset buttons and mask
PasswordToggleButton.Visibility = ViewStates.Gone;
showPassword = false;
} else if (showPassword) {
PasswordToggleButton.SetText (Resource.String.LoginHideButtonText);
PasswordToggleButton.Visibility = ViewStates.Visible;
} else {
PasswordToggleButton.SetText (Resource.String.LoginShowButtonText);
PasswordToggleButton.Visibility = ViewStates.Visible;
}
int selectionStart = PasswordEditText.SelectionStart;
int selectionEnd = PasswordEditText.SelectionEnd;
var passwordInputType = PasswordEditText.InputType;
if (showPassword) {
passwordInputType = (passwordInputType & ~InputTypes.TextVariationPassword) | InputTypes.TextVariationVisiblePassword;
} else {
passwordInputType = (passwordInputType & ~InputTypes.TextVariationVisiblePassword) | InputTypes.TextVariationPassword;
}
if (PasswordEditText.InputType != passwordInputType) {
PasswordEditText.InputType = passwordInputType;
// Need to reset font after changing input type
PasswordEditText.SetFont (Font.RobotoLight);
// Restore cursor position:
PasswordEditText.SetSelection (selectionStart, selectionEnd);
}
}
private void OnModeToggleButtonClick (object sender, EventArgs e)
{
CurrentMode = CurrentMode == Mode.Login ? Mode.Signup : Mode.Login;
SyncContent ();
}
private void OnEmailEditTextTextChanged (object sender, TextChangedEventArgs e)
{
SyncLoginButton ();
}
private void OnPasswordEditTextTextChanged (object sender, TextChangedEventArgs e)
{
SyncPasswordVisibility ();
SyncLoginButton ();
}
private void OnPasswordToggleButtonClick (object sender, EventArgs e)
{
showPassword = !showPassword;
SyncPasswordVisibility ();
}
private void OnLoginButtonClick (object sender, EventArgs e)
{
if (CurrentMode == Mode.Login) {
TryLoginPassword ();
} else {
TrySignupPassword ();
}
}
private async void TryLoginPassword ()
{
IsAuthenticating = true;
var authManager = ServiceContainer.Resolve<AuthManager> ();
AuthResult authRes;
try {
authRes = await authManager.AuthenticateAsync (EmailEditText.Text, PasswordEditText.Text);
} catch (InvalidOperationException ex) {
var log = ServiceContainer.Resolve<ILogger> ();
log.Info (LogTag, ex, "Failed to authenticate user with password.");
return;
} finally {
IsAuthenticating = false;
}
if (authRes != AuthResult.Success) {
if (authRes == AuthResult.InvalidCredentials) {
PasswordEditText.Text = String.Empty;
}
PasswordEditText.RequestFocus ();
ShowAuthError (EmailEditText.Text, authRes, Mode.Login);
} else {
// Start the initial sync for the user
ServiceContainer.Resolve<ISyncManager> ().Run (SyncMode.Full);
}
StartAuthActivity ();
}
private async void TrySignupPassword ()
{
IsAuthenticating = true;
var authManager = ServiceContainer.Resolve<AuthManager> ();
AuthResult authRes;
try {
authRes = await authManager.SignupAsync (EmailEditText.Text, PasswordEditText.Text);
} catch (InvalidOperationException ex) {
var log = ServiceContainer.Resolve<ILogger> ();
log.Info (LogTag, ex, "Failed to signup user with password.");
return;
} finally {
IsAuthenticating = false;
}
if (authRes != AuthResult.Success) {
EmailEditText.RequestFocus ();
ShowAuthError (EmailEditText.Text, authRes, Mode.Signup);
} else {
// Start the initial sync for the user
ServiceContainer.Resolve<ISyncManager> ().Run (SyncMode.Full);
}
StartAuthActivity ();
}
private void OnGoogleLoginButtonClick (object sender, EventArgs e)
{
var accounts = GoogleAccounts;
if (accounts.Count == 1) {
GoogleAuthFragment.Start (FragmentManager, accounts [0]);
} else if (accounts.Count > 1) {
var dia = new GoogleAccountSelectionDialogFragment ();
dia.Show (FragmentManager, "accounts_dialog");
}
}
private List<string> GoogleAccounts
{
get {
var am = AccountManager.Get (this);
return am.GetAccounts ()
.Where ((a) => a.Type == GoogleAuthUtil.GoogleAccountType)
.Select ((a) => a.Name)
.Distinct ()
.ToList ();
}
}
private bool IsAuthenticating
{
set {
if (isAuthenticating == value) {
return;
}
isAuthenticating = value;
SyncContent ();
}
}
private ISpannable FormattedLegalText
{
get {
if (formattedLegalText == null) {
var template = Resources.GetText (Resource.String.LoginSignupLegalText);
var arg0 = Resources.GetText (Resource.String.LoginSignupLegalTermsText);
var arg1 = Resources.GetText (Resource.String.LoginSignupLegalPrivacyText);
var arg0idx = String.Format (template, "{0}", arg1).IndexOf ("{0}", StringComparison.Ordinal);
var arg1idx = String.Format (template, arg0, "{1}").IndexOf ("{1}", StringComparison.Ordinal);
var s = formattedLegalText = new SpannableString (String.Format (template, arg0, arg1));
var mode = SpanTypes.InclusiveExclusive;
s.SetSpan (
new TogglURLSPan (Phoebe.Build.TermsOfServiceUrl.ToString ()),
arg0idx,
arg0idx + arg0.Length,
mode
);
s.SetSpan (
new TogglURLSPan (Phoebe.Build.PrivacyPolicyUrl.ToString ()),
arg1idx,
arg1idx + arg1.Length,
mode
);
}
return formattedLegalText;
}
}
private Mode CurrentMode;
private enum Mode {
Login,
Signup
}
private void ShowAuthError (string email, AuthResult res, Mode mode, bool googleAuth=false)
{
DialogFragment dia = null;
switch (res) {
case AuthResult.InvalidCredentials:
if (mode == Mode.Login && !googleAuth) {
dia = new InvalidCredentialsDialogFragment ();
} else if (mode == Mode.Signup && !googleAuth) {
dia = new SignupFailedDialogFragment ();
} else if (mode == Mode.Login && googleAuth) {
dia = new NoAccountDialogFragment ();
} else if (mode == Mode.Signup && googleAuth) {
dia = new SignupFailedDialogFragment ();
}
break;
case AuthResult.NoDefaultWorkspace:
dia = new NoWorkspaceDialogFragment (email);
break;
case AuthResult.NetworkError:
dia = new NetworkErrorDialogFragment ();
break;
default:
dia = new SystemErrorDialogFragment ();
break;
}
if (dia != null) {
dia.Show (FragmentManager, "auth_result_dialog");
}
}
public class GoogleAuthFragment : Fragment
{
private static readonly int GoogleAuthRequestCode = 1;
private static readonly string GoogleOAuthScope =
"oauth2:https://www.googleapis.com/auth/userinfo.profile " +
"https://www.googleapis.com/auth/userinfo.email";
private static readonly string EmailArgument = "com.toggl.timer.email";
public static void Start (FragmentManager mgr, string email)
{
// Find old fragment to replace
var frag = mgr.FindFragmentByTag ("google_auth");
if (frag != null) {
var authFrag = frag as GoogleAuthFragment;
if (authFrag != null && authFrag.IsAuthenticating) {
// Authentication going on still, do nothing.
return;
}
}
var tx = mgr.BeginTransaction ();
if (frag != null) {
tx.Remove (frag);
}
tx.Add (new GoogleAuthFragment (email), "google_auth");
tx.Commit ();
}
public GoogleAuthFragment (string email)
{
var args = new Bundle ();
args.PutString (EmailArgument, email);
Arguments = args;
}
public GoogleAuthFragment ()
{
}
public GoogleAuthFragment (IntPtr javaRef, Android.Runtime.JniHandleOwnership transfer) : base (javaRef, transfer)
{
}
public override void OnCreate (Bundle savedInstanceState)
{
base.OnCreate (savedInstanceState);
RetainInstance = true;
StartAuth ();
}
public override void OnActivityCreated (Bundle savedInstanceState)
{
base.OnActivityCreated (savedInstanceState);
// Restore IsAuthenticating value
var activity = Activity as LoginActivity;
if (activity != null) {
activity.IsAuthenticating = IsAuthenticating;
}
}
public override void OnActivityResult (int requestCode, int resultCode, Intent data)
{
base.OnActivityResult (requestCode, resultCode, data);
if (requestCode == GoogleAuthRequestCode) {
if (resultCode == (int)Result.Ok) {
StartAuth ();
}
}
}
private async void StartAuth ()
{
if (IsAuthenticating) {
return;
}
IsAuthenticating = true;
LoginActivity activity;
try {
var log = ServiceContainer.Resolve<ILogger> ();
var authManager = ServiceContainer.Resolve<AuthManager> ();
var ctx = Activity;
// No point in trying to reauth when old authentication is still running.
if (authManager.IsAuthenticating) {
return;
}
// Workaround for Android linker bug which forgets to register JNI types
Java.Interop.TypeManager.RegisterType ("com/google/android/gms/auth/GoogleAuthException", typeof (GoogleAuthException));
Java.Interop.TypeManager.RegisterType ("com/google/android/gms/auth/GooglePlayServicesAvailabilityException", typeof (GooglePlayServicesAvailabilityException));
Java.Interop.TypeManager.RegisterType ("com/google/android/gms/auth/UserRecoverableAuthException", typeof (UserRecoverableAuthException));
Java.Interop.TypeManager.RegisterType ("com/google/android/gms/auth/UserRecoverableNotifiedException", typeof (UserRecoverableNotifiedException));
String token = null;
try {
token = await Task.Factory.StartNew (() => GoogleAuthUtil.GetToken (ctx, Email, GoogleOAuthScope));
} catch (GooglePlayServicesAvailabilityException exc) {
var dia = GooglePlayServicesUtil.GetErrorDialog (
exc.ConnectionStatusCode, ctx, GoogleAuthRequestCode);
dia.Show ();
} catch (UserRecoverableAuthException exc) {
StartActivityForResult (exc.Intent, GoogleAuthRequestCode);
} catch (Java.IO.IOException exc) {
// Connectivity error.. nothing to do really?
log.Info (LogTag, exc, "Failed to login with Google due to network issues.");
} catch (Exception exc) {
log.Error (LogTag, exc, "Failed to get access token for '{0}'.", Email);
}
// Failed to get token
if (token == null) {
return;
}
try {
activity = Activity as LoginActivity;
if (activity != null && activity.CurrentMode == Mode.Signup) {
// Signup with Google
var authRes = await authManager.SignupWithGoogleAsync (token);
if (authRes != AuthResult.Success) {
ClearGoogleToken (ctx, token);
activity.ShowAuthError (Email, authRes, Mode.Signup, googleAuth: true);
}
} else {
// Authenticate client
var authRes = await authManager.AuthenticateWithGoogleAsync (token);
if (authRes != AuthResult.Success) {
ClearGoogleToken (ctx, token);
activity.ShowAuthError (Email, authRes, Mode.Login, googleAuth: true);
}
}
} catch (InvalidOperationException ex) {
log.Info (LogTag, ex, "Failed to authenticate user with Google login.");
}
} finally {
IsAuthenticating = false;
}
// Clean up self:
if (Activity != null) {
FragmentManager.BeginTransaction ()
.Remove (this)
.Commit ();
}
// Try to make the activity recheck auth status
activity = Activity as LoginActivity;
if (activity != null) {
activity.StartAuthActivity ();
}
}
private void ClearGoogleToken (Context ctx, string token)
{
var log = ServiceContainer.Resolve<ILogger> ();
ThreadPool.QueueUserWorkItem (delegate {
try {
GoogleAuthUtil.ClearToken (ctx, token);
} catch (Exception ex) {
log.Warning (LogTag, ex, "Failed to authenticate user with Google login.");
}
});
}
private string Email
{
get {
return Arguments != null ? Arguments.GetString (EmailArgument) : null;
}
}
private bool isAuthenticating;
private bool IsAuthenticating
{
get { return isAuthenticating; }
set {
isAuthenticating = value;
var activity = Activity as LoginActivity;
if (activity != null) {
activity.IsAuthenticating = isAuthenticating;
}
}
}
}
public class GoogleAccountSelectionDialogFragment : DialogFragment
{
private ArrayAdapter<string> accountsAdapter;
public override Dialog OnCreateDialog (Bundle savedInstanceState)
{
accountsAdapter = MakeAccountsAdapter ();
return new AlertDialog.Builder (Activity)
.SetTitle (Resource.String.LoginAccountsDialogTitle)
.SetAdapter (MakeAccountsAdapter (), OnAccountSelected)
.SetNegativeButton (Resource.String.LoginAccountsDialogCancelButton, OnCancelButtonClicked)
.Create ();
}
private void OnAccountSelected (object sender, DialogClickEventArgs args)
{
var email = accountsAdapter.GetItem (args.Which);
GoogleAuthFragment.Start (FragmentManager, email);
}
private void OnCancelButtonClicked (object sender, DialogClickEventArgs args)
{
}
private ArrayAdapter<string> MakeAccountsAdapter ()
{
var am = AccountManager.Get (Activity);
var emails = am.GetAccounts ()
.Where ((a) => a.Type == GoogleAuthUtil.GoogleAccountType)
.Select ((a) => a.Name)
.Distinct ()
.ToList ();
return new ArrayAdapter<string> (Activity, Android.Resource.Layout.SimpleListItem1, emails);
}
}
public class InvalidCredentialsDialogFragment : DialogFragment
{
public override Dialog OnCreateDialog (Bundle savedInstanceState)
{
return new AlertDialog.Builder (Activity)
.SetTitle (Resource.String.LoginInvalidCredentialsDialogTitle)
.SetMessage (Resource.String.LoginInvalidCredentialsDialogText)
.SetPositiveButton (Resource.String.LoginInvalidCredentialsDialogOk, OnOkButtonClicked)
.Create ();
}
private void OnOkButtonClicked (object sender, DialogClickEventArgs args)
{
}
}
public class SignupFailedDialogFragment : DialogFragment
{
public override Dialog OnCreateDialog (Bundle savedInstanceState)
{
return new AlertDialog.Builder (Activity)
.SetTitle (Resource.String.LoginSignupFailedDialogTitle)
.SetMessage (Resource.String.LoginSignupFailedDialogText)
.SetPositiveButton (Resource.String.LoginSignupFailedDialogOk, OnOkButtonClicked)
.Create ();
}
private void OnOkButtonClicked (object sender, DialogClickEventArgs args)
{
}
}
public class NoAccountDialogFragment : DialogFragment
{
public override Dialog OnCreateDialog (Bundle savedInstanceState)
{
return new AlertDialog.Builder (Activity)
.SetTitle (Resource.String.LoginNoAccountDialogTitle)
.SetMessage (Resource.String.LoginNoAccountDialogText)
.SetPositiveButton (Resource.String.LoginNoAccountDialogOk, OnOkButtonClicked)
.Create ();
}
private void OnOkButtonClicked (object sender, DialogClickEventArgs args)
{
}
}
public class NetworkErrorDialogFragment : DialogFragment
{
public override Dialog OnCreateDialog (Bundle savedInstanceState)
{
return new AlertDialog.Builder (Activity)
.SetTitle (Resource.String.LoginNetworkErrorDialogTitle)
.SetMessage (Resource.String.LoginNetworkErrorDialogText)
.SetPositiveButton (Resource.String.LoginNetworkErrorDialogOk, OnOkButtonClicked)
.Create ();
}
private void OnOkButtonClicked (object sender, DialogClickEventArgs args)
{
}
}
public class SystemErrorDialogFragment : DialogFragment
{
public override Dialog OnCreateDialog (Bundle savedInstanceState)
{
return new AlertDialog.Builder (Activity)
.SetTitle (Resource.String.LoginSystemErrorDialogTitle)
.SetMessage (Resource.String.LoginSystemErrorDialogText)
.SetPositiveButton (Resource.String.LoginSystemErrorDialogOk, OnOkButtonClicked)
.Create ();
}
private void OnOkButtonClicked (object sender, DialogClickEventArgs args)
{
}
}
public class NoWorkspaceDialogFragment : DialogFragment
{
private const string EmailKey = "com.toggl.timer.email";
public NoWorkspaceDialogFragment ()
{
}
public NoWorkspaceDialogFragment (string email)
{
var args = new Bundle();
args.PutString (EmailKey, email);
Arguments = args;
}
private string Email
{
get {
if (Arguments == null) {
return String.Empty;
}
return Arguments.GetString (EmailKey);
}
}
public override Dialog OnCreateDialog (Bundle savedInstanceState)
{
return new AlertDialog.Builder (Activity)
.SetTitle (Resource.String.LoginNoWorkspaceDialogTitle)
.SetMessage (Resource.String.LoginNoWorkspaceDialogText)
.SetPositiveButton (Resource.String.LoginNoWorkspaceDialogOk, OnOkButtonClicked)
.SetNegativeButton (Resource.String.LoginNoWorkspaceDialogCancel, OnCancelButtonClicked)
.Create ();
}
private void OnOkButtonClicked (object sender, DialogClickEventArgs args)
{
var intent = new Intent (Intent.ActionSend);
intent.SetType ("message/rfc822");
intent.PutExtra (Intent.ExtraEmail, new[] { Resources.GetString (Resource.String.LoginNoWorkspaceDialogEmail) });
intent.PutExtra (Intent.ExtraSubject, Resources.GetString (Resource.String.LoginNoWorkspaceDialogSubject));
intent.PutExtra (Intent.ExtraText, String.Format (Resources.GetString (Resource.String.LoginNoWorkspaceDialogBody), Email));
StartActivity (Intent.CreateChooser (intent, (string)null));
}
private void OnCancelButtonClicked (object sender, DialogClickEventArgs args)
{
}
}
private class TogglURLSPan : URLSpan
{
public TogglURLSPan (String url) : base (url)
{
}
public override void UpdateDrawState (TextPaint ds)
{
base.UpdateDrawState (ds);
ds.UnderlineText = false;
ds.SetTypeface (Android.Graphics.Typeface.DefaultBold);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Content.Shared.Body.Events;
using Content.Shared.Body.Part;
using Robust.Shared.GameObjects;
using Robust.Shared.GameStates;
using Robust.Shared.IoC;
using Robust.Shared.Map;
using Robust.Shared.Serialization;
using Robust.Shared.Serialization.Manager.Attributes;
using Robust.Shared.Utility;
using Robust.Shared.ViewVariables;
namespace Content.Shared.Body.Components
{
[NetworkedComponent()]
public abstract class SharedBodyPartComponent : Component
{
[Dependency] private readonly IEntityManager _entMan = default!;
private SharedBodyComponent? _body;
// TODO BODY Remove
[DataField("mechanisms")]
private readonly List<string> _mechanismIds = new();
public IReadOnlyList<string> MechanismIds => _mechanismIds;
[ViewVariables]
private readonly HashSet<MechanismComponent> _mechanisms = new();
[ViewVariables]
public SharedBodyComponent? Body
{
get => _body;
set
{
if (_body == value)
{
return;
}
var old = _body;
_body = value;
if (old != null)
{
RemovedFromBody(old);
}
if (value != null)
{
AddedToBody(value);
}
}
}
/// <summary>
/// <see cref="BodyPartType"/> that this <see cref="IBodyPart"/> is considered
/// to be.
/// For example, <see cref="BodyPartType.Arm"/>.
/// </summary>
[ViewVariables]
[DataField("partType")]
public BodyPartType PartType { get; private set; } = BodyPartType.Other;
/// <summary>
/// Determines how many mechanisms can be fit inside this
/// <see cref="SharedBodyPartComponent"/>.
/// </summary>
[ViewVariables] [DataField("size")] public int Size { get; private set; } = 1;
[ViewVariables] public int SizeUsed { get; private set; }
// TODO BODY size used
// TODO BODY surgerydata
/// <summary>
/// What types of BodyParts this <see cref="SharedBodyPartComponent"/> can easily attach to.
/// For the most part, most limbs aren't universal and require extra work to
/// attach between types.
/// </summary>
[ViewVariables]
[DataField("compatibility")]
public BodyPartCompatibility Compatibility = BodyPartCompatibility.Universal;
// TODO BODY Mechanisms occupying different parts at the body level
[ViewVariables]
public IReadOnlyCollection<MechanismComponent> Mechanisms => _mechanisms;
// TODO BODY Replace with a simulation of organs
/// <summary>
/// Whether or not the owning <see cref="Body"/> will die if all
/// <see cref="SharedBodyPartComponent"/>s of this type are removed from it.
/// </summary>
[ViewVariables]
[DataField("vital")]
public bool IsVital = false;
[ViewVariables]
[DataField("symmetry")]
public BodyPartSymmetry Symmetry = BodyPartSymmetry.None;
protected virtual void OnAddMechanism(MechanismComponent mechanism)
{
var prototypeId = _entMan.GetComponent<MetaDataComponent>(mechanism.Owner).EntityPrototype!.ID;
if (!_mechanismIds.Contains(prototypeId))
{
_mechanismIds.Add(prototypeId);
}
mechanism.Part = this;
SizeUsed += mechanism.Size;
Dirty();
}
protected virtual void OnRemoveMechanism(MechanismComponent mechanism)
{
_mechanismIds.Remove(_entMan.GetComponent<MetaDataComponent>(mechanism.Owner).EntityPrototype!.ID);
mechanism.Part = null;
SizeUsed -= mechanism.Size;
Dirty();
}
public override ComponentState GetComponentState()
{
var mechanismIds = new EntityUid[_mechanisms.Count];
var i = 0;
foreach (var mechanism in _mechanisms)
{
mechanismIds[i] = mechanism.Owner;
i++;
}
return new BodyPartComponentState(mechanismIds);
}
public override void HandleComponentState(ComponentState? curState, ComponentState? nextState)
{
base.HandleComponentState(curState, nextState);
if (curState is not BodyPartComponentState state)
{
return;
}
var newMechanisms = state.Mechanisms();
foreach (var mechanism in _mechanisms.ToArray())
{
if (!newMechanisms.Contains(mechanism))
{
RemoveMechanism(mechanism);
}
}
foreach (var mechanism in newMechanisms)
{
if (!_mechanisms.Contains(mechanism))
{
TryAddMechanism(mechanism, true);
}
}
}
public virtual bool CanAddMechanism(MechanismComponent mechanism)
{
return SizeUsed + mechanism.Size <= Size;
}
/// <summary>
/// Tries to add a <see cref="MechanismComponent"/> to this part.
/// </summary>
/// <param name="mechanism">The mechanism to add.</param>
/// <param name="force">
/// Whether or not to check if the mechanism is compatible.
/// Passing true does not guarantee it to be added, for example if
/// it was already added before.
/// </param>
/// <returns>true if added, false otherwise even if it was already added.</returns>
public bool TryAddMechanism(MechanismComponent mechanism, bool force = false)
{
DebugTools.AssertNotNull(mechanism);
if (!force && !CanAddMechanism(mechanism))
{
return false;
}
if (!_mechanisms.Add(mechanism))
{
return false;
}
OnAddMechanism(mechanism);
return true;
}
/// <summary>
/// Tries to remove the given <see cref="mechanism"/> from this part.
/// </summary>
/// <param name="mechanism">The mechanism to remove.</param>
/// <returns>True if it was removed, false otherwise.</returns>
public bool RemoveMechanism(MechanismComponent mechanism)
{
DebugTools.AssertNotNull(mechanism);
if (!_mechanisms.Remove(mechanism))
{
return false;
}
OnRemoveMechanism(mechanism);
return true;
}
/// <summary>
/// Tries to remove the given <see cref="mechanism"/> from this
/// part and drops it at the specified coordinates.
/// </summary>
/// <param name="mechanism">The mechanism to remove.</param>
/// <param name="coordinates">The coordinates to drop it at.</param>
/// <returns>True if it was removed, false otherwise.</returns>
public bool RemoveMechanism(MechanismComponent mechanism, EntityCoordinates coordinates)
{
if (RemoveMechanism(mechanism))
{
_entMan.GetComponent<TransformComponent>(mechanism.Owner).Coordinates = coordinates;
return true;
}
return false;
}
/// <summary>
/// Tries to destroy the given <see cref="MechanismComponent"/> from
/// this part.
/// The mechanism won't be deleted if it is not in this body part.
/// </summary>
/// <returns>
/// True if the mechanism was in this body part and destroyed,
/// false otherwise.
/// </returns>
public bool DeleteMechanism(MechanismComponent mechanism)
{
DebugTools.AssertNotNull(mechanism);
if (!RemoveMechanism(mechanism))
{
return false;
}
_entMan.DeleteEntity(mechanism.Owner);
return true;
}
private void AddedToBody(SharedBodyComponent body)
{
_entMan.GetComponent<TransformComponent>(Owner).LocalRotation = 0;
_entMan.GetComponent<TransformComponent>(Owner).AttachParent(body.Owner);
OnAddedToBody(body);
foreach (var mechanism in _mechanisms)
{
_entMan.EventBus.RaiseLocalEvent(mechanism.Owner, new AddedToBodyEvent(body));
}
}
private void RemovedFromBody(SharedBodyComponent old)
{
if (!_entMan.GetComponent<TransformComponent>(Owner).Deleted)
{
_entMan.GetComponent<TransformComponent>(Owner).AttachToGridOrMap();
}
OnRemovedFromBody(old);
foreach (var mechanism in _mechanisms)
{
_entMan.EventBus.RaiseLocalEvent(mechanism.Owner, new RemovedFromBodyEvent(old));
}
}
protected virtual void OnAddedToBody(SharedBodyComponent body) { }
protected virtual void OnRemovedFromBody(SharedBodyComponent old) { }
/// <summary>
/// Gibs the body part.
/// </summary>
public virtual void Gib()
{
foreach (var mechanism in _mechanisms)
{
RemoveMechanism(mechanism);
}
}
}
[Serializable, NetSerializable]
public sealed class BodyPartComponentState : ComponentState
{
[NonSerialized] private List<MechanismComponent>? _mechanisms;
public readonly EntityUid[] MechanismIds;
public BodyPartComponentState(EntityUid[] mechanismIds)
{
MechanismIds = mechanismIds;
}
public List<MechanismComponent> Mechanisms(IEntityManager? entityManager = null)
{
if (_mechanisms != null)
{
return _mechanisms;
}
IoCManager.Resolve(ref entityManager);
var mechanisms = new List<MechanismComponent>(MechanismIds.Length);
foreach (var id in MechanismIds)
{
if (!entityManager.EntityExists(id))
{
continue;
}
if (!entityManager.TryGetComponent(id, out MechanismComponent? mechanism))
{
continue;
}
mechanisms.Add(mechanism);
}
return _mechanisms = mechanisms;
}
}
}
| |
// 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 CompareUnorderedDouble()
{
var test = new SimpleBinaryOpTest__CompareUnorderedDouble();
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 works
test.RunLclFldScenario();
// Validates passing an instance member works
test.RunFldScenario();
}
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 SimpleBinaryOpTest__CompareUnorderedDouble
{
private const int VectorSize = 16;
private const int Op1ElementCount = VectorSize / sizeof(Double);
private const int Op2ElementCount = VectorSize / sizeof(Double);
private const int RetElementCount = VectorSize / sizeof(Double);
private static Double[] _data1 = new Double[Op1ElementCount];
private static Double[] _data2 = new Double[Op2ElementCount];
private static Vector128<Double> _clsVar1;
private static Vector128<Double> _clsVar2;
private Vector128<Double> _fld1;
private Vector128<Double> _fld2;
private SimpleBinaryOpTest__DataTable<Double, Double, Double> _dataTable;
static SimpleBinaryOpTest__CompareUnorderedDouble()
{
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (double)(random.NextDouble()); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar1), ref Unsafe.As<Double, byte>(ref _data1[0]), VectorSize);
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (double)(random.NextDouble()); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar2), ref Unsafe.As<Double, byte>(ref _data2[0]), VectorSize);
}
public SimpleBinaryOpTest__CompareUnorderedDouble()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (double)(random.NextDouble()); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), VectorSize);
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (double)(random.NextDouble()); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), VectorSize);
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (double)(random.NextDouble()); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (double)(random.NextDouble()); }
_dataTable = new SimpleBinaryOpTest__DataTable<Double, Double, Double>(_data1, _data2, new Double[RetElementCount], VectorSize);
}
public bool IsSupported => Sse2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Sse2.CompareUnordered(
Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
var result = Sse2.CompareUnordered(
Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
var result = Sse2.CompareUnordered(
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.CompareUnordered), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.CompareUnordered), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) })
.Invoke(null, new object[] {
Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.CompareUnordered), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
var result = Sse2.CompareUnordered(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
var left = Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr);
var right = Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr);
var result = Sse2.CompareUnordered(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
var left = Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr));
var right = Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr));
var result = Sse2.CompareUnordered(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
var left = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr));
var right = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr));
var result = Sse2.CompareUnordered(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclFldScenario()
{
var test = new SimpleBinaryOpTest__CompareUnorderedDouble();
var result = Sse2.CompareUnordered(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunFldScenario()
{
var result = Sse2.CompareUnordered(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunUnsupportedScenario()
{
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector128<Double> left, Vector128<Double> right, void* result, [CallerMemberName] string method = "")
{
Double[] inArray1 = new Double[Op1ElementCount];
Double[] inArray2 = new Double[Op2ElementCount];
Double[] outArray = new Double[RetElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left);
Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "")
{
Double[] inArray1 = new Double[Op1ElementCount];
Double[] inArray2 = new Double[Op2ElementCount];
Double[] outArray = new Double[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Double[] left, Double[] right, Double[] result, [CallerMemberName] string method = "")
{
if (BitConverter.DoubleToInt64Bits(result[0]) != ((double.IsNaN(left[0]) || double.IsNaN(right[0])) ? -1 : 0))
{
Succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (BitConverter.DoubleToInt64Bits(result[i]) != ((double.IsNaN(left[i]) || double.IsNaN(right[i])) ? -1 : 0))
{
Succeeded = false;
break;
}
}
}
if (!Succeeded)
{
Console.WriteLine($"{nameof(Sse2)}.{nameof(Sse2.CompareUnordered)}<Double>(Vector128<Double>, Vector128<Double>): {method} failed:");
Console.WriteLine($" left: ({string.Join(", ", left)})");
Console.WriteLine($" right: ({string.Join(", ", right)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Entities.ViewModels.Account;
using Microsoft.AspNetCore.Identity;
using RAMdomizer.Entities.Models;
using Microsoft.AspNetCore.WebUtilities;
using System.Text;
using RAMdomizer.Services;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Options;
using Entities.ViewModels.Manage;
using System.Net.Http;
using Newtonsoft.Json;
using RAMdomizer.Entities.ViewModels;
using System;
using RAMdomizer.ViewModels.Account;
using RAMdomizer.Core.Enumerations;
using RAMdomizer.Entities.ViewModels.Account;
using System.IdentityModel.Tokens.Jwt;
using Microsoft.IdentityModel.Tokens;
using System.Security.Claims;
using Microsoft.AspNetCore.Authorization;
namespace RAMdomizer.API.Controllers
{
[ApiVersion("1.0")]
[Route("~/api/v{version:apiVersion}/accounts")]
public class AccountsController : Controller
{
private readonly UserManager<ApplicationUser> _userManager;
private readonly SignInManager<ApplicationUser> _signInManager;
private readonly SparkPostService SparkPostService;
private readonly AppSetting _appSetting;
public AccountsController(
UserManager<ApplicationUser> userManager,
SignInManager<ApplicationUser> signInManager,
SparkPostService _SparkPostService,
IOptions<AppSetting> appSetting)
{
_userManager = userManager;
_signInManager = signInManager;
SparkPostService = _SparkPostService;
_appSetting = appSetting.Value;
}
[HttpPost("register"), MapToApiVersion("1.0")]
public async Task<IActionResult> Register([FromBody] RegisterViewModel model)
{
if (ModelState.IsValid)
{
var secret = _appSetting.GoogleRecaptchaSecretKey;
var recaptchaToken = model.RecaptchaToken;
var client = new HttpClient();
string postResponse = await client.GetStringAsync(
string.Format("https://www.google.com/recaptcha/api/siteverify?secret={0}&response={1}",
secret,
recaptchaToken)
);
var captchaResponse = JsonConvert.DeserializeObject<RecaptchaResponse>(postResponse);
if (captchaResponse.Success)
{
var user = new ApplicationUser
{
UserName = model.Email,
Name = model.Name,
Email = model.Email,
RegistrationDate = DateTime.Now.ToUniversalTime(),
RegistrationSource = (int)RegistrationSource.RAMdomizer
};
var result = await _userManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
// For more information on how to enable account confirmation and password reset please visit https://go.microsoft.com/fwlink/?LinkID=532713
// Send an email with this link
var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
byte[] tokenGeneratedBytes = Encoding.UTF8.GetBytes(code);
var codeEncoded = WebEncoders.Base64UrlEncode(tokenGeneratedBytes);
var callbackUrl = Url.Action(nameof(ConfirmEmail), "Accounts", new { userId = user.Id, code = codeEncoded }, protocol: HttpContext.Request.Scheme);
//Send Email
await SparkPostService.RegisterUser(model.Email, callbackUrl);
return UserInfo(user, false);
}
// If we got this far, something failed
IEnumerable<string> errorList = AddErrors(result.Errors);
return StatusCode(500, new { errors = errorList });
}
// If we got this far, something failed in the recaptcha
var IdentityErrors = new List<IdentityError>();
IdentityErrors.Add(new IdentityError { Description = "The recaptcha is not valid." });
IEnumerable<string> recapchaterrorList = AddErrors(IdentityErrors);
return StatusCode(500, new { errors = recapchaterrorList });
}
return BadRequest(ModelState);
}
[HttpPost("login"), MapToApiVersion("1.0")]
public async Task<IActionResult> Login([FromBody] LoginViewModel model)
{
if (ModelState.IsValid)
{
var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, true, lockoutOnFailure: false);
if (result.Succeeded)
{
var user = await _userManager.FindByEmailAsync(model.Email);
return UserInfo(user, false);
}
// If we got this far, something failed
var IdentityErrors = new List<IdentityError>();
IdentityErrors.Add(new IdentityError { Description = "The username or password is invalid." });
IEnumerable<string> errorList = AddErrors(IdentityErrors);
return StatusCode(500, new { errors = errorList });
}
return BadRequest(ModelState);
}
[HttpPost("googlesignin"), MapToApiVersion("1.0")]
public async Task<IActionResult> GoogleSignIn([FromBody] GoogleSignInViewModel model)
{
if (ModelState.IsValid)
{
var client = new HttpClient();
string postResponse = await client.GetStringAsync(
string.Format("https://www.googleapis.com/oauth2/v3/tokeninfo?id_token={0}", model.IdToken)
);
var googleAuthResponse = JsonConvert.DeserializeObject<GoogleAuthResponse>(postResponse);
if (!string.IsNullOrEmpty(googleAuthResponse.email))
{
//try to sign in
var user = await _userManager.FindByEmailAsync(googleAuthResponse.email);
if (user != null)
{
await _signInManager.SignInAsync(user, true, null);
return UserInfo(user, true);
}
else
{ //try to sign up
var userToCreate = new ApplicationUser
{
UserName = googleAuthResponse.email,
Name = googleAuthResponse.given_name,
Email = googleAuthResponse.email,
RegistrationDate = DateTime.Now.ToUniversalTime(),
RegistrationSource = (int)RegistrationSource.Google
};
var result = await _userManager.CreateAsync(userToCreate);
if (result.Succeeded)
{
// For more information on how to enable account confirmation and password reset please visit https://go.microsoft.com/fwlink/?LinkID=532713
// Send an email with this link
var code = await _userManager.GenerateEmailConfirmationTokenAsync(userToCreate);
byte[] tokenGeneratedBytes = Encoding.UTF8.GetBytes(code);
var codeEncoded = WebEncoders.Base64UrlEncode(tokenGeneratedBytes);
var callbackUrl = Url.Action(nameof(ConfirmEmail), "Accounts", new { userId = userToCreate.Id, code = codeEncoded }, protocol: HttpContext.Request.Scheme);
//Send Email
await SparkPostService.RegisterUser(userToCreate.Email, callbackUrl);
return UserInfo(userToCreate, true);
}
// If we got this far, something failed
IEnumerable<string> errorList = AddErrors(result.Errors);
return StatusCode(500, new { errors = errorList });
}
}
}
return BadRequest(ModelState);
}
[HttpPost("facebooksignin"), MapToApiVersion("1.0")]
public async Task<IActionResult> FacebookSignIn([FromBody] FacebookSignInViewModel model)
{
if (ModelState.IsValid)
{
var client = new HttpClient();
string postResponse = await client.GetStringAsync(
string.Format("https://graph.facebook.com/me?fields=first_name,name,email&access_token={0}", model.AccessToken)
);
var facebookAuthResponse = JsonConvert.DeserializeObject<FacebookAuthResponse>(postResponse);
if (!string.IsNullOrEmpty(facebookAuthResponse.email))
{
//try to sign in
var user = await _userManager.FindByEmailAsync(facebookAuthResponse.email);
if (user != null)
{
await _signInManager.SignInAsync(user, true, null);
return UserInfo(user, true);
}
else
{ //try to sign up
var userToCreate = new ApplicationUser
{
UserName = facebookAuthResponse.email,
Name = facebookAuthResponse.first_name,
Email = facebookAuthResponse.email,
RegistrationDate = DateTime.Now.ToUniversalTime(),
RegistrationSource = (int)RegistrationSource.Facebook
};
var result = await _userManager.CreateAsync(userToCreate);
if (result.Succeeded)
{
// For more information on how to enable account confirmation and password reset please visit https://go.microsoft.com/fwlink/?LinkID=532713
// Send an email with this link
var code = await _userManager.GenerateEmailConfirmationTokenAsync(userToCreate);
byte[] tokenGeneratedBytes = Encoding.UTF8.GetBytes(code);
var codeEncoded = WebEncoders.Base64UrlEncode(tokenGeneratedBytes);
var callbackUrl = Url.Action(nameof(ConfirmEmail), "Accounts", new { userId = userToCreate.Id, code = codeEncoded }, protocol: HttpContext.Request.Scheme);
//Send Email
await SparkPostService.RegisterUser(userToCreate.Email, callbackUrl);
return UserInfo(userToCreate, true);
}
// If we got this far, something failed
IEnumerable<string> errorList = AddErrors(result.Errors);
return StatusCode(500, new { errors = errorList });
}
}
}
return BadRequest(ModelState);
}
[HttpGet("confirmEmail"), MapToApiVersion("1.0")]
public async Task<IActionResult> ConfirmEmail(string userId, string code)
{
if (userId == null || code == null)
{
return View("Error");
}
var user = await _userManager.FindByIdAsync(userId);
if (user == null)
{
return View("Error");
}
var codeDecodedBytes = WebEncoders.Base64UrlDecode(code);
var codeDecoded = Encoding.UTF8.GetString(codeDecodedBytes);
var result = await _userManager.ConfirmEmailAsync(user, codeDecoded);
if (result.Succeeded)
{
await _signInManager.SignInAsync(user, true, null);
var token = this.GenerateSecurityToken(user);
var plan = Enum.GetName(typeof(PlanStatus), user.PlanId);
var redirectUrl = $"{_appSetting.WebAppConfirmedEmailUrl}?userId={user.Id}&name={user.Name}&userEmail={user.Email}&token={token}&plan={plan}";
return Redirect(redirectUrl);
}
return View("Error");
}
[HttpPost("logout"), MapToApiVersion("1.0")]
public async Task<IActionResult> Logout()
{
await _signInManager.SignOutAsync();
return NoContent();
}
[HttpPost("forgotpassword"), MapToApiVersion("1.0")]
public async Task<IActionResult> ForgotPassword([FromBody] ForgotPasswordViewModel model)
{
if (ModelState.IsValid)
{
var user = await _userManager.FindByEmailAsync(model.Email);
if (user == null)
{
// Don't reveal that the user does not exist or is not confirmed~send it to the ForgotPasswordConfirmation page.
return NoContent();
}
var code = await _userManager.GeneratePasswordResetTokenAsync(user);
byte[] tokenGeneratedBytes = Encoding.UTF8.GetBytes(code);
var codeEncoded = WebEncoders.Base64UrlEncode(tokenGeneratedBytes);
var callbackUrl = $"{_appSetting.ResetPasswordFromEmailUrl}?email={user.Email}&code={codeEncoded}";
// Send an email
await SparkPostService.ForgotPassword(model.Email, callbackUrl);
//Send it to the ForgotPasswordConfirmation page.
return NoContent();
}
return BadRequest(ModelState);
}
[HttpPut("resetpassword"), MapToApiVersion("1.0")]
public async Task<IActionResult> ResetPassword([FromBody] ResetPasswordViewModel model)
{
if (ModelState.IsValid)
{
var user = await _userManager.FindByEmailAsync(model.Email);
if (user == null)
{
// Don't reveal that the user does not exist~Send it to the ResetPasswordConfirmation page.
return NoContent();
}
var codeDecodedBytes = WebEncoders.Base64UrlDecode(model.Code);
var codeDecoded = Encoding.UTF8.GetString(codeDecodedBytes);
var result = await _userManager.ResetPasswordAsync(user, codeDecoded, model.Password);
if (result.Succeeded)
{
//Send Email
await SparkPostService.ResetPasswordConfirmation(model.Email);
//Send it to the ResetPasswordConfirmation page.
return NoContent();
}
// If we got this far, something failed
IEnumerable<string> errorList = AddErrors(result.Errors);
return StatusCode(500, new { errors = errorList });
}
return BadRequest(ModelState);
}
[Authorize]
[HttpPut("changepassword"), MapToApiVersion("1.0")]
public async Task<IActionResult> ChangePassword([FromBody] ChangePasswordViewModel model)
{
if (ModelState.IsValid)
{
var userId = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
var user = await _userManager.FindByIdAsync(userId);
if (user != null)
{
var result = await _userManager.ChangePasswordAsync(user, model.CurrentPassword, model.NewPassword);
if (result.Succeeded)
{
//Send Email
await SparkPostService.ResetPasswordConfirmation(user.Email);
//Send it to the ResetPasswordConfirmation page.
return NoContent();
}
// If we got this far, something failed
IEnumerable<string> errorList = AddErrors(result.Errors);
return StatusCode(500, new { errors = errorList });
}
}
return BadRequest(ModelState);
}
[Authorize]
[HttpPut("update"), MapToApiVersion("1.0")]
public async Task<IActionResult> Upadate([FromBody] UpdateViewModel model)
{
if (ModelState.IsValid)
{
var userId = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
var user = await _userManager.FindByIdAsync(userId);
if (user != null)
{
user.Name = model.Name;
if (user.Email != model.Email)
{
user.UserName = model.Email;
user.Email = model.Email;
user.EmailConfirmed = false;
var result = await _userManager.UpdateAsync(user);
if (result.Succeeded)
{
var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
byte[] tokenGeneratedBytes = Encoding.UTF8.GetBytes(code);
var codeEncoded = WebEncoders.Base64UrlEncode(tokenGeneratedBytes);
var callbackUrl = Url.Action(nameof(ConfirmEmail), "Accounts", new { userId = user.Id, code = codeEncoded }, protocol: HttpContext.Request.Scheme);
//Send Email
await SparkPostService.RegisterUser(model.Email, callbackUrl);
return Ok(new { isEmailChanged = true });
}
// If we got this far, something failed
IEnumerable<string> errorList = AddErrors(result.Errors);
return StatusCode(500, new { errors = errorList });
}
else
{
var result = await _userManager.UpdateAsync(user);
if (result.Succeeded)
{
return Ok(new { isEmailChanged = false });
}
// If we got this far, something failed
IEnumerable<string> errorList = AddErrors(result.Errors);
return StatusCode(500, new { errors = errorList });
}
}
}
return BadRequest(ModelState);
}
[Authorize]
[HttpPut("delete"), MapToApiVersion("1.0")]
public async Task<IActionResult> Delete()
{
if (ModelState.IsValid)
{
var userId = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
var user = await _userManager.FindByIdAsync(userId);
if (user != null)
{
await _userManager.SetLockoutEnabledAsync(user, true);
var result = await _userManager.SetLockoutEndDateAsync(user, DateTime.Today.AddYears(10));
if (result.Succeeded)
{
//Send Email
await SparkPostService.DeleteUser(user.Email);
//Send it to the Home page.
return NoContent();
}
// If we got this far, something failed
IEnumerable<string> errorList = AddErrors(result.Errors);
return StatusCode(500, new { errors = errorList });
}
}
return BadRequest(ModelState);
}
#region Helpers
private string GenerateSecurityToken(ApplicationUser user)
{
var tokenHandler = new JwtSecurityTokenHandler();
var key = Encoding.ASCII.GetBytes(_appSetting.JWTSecret);
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(new Claim[]
{
new Claim(ClaimTypes.NameIdentifier, user.Id),
new Claim("plan", user.PlanId.ToString())
}),
Expires = DateTime.UtcNow.AddDays(5),
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
};
var token = tokenHandler.CreateToken(tokenDescriptor);
return tokenHandler.WriteToken(token);
}
private OkObjectResult UserInfo(ApplicationUser user, bool isSocialNetwork)
{
var token = this.GenerateSecurityToken(user);
var plan = Enum.GetName(typeof(PlanStatus), user.PlanId);
if (isSocialNetwork)
{
return Ok(new { userId = user.Id, name = user.Name, email = user.Email, plan, token });
}
else
{
return Ok(new { userId = user.Id, name = user.Name, plan, token });
}
}
private IEnumerable<string> AddErrors(IEnumerable<IdentityError> errors)
{
var list = new List<string>();
foreach (var error in errors)
{
list.Add(error.Description);
}
return list;
}
private class RecaptchaResponse
{
[JsonProperty("success")]
public bool Success { get; set; }
}
private class FacebookAuthResponse
{
public string first_name { get; set; }
public string name { get; set; }
public string email { get; set; }
public string id { get; set; }
}
private class GoogleAuthResponse
{
public string name { get; set; }
public string picture { get; set; }
public string given_name { get; set; }
public string email { get; set; }
public string sub { get; set; } //user Id
}
#endregion
}
}
| |
// Description: Html Agility Pack - HTML Parsers, selectors, traversors, manupulators.
// Website & Documentation: http://html-agility-pack.net
// Forum & Issues: https://github.com/zzzprojects/html-agility-pack
// License: https://github.com/zzzprojects/html-agility-pack/blob/master/LICENSE
// More projects: http://www.zzzprojects.com/
// Copyright ?ZZZ Projects Inc. 2014 - 2017. All rights reserved.
#region
using System;
using System.Diagnostics;
#endregion
// ReSharper disable InconsistentNaming
namespace ToolGood.ReadyGo3.Mvc.HtmlAgilityPack
{
/// <summary>
/// Represents an HTML attribute.
/// </summary>
[DebuggerDisplay("Name: {OriginalName}, Value: {Value}")]
public class HtmlAttribute : IComparable
{
#region Fields
private int _line;
internal int _lineposition;
internal string _name;
internal int _namelength;
internal int _namestartindex;
internal HtmlDocument _ownerdocument; // attribute can exists without a node
internal HtmlNode _ownernode;
private AttributeValueQuote _quoteType = AttributeValueQuote.DoubleQuote;
internal int _streamposition;
internal string _value;
internal int _valuelength;
internal int _valuestartindex;
#endregion
#region Constructors
internal HtmlAttribute(HtmlDocument ownerdocument)
{
_ownerdocument = ownerdocument;
}
#endregion
#region Properties
/// <summary>
/// Gets the line number of this attribute in the document.
/// </summary>
public int Line
{
get { return _line; }
internal set { _line = value; }
}
/// <summary>
/// Gets the column number of this attribute in the document.
/// </summary>
public int LinePosition
{
get { return _lineposition; }
}
/// <summary>
/// Gets the qualified name of the attribute.
/// </summary>
public string Name
{
get
{
if (_name == null)
{
_name = _ownerdocument.Text.Substring(_namestartindex, _namelength);
}
return _name.ToLowerInvariant();
}
set
{
if (value == null)
{
throw new ArgumentNullException("value");
}
_name = value;
if (_ownernode != null)
{
_ownernode.SetChanged();
}
}
}
/// <summary>
/// Name of attribute with original case
/// </summary>
public string OriginalName
{
get { return _name; }
}
/// <summary>
/// Gets the HTML document to which this attribute belongs.
/// </summary>
public HtmlDocument OwnerDocument
{
get { return _ownerdocument; }
}
/// <summary>
/// Gets the HTML node to which this attribute belongs.
/// </summary>
public HtmlNode OwnerNode
{
get { return _ownernode; }
}
/// <summary>
/// Specifies what type of quote the data should be wrapped in
/// </summary>
public AttributeValueQuote QuoteType
{
get { return _quoteType; }
set { _quoteType = value; }
}
/// <summary>
/// Gets the stream position of this attribute in the document, relative to the start of the document.
/// </summary>
public int StreamPosition
{
get { return _streamposition; }
}
/// <summary>
/// Gets or sets the value of the attribute.
/// </summary>
public string Value
{
get
{
// A null value has been provided, the attribute should be considered as "hidden"
if (_value == null && _ownerdocument.Text == null && _valuestartindex == 0 && _valuelength == 0)
{
return null;
}
if (_value == null)
{
_value = _ownerdocument.Text.Substring(_valuestartindex, _valuelength);
if (!_ownerdocument.BackwardCompatibility)
{
_value = HtmlEntity.DeEntitize(_value);
}
}
return _value;
}
set
{
_value = value;
if (_ownernode != null)
{
_ownernode.SetChanged();
}
}
}
/// <summary>
/// Gets the DeEntitized value of the attribute.
/// </summary>
public string DeEntitizeValue
{
get { return HtmlEntity.DeEntitize(Value); }
}
internal string XmlName
{
get { return HtmlDocument.GetXmlName(Name, true); }
}
internal string XmlValue
{
get { return Value; }
}
/// <summary>
/// Gets a valid XPath string that points to this Attribute
/// </summary>
public string XPath
{
get
{
string basePath = (OwnerNode == null) ? "/" : OwnerNode.XPath + "/";
return basePath + GetRelativeXpath();
}
}
#endregion
#region IComparable Members
/// <summary>
/// Compares the current instance with another attribute. Comparison is based on attributes' name.
/// </summary>
/// <param name="obj">An attribute to compare with this instance.</param>
/// <returns>A 32-bit signed integer that indicates the relative order of the names comparison.</returns>
public int CompareTo(object obj)
{
HtmlAttribute att = obj as HtmlAttribute;
if (att == null)
{
throw new ArgumentException("obj");
}
return Name.CompareTo(att.Name);
}
#endregion
#region Public Methods
/// <summary>
/// Creates a duplicate of this attribute.
/// </summary>
/// <returns>The cloned attribute.</returns>
public HtmlAttribute Clone()
{
HtmlAttribute att = new HtmlAttribute(_ownerdocument);
att.Name = Name;
att.Value = Value;
att.QuoteType = QuoteType;
return att;
}
/// <summary>
/// Removes this attribute from it's parents collection
/// </summary>
public void Remove()
{
_ownernode.Attributes.Remove(this);
}
#endregion
#region Private Methods
private string GetRelativeXpath()
{
if (OwnerNode == null)
return Name;
int i = 1;
foreach (HtmlAttribute node in OwnerNode.Attributes)
{
if (node.Name != Name) continue;
if (node == this)
break;
i++;
}
return "@" + Name + "[" + i + "]";
}
#endregion
}
/// <summary>
/// An Enum representing different types of Quotes used for surrounding attribute values
/// </summary>
public enum AttributeValueQuote
{
/// <summary>
/// A single quote mark '
/// </summary>
SingleQuote,
/// <summary>
/// A double quote mark "
/// </summary>
DoubleQuote
}
}
| |
using Microsoft.IdentityModel.S2S.Protocols.OAuth2;
using Microsoft.IdentityModel.Tokens;
using Microsoft.SharePoint.Client;
using System;
using System.Net;
using System.Security.Principal;
using System.Web;
using System.Web.Configuration;
namespace Contoso.Core.EventReceiverBasedModificationsWeb
{
/// <summary>
/// Encapsulates all the information from SharePoint.
/// </summary>
public abstract class SharePointContext
{
public const string SPHostUrlKey = "SPHostUrl";
public const string SPAppWebUrlKey = "SPAppWebUrl";
public const string SPLanguageKey = "SPLanguage";
public const string SPClientTagKey = "SPClientTag";
public const string SPProductNumberKey = "SPProductNumber";
protected static readonly TimeSpan AccessTokenLifetimeTolerance = TimeSpan.FromMinutes(5.0);
private readonly Uri spHostUrl;
private readonly Uri spAppWebUrl;
private readonly string spLanguage;
private readonly string spClientTag;
private readonly string spProductNumber;
// <AccessTokenString, UtcExpiresOn>
protected Tuple<string, DateTime> userAccessTokenForSPHost;
protected Tuple<string, DateTime> userAccessTokenForSPAppWeb;
protected Tuple<string, DateTime> appOnlyAccessTokenForSPHost;
protected Tuple<string, DateTime> appOnlyAccessTokenForSPAppWeb;
/// <summary>
/// Gets the SharePoint host url from QueryString of the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The specified HTTP request.</param>
/// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns>
public static Uri GetSPHostUrl(HttpRequestBase httpRequest)
{
if (httpRequest == null)
{
throw new ArgumentNullException("httpRequest");
}
string spHostUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SPHostUrlKey]);
Uri spHostUrl;
if (Uri.TryCreate(spHostUrlString, UriKind.Absolute, out spHostUrl) &&
(spHostUrl.Scheme == Uri.UriSchemeHttp || spHostUrl.Scheme == Uri.UriSchemeHttps))
{
return spHostUrl;
}
return null;
}
/// <summary>
/// Gets the SharePoint host url from QueryString of the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The specified HTTP request.</param>
/// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns>
public static Uri GetSPHostUrl(HttpRequest httpRequest)
{
return GetSPHostUrl(new HttpRequestWrapper(httpRequest));
}
/// <summary>
/// The SharePoint host url.
/// </summary>
public Uri SPHostUrl
{
get { return this.spHostUrl; }
}
/// <summary>
/// The SharePoint app web url.
/// </summary>
public Uri SPAppWebUrl
{
get { return this.spAppWebUrl; }
}
/// <summary>
/// The SharePoint language.
/// </summary>
public string SPLanguage
{
get { return this.spLanguage; }
}
/// <summary>
/// The SharePoint client tag.
/// </summary>
public string SPClientTag
{
get { return this.spClientTag; }
}
/// <summary>
/// The SharePoint product number.
/// </summary>
public string SPProductNumber
{
get { return this.spProductNumber; }
}
/// <summary>
/// The user access token for the SharePoint host.
/// </summary>
public abstract string UserAccessTokenForSPHost
{
get;
}
/// <summary>
/// The user access token for the SharePoint app web.
/// </summary>
public abstract string UserAccessTokenForSPAppWeb
{
get;
}
/// <summary>
/// The app only access token for the SharePoint host.
/// </summary>
public abstract string AppOnlyAccessTokenForSPHost
{
get;
}
/// <summary>
/// The app only access token for the SharePoint app web.
/// </summary>
public abstract string AppOnlyAccessTokenForSPAppWeb
{
get;
}
/// <summary>
/// Constructor.
/// </summary>
/// <param name="spHostUrl">The SharePoint host url.</param>
/// <param name="spAppWebUrl">The SharePoint app web url.</param>
/// <param name="spLanguage">The SharePoint language.</param>
/// <param name="spClientTag">The SharePoint client tag.</param>
/// <param name="spProductNumber">The SharePoint product number.</param>
protected SharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber)
{
if (spHostUrl == null)
{
throw new ArgumentNullException("spHostUrl");
}
if (string.IsNullOrEmpty(spLanguage))
{
throw new ArgumentNullException("spLanguage");
}
if (string.IsNullOrEmpty(spClientTag))
{
throw new ArgumentNullException("spClientTag");
}
if (string.IsNullOrEmpty(spProductNumber))
{
throw new ArgumentNullException("spProductNumber");
}
this.spHostUrl = spHostUrl;
this.spAppWebUrl = spAppWebUrl;
this.spLanguage = spLanguage;
this.spClientTag = spClientTag;
this.spProductNumber = spProductNumber;
}
/// <summary>
/// Creates a user ClientContext for the SharePoint host.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateUserClientContextForSPHost()
{
return CreateClientContext(this.SPHostUrl, this.UserAccessTokenForSPHost);
}
/// <summary>
/// Creates a user ClientContext for the SharePoint app web.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateUserClientContextForSPAppWeb()
{
return CreateClientContext(this.SPAppWebUrl, this.UserAccessTokenForSPAppWeb);
}
/// <summary>
/// Creates app only ClientContext for the SharePoint host.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateAppOnlyClientContextForSPHost()
{
return CreateClientContext(this.SPHostUrl, this.AppOnlyAccessTokenForSPHost);
}
/// <summary>
/// Creates an app only ClientContext for the SharePoint app web.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateAppOnlyClientContextForSPAppWeb()
{
return CreateClientContext(this.SPAppWebUrl, this.AppOnlyAccessTokenForSPAppWeb);
}
/// <summary>
/// Gets the database connection string from SharePoint for autohosted app.
/// </summary>
/// <returns>The database connection string. Returns <c>null</c> if the app is not autohosted or there is no database.</returns>
public string GetDatabaseConnectionString()
{
string dbConnectionString = null;
using (ClientContext clientContext = CreateAppOnlyClientContextForSPHost())
{
if (clientContext != null)
{
var result = AppInstance.RetrieveAppDatabaseConnectionString(clientContext);
clientContext.ExecuteQuery();
dbConnectionString = result.Value;
}
}
if (dbConnectionString == null)
{
const string LocalDBInstanceForDebuggingKey = "LocalDBInstanceForDebugging";
var dbConnectionStringSettings = WebConfigurationManager.ConnectionStrings[LocalDBInstanceForDebuggingKey];
dbConnectionString = dbConnectionStringSettings != null ? dbConnectionStringSettings.ConnectionString : null;
}
return dbConnectionString;
}
/// <summary>
/// Determines if the specified access token is valid.
/// It considers an access token as not valid if it is null, or it has expired.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <returns>True if the access token is valid.</returns>
protected static bool IsAccessTokenValid(Tuple<string, DateTime> accessToken)
{
return accessToken != null &&
!string.IsNullOrEmpty(accessToken.Item1) &&
accessToken.Item2 > DateTime.UtcNow;
}
/// <summary>
/// Creates a ClientContext with the specified SharePoint site url and the access token.
/// </summary>
/// <param name="spSiteUrl">The site url.</param>
/// <param name="accessToken">The access token.</param>
/// <returns>A ClientContext instance.</returns>
private static ClientContext CreateClientContext(Uri spSiteUrl, string accessToken)
{
if (spSiteUrl != null && !string.IsNullOrEmpty(accessToken))
{
return TokenHelper.GetClientContextWithAccessToken(spSiteUrl.AbsoluteUri, accessToken);
}
return null;
}
}
/// <summary>
/// Redirection status.
/// </summary>
public enum RedirectionStatus
{
Ok,
ShouldRedirect,
CanNotRedirect
}
/// <summary>
/// Provides SharePointContext instances.
/// </summary>
public abstract class SharePointContextProvider
{
private static SharePointContextProvider current;
/// <summary>
/// The current SharePointContextProvider instance.
/// </summary>
public static SharePointContextProvider Current
{
get { return SharePointContextProvider.current; }
}
/// <summary>
/// Initializes the default SharePointContextProvider instance.
/// </summary>
static SharePointContextProvider()
{
if (!TokenHelper.IsHighTrustApp())
{
SharePointContextProvider.current = new SharePointAcsContextProvider();
}
else
{
SharePointContextProvider.current = new SharePointHighTrustContextProvider();
}
}
/// <summary>
/// Registers the specified SharePointContextProvider instance as current.
/// It should be called by Application_Start() in Global.asax.
/// </summary>
/// <param name="provider">The SharePointContextProvider to be set as current.</param>
public static void Register(SharePointContextProvider provider)
{
if (provider == null)
{
throw new ArgumentNullException("provider");
}
SharePointContextProvider.current = provider;
}
/// <summary>
/// Checks if it is necessary to redirect to SharePoint for user to authenticate.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param>
/// <returns>Redirection status.</returns>
public static RedirectionStatus CheckRedirectionStatus(HttpContextBase httpContext, out Uri redirectUrl)
{
if (httpContext == null)
{
throw new ArgumentNullException("httpContext");
}
redirectUrl = null;
if (SharePointContextProvider.Current.GetSharePointContext(httpContext) != null)
{
return RedirectionStatus.Ok;
}
const string SPHasRedirectedToSharePointKey = "SPHasRedirectedToSharePoint";
if (!string.IsNullOrEmpty(httpContext.Request.QueryString[SPHasRedirectedToSharePointKey]))
{
return RedirectionStatus.CanNotRedirect;
}
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
if (spHostUrl == null)
{
return RedirectionStatus.CanNotRedirect;
}
if (StringComparer.OrdinalIgnoreCase.Equals(httpContext.Request.HttpMethod, "POST"))
{
return RedirectionStatus.CanNotRedirect;
}
Uri requestUrl = httpContext.Request.Url;
var queryNameValueCollection = HttpUtility.ParseQueryString(requestUrl.Query);
// Removes the values that are included in {StandardTokens}, as {StandardTokens} will be inserted at the beginning of the query string.
queryNameValueCollection.Remove(SharePointContext.SPHostUrlKey);
queryNameValueCollection.Remove(SharePointContext.SPAppWebUrlKey);
queryNameValueCollection.Remove(SharePointContext.SPLanguageKey);
queryNameValueCollection.Remove(SharePointContext.SPClientTagKey);
queryNameValueCollection.Remove(SharePointContext.SPProductNumberKey);
// Adds SPHasRedirectedToSharePoint=1.
queryNameValueCollection.Add(SPHasRedirectedToSharePointKey, "1");
UriBuilder returnUrlBuilder = new UriBuilder(requestUrl);
returnUrlBuilder.Query = queryNameValueCollection.ToString();
// Inserts StandardTokens.
const string StandardTokens = "{StandardTokens}";
string returnUrlString = returnUrlBuilder.Uri.AbsoluteUri;
returnUrlString = returnUrlString.Insert(returnUrlString.IndexOf("?") + 1, StandardTokens + "&");
// Constructs redirect url.
string redirectUrlString = TokenHelper.GetAppContextTokenRequestUrl(spHostUrl.AbsoluteUri, Uri.EscapeDataString(returnUrlString));
redirectUrl = new Uri(redirectUrlString, UriKind.Absolute);
return RedirectionStatus.ShouldRedirect;
}
/// <summary>
/// Checks if it is necessary to redirect to SharePoint for user to authenticate.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param>
/// <returns>Redirection status.</returns>
public static RedirectionStatus CheckRedirectionStatus(HttpContext httpContext, out Uri redirectUrl)
{
return CheckRedirectionStatus(new HttpContextWrapper(httpContext), out redirectUrl);
}
/// <summary>
/// Creates a SharePointContext instance with the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
public SharePointContext CreateSharePointContext(HttpRequestBase httpRequest)
{
if (httpRequest == null)
{
throw new ArgumentNullException("httpRequest");
}
// SPHostUrl
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpRequest);
if (spHostUrl == null)
{
return null;
}
// SPAppWebUrl
string spAppWebUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SharePointContext.SPAppWebUrlKey]);
Uri spAppWebUrl;
if (!Uri.TryCreate(spAppWebUrlString, UriKind.Absolute, out spAppWebUrl) ||
!(spAppWebUrl.Scheme == Uri.UriSchemeHttp || spAppWebUrl.Scheme == Uri.UriSchemeHttps))
{
spAppWebUrl = null;
}
// SPLanguage
string spLanguage = httpRequest.QueryString[SharePointContext.SPLanguageKey];
if (string.IsNullOrEmpty(spLanguage))
{
return null;
}
// SPClientTag
string spClientTag = httpRequest.QueryString[SharePointContext.SPClientTagKey];
if (string.IsNullOrEmpty(spClientTag))
{
return null;
}
// SPProductNumber
string spProductNumber = httpRequest.QueryString[SharePointContext.SPProductNumberKey];
if (string.IsNullOrEmpty(spProductNumber))
{
return null;
}
return CreateSharePointContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, httpRequest);
}
/// <summary>
/// Creates a SharePointContext instance with the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
public SharePointContext CreateSharePointContext(HttpRequest httpRequest)
{
return CreateSharePointContext(new HttpRequestWrapper(httpRequest));
}
/// <summary>
/// Gets a SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns>
public SharePointContext GetSharePointContext(HttpContextBase httpContext)
{
if (httpContext == null)
{
throw new ArgumentNullException("httpContext");
}
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
if (spHostUrl == null)
{
return null;
}
SharePointContext spContext = LoadSharePointContext(httpContext);
if (spContext == null || !ValidateSharePointContext(spContext, httpContext))
{
spContext = CreateSharePointContext(httpContext.Request);
if (spContext != null)
{
SaveSharePointContext(spContext, httpContext);
}
}
return spContext;
}
/// <summary>
/// Gets a SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns>
public SharePointContext GetSharePointContext(HttpContext httpContext)
{
return GetSharePointContext(new HttpContextWrapper(httpContext));
}
/// <summary>
/// Creates a SharePointContext instance.
/// </summary>
/// <param name="spHostUrl">The SharePoint host url.</param>
/// <param name="spAppWebUrl">The SharePoint app web url.</param>
/// <param name="spLanguage">The SharePoint language.</param>
/// <param name="spClientTag">The SharePoint client tag.</param>
/// <param name="spProductNumber">The SharePoint product number.</param>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
protected abstract SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest);
/// <summary>
/// Validates if the given SharePointContext can be used with the specified HTTP context.
/// </summary>
/// <param name="spContext">The SharePointContext.</param>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>True if the given SharePointContext can be used with the specified HTTP context.</returns>
protected abstract bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext);
/// <summary>
/// Loads the SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found.</returns>
protected abstract SharePointContext LoadSharePointContext(HttpContextBase httpContext);
/// <summary>
/// Saves the specified SharePointContext instance associated with the specified HTTP context.
/// <c>null</c> is accepted for clearing the SharePointContext instance associated with the HTTP context.
/// </summary>
/// <param name="spContext">The SharePointContext instance to be saved, or <c>null</c>.</param>
/// <param name="httpContext">The HTTP context.</param>
protected abstract void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext);
}
#region ACS
/// <summary>
/// Encapsulates all the information from SharePoint in ACS mode.
/// </summary>
public class SharePointAcsContext : SharePointContext
{
private readonly string contextToken;
private readonly SharePointContextToken contextTokenObj;
/// <summary>
/// The context token.
/// </summary>
public string ContextToken
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextToken : null; }
}
/// <summary>
/// The context token's "CacheKey" claim.
/// </summary>
public string CacheKey
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.CacheKey : null; }
}
/// <summary>
/// The context token's "refreshtoken" claim.
/// </summary>
public string RefreshToken
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.RefreshToken : null; }
}
public override string UserAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.userAccessTokenForSPHost,
() => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPHostUrl.Authority));
}
}
public override string UserAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb,
() => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPAppWebUrl.Authority));
}
}
public override string AppOnlyAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost,
() => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPHostUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPHostUrl)));
}
}
public override string AppOnlyAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb,
() => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPAppWebUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPAppWebUrl)));
}
}
public SharePointAcsContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, string contextToken, SharePointContextToken contextTokenObj)
: base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber)
{
if (string.IsNullOrEmpty(contextToken))
{
throw new ArgumentNullException("contextToken");
}
if (contextTokenObj == null)
{
throw new ArgumentNullException("contextTokenObj");
}
this.contextToken = contextToken;
this.contextTokenObj = contextTokenObj;
}
/// <summary>
/// Ensures the access token is valid and returns it.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
/// <returns>The access token string.</returns>
private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler)
{
RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler);
return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null;
}
/// <summary>
/// Renews the access token if it is not valid.
/// </summary>
/// <param name="accessToken">The access token to renew.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler)
{
if (IsAccessTokenValid(accessToken))
{
return;
}
try
{
OAuth2AccessTokenResponse oAuth2AccessTokenResponse = tokenRenewalHandler();
DateTime expiresOn = oAuth2AccessTokenResponse.ExpiresOn;
if ((expiresOn - oAuth2AccessTokenResponse.NotBefore) > AccessTokenLifetimeTolerance)
{
// Make the access token get renewed a bit earlier than the time when it expires
// so that the calls to SharePoint with it will have enough time to complete successfully.
expiresOn -= AccessTokenLifetimeTolerance;
}
accessToken = Tuple.Create(oAuth2AccessTokenResponse.AccessToken, expiresOn);
}
catch (WebException)
{
}
}
}
/// <summary>
/// Default provider for SharePointAcsContext.
/// </summary>
public class SharePointAcsContextProvider : SharePointContextProvider
{
private const string SPContextKey = "SPContext";
private const string SPCacheKeyKey = "SPCacheKey";
protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest)
{
string contextTokenString = TokenHelper.GetContextTokenFromRequest(httpRequest);
if (string.IsNullOrEmpty(contextTokenString))
{
return null;
}
SharePointContextToken contextToken = null;
try
{
contextToken = TokenHelper.ReadAndValidateContextToken(contextTokenString, httpRequest.Url.Authority);
}
catch (WebException)
{
return null;
}
catch (AudienceUriValidationFailedException)
{
return null;
}
return new SharePointAcsContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, contextTokenString, contextToken);
}
protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointAcsContext spAcsContext = spContext as SharePointAcsContext;
if (spAcsContext != null)
{
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
string contextToken = TokenHelper.GetContextTokenFromRequest(httpContext.Request);
HttpCookie spCacheKeyCookie = httpContext.Request.Cookies[SPCacheKeyKey];
string spCacheKey = spCacheKeyCookie != null ? spCacheKeyCookie.Value : null;
return spHostUrl == spAcsContext.SPHostUrl &&
!string.IsNullOrEmpty(spAcsContext.CacheKey) &&
spCacheKey == spAcsContext.CacheKey &&
!string.IsNullOrEmpty(spAcsContext.ContextToken) &&
(string.IsNullOrEmpty(contextToken) || contextToken == spAcsContext.ContextToken);
}
return false;
}
protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext)
{
return httpContext.Session[SPContextKey] as SharePointAcsContext;
}
protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointAcsContext spAcsContext = spContext as SharePointAcsContext;
if (spAcsContext != null)
{
HttpCookie spCacheKeyCookie = new HttpCookie(SPCacheKeyKey)
{
Value = spAcsContext.CacheKey,
Secure = true,
HttpOnly = true
};
httpContext.Response.AppendCookie(spCacheKeyCookie);
}
httpContext.Session[SPContextKey] = spAcsContext;
}
}
#endregion ACS
#region HighTrust
/// <summary>
/// Encapsulates all the information from SharePoint in HighTrust mode.
/// </summary>
public class SharePointHighTrustContext : SharePointContext
{
private readonly WindowsIdentity logonUserIdentity;
/// <summary>
/// The Windows identity for the current user.
/// </summary>
public WindowsIdentity LogonUserIdentity
{
get { return this.logonUserIdentity; }
}
public override string UserAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.userAccessTokenForSPHost,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, this.LogonUserIdentity));
}
}
public override string UserAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, this.LogonUserIdentity));
}
}
public override string AppOnlyAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, null));
}
}
public override string AppOnlyAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, null));
}
}
public SharePointHighTrustContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, WindowsIdentity logonUserIdentity)
: base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber)
{
if (logonUserIdentity == null)
{
throw new ArgumentNullException("logonUserIdentity");
}
this.logonUserIdentity = logonUserIdentity;
}
/// <summary>
/// Ensures the access token is valid and returns it.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
/// <returns>The access token string.</returns>
private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler)
{
RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler);
return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null;
}
/// <summary>
/// Renews the access token if it is not valid.
/// </summary>
/// <param name="accessToken">The access token to renew.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler)
{
if (IsAccessTokenValid(accessToken))
{
return;
}
DateTime expiresOn = DateTime.UtcNow.Add(TokenHelper.HighTrustAccessTokenLifetime);
if (TokenHelper.HighTrustAccessTokenLifetime > AccessTokenLifetimeTolerance)
{
// Make the access token get renewed a bit earlier than the time when it expires
// so that the calls to SharePoint with it will have enough time to complete successfully.
expiresOn -= AccessTokenLifetimeTolerance;
}
accessToken = Tuple.Create(tokenRenewalHandler(), expiresOn);
}
}
/// <summary>
/// Default provider for SharePointHighTrustContext.
/// </summary>
public class SharePointHighTrustContextProvider : SharePointContextProvider
{
private const string SPContextKey = "SPContext";
protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest)
{
WindowsIdentity logonUserIdentity = httpRequest.LogonUserIdentity;
if (logonUserIdentity == null || !logonUserIdentity.IsAuthenticated || logonUserIdentity.IsGuest || logonUserIdentity.User == null)
{
return null;
}
return new SharePointHighTrustContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, logonUserIdentity);
}
protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointHighTrustContext spHighTrustContext = spContext as SharePointHighTrustContext;
if (spHighTrustContext != null)
{
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
WindowsIdentity logonUserIdentity = httpContext.Request.LogonUserIdentity;
return spHostUrl == spHighTrustContext.SPHostUrl &&
logonUserIdentity != null &&
logonUserIdentity.IsAuthenticated &&
!logonUserIdentity.IsGuest &&
logonUserIdentity.User == spHighTrustContext.LogonUserIdentity.User;
}
return false;
}
protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext)
{
return httpContext.Session[SPContextKey] as SharePointHighTrustContext;
}
protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
httpContext.Session[SPContextKey] = spContext as SharePointHighTrustContext;
}
}
#endregion HighTrust
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using Microsoft.MixedReality.Toolkit.Utilities.Editor;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using UnityEditor;
using UnityEditor.Build.Reporting;
using UnityEngine;
using Debug = UnityEngine.Debug;
namespace Microsoft.MixedReality.Toolkit.Build.Editor
{
/// <summary>
/// Cross platform player build tools
/// </summary>
public static class UnityPlayerBuildTools
{
// Build configurations. Exactly one of these should be defined for any given build.
public const string BuildSymbolDebug = "debug";
public const string BuildSymbolRelease = "release";
public const string BuildSymbolMaster = "master";
/// <summary>
/// Starts the build process
/// </summary>
/// <param name="buildInfo"></param>
/// <returns>The <see href="https://docs.unity3d.com/ScriptReference/Build.Reporting.BuildReport.html">BuildReport</see> from Unity's <see href="https://docs.unity3d.com/ScriptReference/BuildPipeline.html">BuildPipeline</see></returns>
public static BuildReport BuildUnityPlayer(IBuildInfo buildInfo)
{
EditorUtility.DisplayProgressBar("Build Pipeline", "Gathering Build Data...", 0.25f);
// Call the pre-build action, if any
buildInfo.PreBuildAction?.Invoke(buildInfo);
BuildTargetGroup buildTargetGroup = buildInfo.BuildTarget.GetGroup();
string playerBuildSymbols = PlayerSettings.GetScriptingDefineSymbolsForGroup(buildTargetGroup);
if (!string.IsNullOrEmpty(playerBuildSymbols))
{
if (buildInfo.HasConfigurationSymbol())
{
buildInfo.AppendWithoutConfigurationSymbols(playerBuildSymbols);
}
else
{
buildInfo.AppendSymbols(playerBuildSymbols.Split(';'));
}
}
if (!string.IsNullOrEmpty(buildInfo.BuildSymbols))
{
PlayerSettings.SetScriptingDefineSymbolsForGroup(buildTargetGroup, buildInfo.BuildSymbols);
}
if ((buildInfo.BuildOptions & BuildOptions.Development) == BuildOptions.Development &&
!buildInfo.HasConfigurationSymbol())
{
buildInfo.AppendSymbols(BuildSymbolDebug);
}
if (buildInfo.HasAnySymbols(BuildSymbolDebug))
{
buildInfo.BuildOptions |= BuildOptions.Development | BuildOptions.AllowDebugging;
}
if (buildInfo.HasAnySymbols(BuildSymbolRelease))
{
// Unity automatically adds the DEBUG symbol if the BuildOptions.Development flag is
// specified. In order to have debug symbols and the RELEASE symbols we have to
// inject the symbol Unity relies on to enable the /debug+ flag of csc.exe which is "DEVELOPMENT_BUILD"
buildInfo.AppendSymbols("DEVELOPMENT_BUILD");
}
var oldColorSpace = PlayerSettings.colorSpace;
if (buildInfo.ColorSpace.HasValue)
{
PlayerSettings.colorSpace = buildInfo.ColorSpace.Value;
}
if (buildInfo.ScriptingBackend.HasValue)
{
PlayerSettings.SetScriptingBackend(buildTargetGroup, buildInfo.ScriptingBackend.Value);
}
BuildTarget oldBuildTarget = EditorUserBuildSettings.activeBuildTarget;
BuildTargetGroup oldBuildTargetGroup = oldBuildTarget.GetGroup();
if (EditorUserBuildSettings.activeBuildTarget != buildInfo.BuildTarget)
{
EditorUserBuildSettings.SwitchActiveBuildTarget(buildTargetGroup, buildInfo.BuildTarget);
}
switch (buildInfo.BuildTarget)
{
case BuildTarget.Android:
buildInfo.OutputDirectory = $"{buildInfo.OutputDirectory}/{PlayerSettings.productName}.apk";
break;
case BuildTarget.StandaloneWindows:
case BuildTarget.StandaloneWindows64:
buildInfo.OutputDirectory = $"{buildInfo.OutputDirectory}/{PlayerSettings.productName}.exe";
break;
}
BuildReport buildReport = default;
try
{
buildReport = BuildPipeline.BuildPlayer(
buildInfo.Scenes.ToArray(),
buildInfo.OutputDirectory,
buildInfo.BuildTarget,
buildInfo.BuildOptions);
}
catch (Exception e)
{
Debug.LogError($"{e.Message}\n{e.StackTrace}");
}
PlayerSettings.colorSpace = oldColorSpace;
if (EditorUserBuildSettings.activeBuildTarget != oldBuildTarget)
{
EditorUserBuildSettings.SwitchActiveBuildTarget(oldBuildTargetGroup, oldBuildTarget);
}
// Call the post-build action, if any
buildInfo.PostBuildAction?.Invoke(buildInfo, buildReport);
return buildReport;
}
/// <summary>
/// Force Unity To Write Project Files
/// </summary>
public static void SyncSolution()
{
var syncVs = Type.GetType("UnityEditor.SyncVS,UnityEditor");
var syncSolution = syncVs.GetMethod("SyncSolution", BindingFlags.Public | BindingFlags.Static);
syncSolution.Invoke(null, null);
}
/// <summary>
/// Start a build using Unity's command line.
/// </summary>
public static async void StartCommandLineBuild()
{
// We don't need stack traces on all our logs. Makes things a lot easier to read.
Application.SetStackTraceLogType(LogType.Log, StackTraceLogType.None);
Debug.Log($"Starting command line build for {EditorUserBuildSettings.activeBuildTarget}...");
EditorAssemblyReloadManager.LockReloadAssemblies = true;
bool success;
try
{
SyncSolution();
switch (EditorUserBuildSettings.activeBuildTarget)
{
case BuildTarget.WSAPlayer:
success = await UwpPlayerBuildTools.BuildPlayer(new UwpBuildInfo(true));
break;
default:
var buildInfo = new BuildInfo(true) as IBuildInfo;
ParseBuildCommandLine(ref buildInfo);
var buildResult = BuildUnityPlayer(buildInfo);
success = buildResult.summary.result == BuildResult.Succeeded;
break;
}
}
catch (Exception e)
{
Debug.LogError($"Build Failed!\n{e.Message}\n{e.StackTrace}");
success = false;
}
Debug.Log($"Exiting command line build... Build success? {success}");
EditorApplication.Exit(success ? 0 : 1);
}
internal static bool CheckBuildScenes()
{
if (EditorBuildSettings.scenes.Length == 0)
{
return EditorUtility.DisplayDialog("Attention!",
"No scenes are present in the build settings.\n" +
"The current scene will be the one built.\n\n" +
"Do you want to cancel and add one?",
"Continue Anyway", "Cancel Build");
}
return true;
}
/// <summary>
/// Get the Unity Project Root Path.
/// </summary>
/// <returns>The full path to the project's root.</returns>
public static string GetProjectPath()
{
return Path.GetDirectoryName(Path.GetFullPath(Application.dataPath));
}
public static void ParseBuildCommandLine(ref IBuildInfo buildInfo)
{
string[] arguments = Environment.GetCommandLineArgs();
for (int i = 0; i < arguments.Length; ++i)
{
switch (arguments[i])
{
case "-autoIncrement":
buildInfo.AutoIncrement = true;
break;
case "-sceneList":
buildInfo.Scenes = buildInfo.Scenes.Union(SplitSceneList(arguments[++i]));
break;
case "-sceneListFile":
string path = arguments[++i];
if (File.Exists(path))
{
buildInfo.Scenes = buildInfo.Scenes.Union(SplitSceneList(File.ReadAllText(path)));
}
else
{
Debug.LogWarning($"Scene list file at '{path}' does not exist.");
}
break;
case "-buildOutput":
buildInfo.OutputDirectory = arguments[++i];
break;
case "-colorSpace":
buildInfo.ColorSpace = (ColorSpace)Enum.Parse(typeof(ColorSpace), arguments[++i]);
break;
case "-scriptingBackend":
buildInfo.ScriptingBackend = (ScriptingImplementation)Enum.Parse(typeof(ScriptingImplementation), arguments[++i]);
break;
case "-x86":
case "-x64":
case "-arm":
buildInfo.BuildPlatform = arguments[i].Substring(1);
break;
case "-debug":
case "-master":
case "-release":
buildInfo.Configuration = arguments[i].Substring(1).ToLower();
break;
}
}
}
private static IEnumerable<string> SplitSceneList(string sceneList)
{
return from scene in sceneList.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
select scene.Trim();
}
/// <summary>
/// Restores any nuget packages at the path specified.
/// </summary>
/// <param name="nugetPath"></param>
/// <param name="storePath"></param>
/// <returns>True, if the nuget packages were successfully restored.</returns>
public static async Task<bool> RestoreNugetPackagesAsync(string nugetPath, string storePath)
{
Debug.Assert(File.Exists(nugetPath));
Debug.Assert(Directory.Exists(storePath));
await new Process().StartProcessAsync(nugetPath, $"restore \"{storePath}/project.json\"");
return File.Exists($"{storePath}\\project.lock.json");
}
}
}
| |
using System;
using NUnit.Framework;
using System.Drawing;
using OpenQA.Selenium.Environment;
using System.Collections.ObjectModel;
namespace OpenQA.Selenium
{
[TestFixture]
public class VisibilityTest : DriverTestFixture
{
[Test]
public void ShouldAllowTheUserToTellIfAnElementIsDisplayedOrNot()
{
driver.Url = javascriptPage;
Assert.That(driver.FindElement(By.Id("displayed")).Displayed, Is.True, "Element with ID 'displayed' should be displayed");
Assert.That(driver.FindElement(By.Id("none")).Displayed, Is.False, "Element with ID 'none' should not be displayed");
Assert.That(driver.FindElement(By.Id("suppressedParagraph")).Displayed, Is.False, "Element with ID 'suppressedParagraph' should not be displayed");
Assert.That(driver.FindElement(By.Id("hidden")).Displayed, Is.False, "Element with ID 'hidden' should not be displayed");
}
[Test]
public void VisibilityShouldTakeIntoAccountParentVisibility()
{
driver.Url = javascriptPage;
IWebElement childDiv = driver.FindElement(By.Id("hiddenchild"));
IWebElement hiddenLink = driver.FindElement(By.Id("hiddenlink"));
Assert.That(childDiv.Displayed, Is.False, "Child div should not be displayed");
Assert.That(hiddenLink.Displayed, Is.False, "Hidden link should not be displayed");
}
[Test]
public void ShouldCountElementsAsVisibleIfStylePropertyHasBeenSet()
{
driver.Url = javascriptPage;
IWebElement shown = driver.FindElement(By.Id("visibleSubElement"));
Assert.That(shown.Displayed, Is.True);
}
[Test]
public void ShouldModifyTheVisibilityOfAnElementDynamically()
{
driver.Url = javascriptPage;
IWebElement element = driver.FindElement(By.Id("hideMe"));
Assert.That(element.Displayed, Is.True);
element.Click();
Assert.That(element.Displayed, Is.False);
}
[Test]
public void HiddenInputElementsAreNeverVisible()
{
driver.Url = javascriptPage;
IWebElement shown = driver.FindElement(By.Name("hidden"));
Assert.That(shown.Displayed, Is.False);
}
[Test]
public void ShouldNotBeAbleToClickOnAnElementThatIsNotDisplayed()
{
driver.Url = javascriptPage;
IWebElement element = driver.FindElement(By.Id("unclickable"));
Assert.That(() => element.Click(), Throws.InstanceOf<ElementNotInteractableException>());
}
[Test]
public void ShouldNotBeAbleToTypeAnElementThatIsNotDisplayed()
{
driver.Url = javascriptPage;
IWebElement element = driver.FindElement(By.Id("unclickable"));
Assert.That(() => element.SendKeys("You don't see me"), Throws.InstanceOf<ElementNotInteractableException>());
Assert.That(element.GetAttribute("value"), Is.Not.EqualTo("You don't see me"));
}
[Test]
public void ZeroSizedDivIsShownIfDescendantHasSize()
{
driver.Url = javascriptPage;
IWebElement element = driver.FindElement(By.Id("zero"));
Size size = element.Size;
Assert.AreEqual(0, size.Width, "Should have 0 width");
Assert.AreEqual(0, size.Height, "Should have 0 height");
Assert.That(element.Displayed, Is.True);
}
[Test]
public void ParentNodeVisibleWhenAllChildrenAreAbsolutelyPositionedAndOverflowIsHidden()
{
String url = EnvironmentManager.Instance.UrlBuilder.WhereIs("visibility-css.html");
driver.Url = url;
IWebElement element = driver.FindElement(By.Id("suggest"));
Assert.That(element.Displayed, Is.True);
}
[Test]
[IgnoreBrowser(Browser.Opera)]
public void ElementHiddenByOverflowXIsNotVisible()
{
string[] pages = new string[]{
"overflow/x_hidden_y_hidden.html",
"overflow/x_hidden_y_scroll.html",
"overflow/x_hidden_y_auto.html",
};
foreach (string page in pages)
{
driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs(page);
IWebElement right = driver.FindElement(By.Id("right"));
Assert.That(right.Displayed, Is.False, "Failed for " + page);
IWebElement bottomRight = driver.FindElement(By.Id("bottom-right"));
Assert.That(bottomRight.Displayed, Is.False, "Failed for " + page);
}
}
[Test]
[IgnoreBrowser(Browser.Opera)]
public void ElementHiddenByOverflowYIsNotVisible()
{
string[] pages = new string[]{
"overflow/x_hidden_y_hidden.html",
"overflow/x_scroll_y_hidden.html",
"overflow/x_auto_y_hidden.html",
};
foreach (string page in pages)
{
driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs(page);
IWebElement bottom = driver.FindElement(By.Id("bottom"));
Assert.That(bottom.Displayed, Is.False, "Failed for " + page);
IWebElement bottomRight = driver.FindElement(By.Id("bottom-right"));
Assert.That(bottomRight.Displayed, Is.False, "Failed for " + page);
}
}
[Test]
public void ElementScrollableByOverflowXIsVisible()
{
string[] pages = new string[]{
"overflow/x_scroll_y_hidden.html",
"overflow/x_scroll_y_scroll.html",
"overflow/x_scroll_y_auto.html",
"overflow/x_auto_y_hidden.html",
"overflow/x_auto_y_scroll.html",
"overflow/x_auto_y_auto.html",
};
foreach (string page in pages)
{
driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs(page);
IWebElement right = driver.FindElement(By.Id("right"));
Assert.That(right.Displayed, Is.True, "Failed for " + page);
}
}
[Test]
public void ElementScrollableByOverflowYIsVisible()
{
string[] pages = new string[]{
"overflow/x_hidden_y_scroll.html",
"overflow/x_scroll_y_scroll.html",
"overflow/x_auto_y_scroll.html",
"overflow/x_hidden_y_auto.html",
"overflow/x_scroll_y_auto.html",
"overflow/x_auto_y_auto.html",
};
foreach (string page in pages)
{
driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs(page);
IWebElement bottom = driver.FindElement(By.Id("bottom"));
Assert.That(bottom.Displayed, Is.True, "Failed for " + page);
}
}
[Test]
public void ElementScrollableByOverflowXAndYIsVisible()
{
string[] pages = new string[]{
"overflow/x_scroll_y_scroll.html",
"overflow/x_scroll_y_auto.html",
"overflow/x_auto_y_scroll.html",
"overflow/x_auto_y_auto.html",
};
foreach (string page in pages)
{
driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs(page);
IWebElement bottomRight = driver.FindElement(By.Id("bottom-right"));
Assert.That(bottomRight.Displayed, Is.True, "Failed for " + page);
}
}
[Test]
[IgnoreBrowser(Browser.Opera)]
public void TooSmallAWindowWithOverflowHiddenIsNotAProblem()
{
IWindow window = driver.Manage().Window;
Size originalSize = window.Size;
try
{
// Short in the Y dimension
window.Size = new Size(1024, 500);
driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("overflow-body.html");
IWebElement element = driver.FindElement(By.Name("resultsFrame"));
Assert.That(element.Displayed, Is.True);
}
finally
{
window.Size = originalSize;
}
}
[Test]
public void ShouldShowElementNotVisibleWithHiddenAttribute()
{
string url = EnvironmentManager.Instance.UrlBuilder.WhereIs("hidden.html");
driver.Url = url;
IWebElement element = driver.FindElement(By.Id("singleHidden"));
Assert.That(element.Displayed, Is.False);
}
[Test]
public void ShouldShowElementNotVisibleWhenParentElementHasHiddenAttribute()
{
string url = EnvironmentManager.Instance.UrlBuilder.WhereIs("hidden.html");
driver.Url = url;
IWebElement element = driver.FindElement(By.Id("child"));
Assert.That(element.Displayed, Is.False);
}
[Test]
public void ShouldBeAbleToClickOnElementsWithOpacityZero()
{
if (TestUtilities.IsOldIE(driver))
{
return;
}
driver.Url = clickJackerPage;
IWebElement element = driver.FindElement(By.Id("clickJacker"));
Assert.AreEqual("0", element.GetCssValue("opacity"), "Precondition failed: clickJacker should be transparent");
element.Click();
Assert.AreEqual("1", element.GetCssValue("opacity"));
}
[Test]
[IgnoreBrowser(Browser.Opera)]
public void ShouldBeAbleToSelectOptionsFromAnInvisibleSelect()
{
driver.Url = formsPage;
IWebElement select = driver.FindElement(By.Id("invisi_select"));
ReadOnlyCollection<IWebElement> options = select.FindElements(By.TagName("option"));
IWebElement apples = options[0];
IWebElement oranges = options[1];
Assert.That(apples.Selected, Is.True, "Apples should be selected");
Assert.That(oranges.Selected, Is.False, "Oranges shoudl be selected");
oranges.Click();
Assert.That(apples.Selected, Is.False, "Apples should not be selected");
Assert.That(oranges.Selected, Is.True, "Oranges should be selected");
}
[Test]
public void CorrectlyDetectMapElementsAreShown()
{
driver.Url = mapVisibilityPage;
IWebElement area = driver.FindElement(By.Id("mtgt_unnamed_0"));
bool isShown = area.Displayed;
Assert.That(isShown, Is.True, "The element and the enclosing map should be considered shown.");
}
//------------------------------------------------------------------
// Tests below here are not included in the Java test suite
//------------------------------------------------------------------
[Test]
public void ShouldNotBeAbleToSelectAnElementThatIsNotDisplayed()
{
driver.Url = javascriptPage;
IWebElement element = driver.FindElement(By.Id("untogglable"));
Assert.That(() => element.Click(), Throws.InstanceOf<ElementNotInteractableException>());
}
[Test]
public void ElementsWithOpacityZeroShouldNotBeVisible()
{
driver.Url = clickJackerPage;
IWebElement element = driver.FindElement(By.Id("clickJacker"));
Assert.That(element.Displayed, Is.False);
}
}
}
| |
// Copyright 2015, Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// 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.
// Author: api.anash@gmail.com (Anash P. Oommen)
using Google.Api.Ads.AdWords.Lib;
using Google.Api.Ads.AdWords.v201506;
using System;
using System.Collections.Generic;
using System.IO;
namespace Google.Api.Ads.AdWords.Examples.CSharp.v201506 {
/// <summary>
/// This code example adds sitelinks to a campaign using feed services.
/// To create a campaign, run AddCampaign.cs. To add sitelinks using the
/// simpler ExtensionSetting services, see AddSitelinks.cs.
///
/// Tags: CampaignFeedService.mutate, FeedService.mutate, FeedItemService.mutate,
/// Tags: FeedMappingService.mutate
/// </summary>
public class AddSitelinksUsingFeeds : ExampleBase {
/// <summary>
/// Holds data about sitelinks in a feed.
/// </summary>
class SitelinksDataHolder {
/// <summary>
/// The sitelink feed item IDs.
/// </summary>
List<long> feedItemIds = new List<long>();
/// <summary>
/// Gets the sitelink feed item IDs.
/// </summary>
public List<long> FeedItemIds {
get {
return feedItemIds;
}
}
/// <summary>
/// Gets or sets the feed ID.
/// </summary>
public long FeedId {
get;
set;
}
/// <summary>
/// Gets or sets the link text feed attribute ID.
/// </summary>
public long LinkTextFeedAttributeId {
get;
set;
}
/// <summary>
/// Gets or sets the link URL feed attribute ID.
/// </summary>
public long LinkFinalUrlFeedAttributeId {
get;
set;
}
}
/// <summary>
/// Main method, to run this code example as a standalone application.
/// </summary>
/// <param name="args">The command line arguments.</param>
public static void Main(string[] args) {
AddSitelinksUsingFeeds codeExample = new AddSitelinksUsingFeeds();
Console.WriteLine(codeExample.Description);
try {
long campaignId = long.Parse("INSERT_CAMPAIGN_ID_HERE");
string feedName = "INSERT_FEED_NAME_HERE";
codeExample.Run(new AdWordsUser(), campaignId, feedName);
} catch (Exception ex) {
Console.WriteLine("An exception occurred while running this code example. {0}",
ExampleUtilities.FormatException(ex));
}
}
/// <summary>
/// Returns a description about the code example.
/// </summary>
public override string Description {
get {
return "This code example adds sitelinks to a campaign using feed services. To create a " +
"campaign, run AddCampaign.cs. To add sitelinks using the simpler ExtensionSetting " +
"services, see AddSitelinks.cs.";
}
}
/// <summary>
/// Runs the code example.
/// </summary>
/// <param name="user">The AdWords user.</param>
/// <param name="campaignId">Id of the campaign with which sitelinks are associated.
/// </param>
/// <param name="feedName">Name of the feed to be created.</param>
public void Run(AdWordsUser user, long campaignId, string feedName) {
SitelinksDataHolder sitelinksData = new SitelinksDataHolder();
createSitelinksFeed(user, sitelinksData, feedName);
createSitelinksFeedItems(user, sitelinksData);
createSitelinksFeedMapping(user, sitelinksData);
createSitelinksCampaignFeed(user, sitelinksData, campaignId);
}
private static void createSitelinksFeed(AdWordsUser user, SitelinksDataHolder sitelinksData,
string feedName) {
// Get the FeedService.
FeedService feedService = (FeedService) user.GetService(AdWordsService.v201506.FeedService);
// Create attributes.
FeedAttribute textAttribute = new FeedAttribute();
textAttribute.type = FeedAttributeType.STRING;
textAttribute.name = "Link Text";
FeedAttribute finalUrlAttribute = new FeedAttribute();
finalUrlAttribute.type = FeedAttributeType.URL_LIST;
finalUrlAttribute.name = "Link URL";
// Create the feed.
Feed sitelinksFeed = new Feed();
sitelinksFeed.name = feedName;
sitelinksFeed.attributes = new FeedAttribute[] {textAttribute, finalUrlAttribute};
sitelinksFeed.origin = FeedOrigin.USER;
// Create operation.
FeedOperation operation = new FeedOperation();
operation.operand = sitelinksFeed;
operation.@operator = Operator.ADD;
// Add the feed.
FeedReturnValue result = feedService.mutate(new FeedOperation[] {operation});
Feed savedFeed = result.value[0];
sitelinksData.FeedId = savedFeed.id;
FeedAttribute[] savedAttributes = savedFeed.attributes;
sitelinksData.LinkTextFeedAttributeId = savedAttributes[0].id;
sitelinksData.LinkFinalUrlFeedAttributeId = savedAttributes[1].id;
Console.WriteLine("Feed with name {0} and ID {1} with linkTextAttributeId {2}"
+ " and linkFinalUrlAttributeId {3} was created.", savedFeed.name, savedFeed.id,
savedAttributes[0].id, savedAttributes[1].id);
}
private static void createSitelinksFeedItems(
AdWordsUser user, SitelinksDataHolder siteLinksData) {
// Get the FeedItemService.
FeedItemService feedItemService =
(FeedItemService) user.GetService(AdWordsService.v201506.FeedItemService);
// Create operations to add FeedItems.
FeedItemOperation home =
newSitelinkFeedItemAddOperation(siteLinksData,
"Home", "http://www.example.com");
FeedItemOperation stores =
newSitelinkFeedItemAddOperation(siteLinksData,
"Stores", "http://www.example.com/stores");
FeedItemOperation onSale =
newSitelinkFeedItemAddOperation(siteLinksData,
"On Sale", "http://www.example.com/sale");
FeedItemOperation support =
newSitelinkFeedItemAddOperation(siteLinksData,
"Support", "http://www.example.com/support");
FeedItemOperation products =
newSitelinkFeedItemAddOperation(siteLinksData,
"Products", "http://www.example.com/prods");
FeedItemOperation aboutUs =
newSitelinkFeedItemAddOperation(siteLinksData,
"About Us", "http://www.example.com/about");
FeedItemOperation[] operations =
new FeedItemOperation[] {home, stores, onSale, support, products, aboutUs};
FeedItemReturnValue result = feedItemService.mutate(operations);
foreach (FeedItem item in result.value) {
Console.WriteLine("FeedItem with feedItemId {0} was added.", item.feedItemId);
siteLinksData.FeedItemIds.Add(item.feedItemId);
}
}
// See the Placeholder reference page for a list of all the placeholder types and fields.
// https://developers.google.com/adwords/api/docs/appendix/placeholders.html
private const int PLACEHOLDER_SITELINKS = 1;
// See the Placeholder reference page for a list of all the placeholder types and fields.
private const int PLACEHOLDER_FIELD_SITELINK_LINK_TEXT = 1;
private const int PLACEHOLDER_FIELD_SITELINK_FINAL_URL = 5;
private static void createSitelinksFeedMapping(
AdWordsUser user, SitelinksDataHolder sitelinksData) {
// Get the FeedItemService.
FeedMappingService feedMappingService =
(FeedMappingService) user.GetService(AdWordsService.v201506.FeedMappingService);
// Map the FeedAttributeIds to the fieldId constants.
AttributeFieldMapping linkTextFieldMapping = new AttributeFieldMapping();
linkTextFieldMapping.feedAttributeId = sitelinksData.LinkTextFeedAttributeId;
linkTextFieldMapping.fieldId = PLACEHOLDER_FIELD_SITELINK_LINK_TEXT;
AttributeFieldMapping linkFinalUrlFieldMapping = new AttributeFieldMapping();
linkFinalUrlFieldMapping.feedAttributeId = sitelinksData.LinkFinalUrlFeedAttributeId;
linkFinalUrlFieldMapping.fieldId = PLACEHOLDER_FIELD_SITELINK_FINAL_URL;
// Create the FieldMapping and operation.
FeedMapping feedMapping = new FeedMapping();
feedMapping.placeholderType = PLACEHOLDER_SITELINKS;
feedMapping.feedId = sitelinksData.FeedId;
feedMapping.attributeFieldMappings =
new AttributeFieldMapping[] {linkTextFieldMapping, linkFinalUrlFieldMapping};
FeedMappingOperation operation = new FeedMappingOperation();
operation.operand = feedMapping;
operation.@operator = Operator.ADD;
// Save the field mapping.
FeedMappingReturnValue result =
feedMappingService.mutate(new FeedMappingOperation[] {operation});
foreach (FeedMapping savedFeedMapping in result.value) {
Console.WriteLine(
"Feed mapping with ID {0} and placeholderType {1} was saved for feed with ID {2}.",
savedFeedMapping.feedMappingId, savedFeedMapping.placeholderType,
savedFeedMapping.feedId);
}
}
private static void createSitelinksCampaignFeed(AdWordsUser user,
SitelinksDataHolder sitelinksData, long campaignId) {
// Get the CampaignFeedService.
CampaignFeedService campaignFeedService =
(CampaignFeedService) user.GetService(AdWordsService.v201506.CampaignFeedService);
// Construct a matching function that associates the sitelink feeditems
// to the campaign, and set the device preference to Mobile. See the
// matching function guide at
// https://developers.google.com/adwords/api/docs/guides/feed-matching-functions
// for more details.
string matchingFunctionString = string.Format(@"
AND(
IN(FEED_ITEM_ID, {{{0}}}),
EQUALS(CONTEXT.DEVICE, 'Mobile')
)",
string.Join(",", sitelinksData.FeedItemIds));
CampaignFeed campaignFeed = new CampaignFeed() {
feedId = sitelinksData.FeedId,
campaignId = campaignId,
matchingFunction = new Function() {
functionString = matchingFunctionString
},
// Specifying placeholder types on the CampaignFeed allows the same feed
// to be used for different placeholders in different Campaigns.
placeholderTypes = new int[] { PLACEHOLDER_SITELINKS }
};
CampaignFeedOperation operation = new CampaignFeedOperation();
operation.operand = campaignFeed;
operation.@operator = Operator.ADD;
CampaignFeedReturnValue result =
campaignFeedService.mutate(new CampaignFeedOperation[] {operation});
foreach (CampaignFeed savedCampaignFeed in result.value) {
Console.WriteLine("Campaign with ID {0} was associated with feed with ID {1}",
savedCampaignFeed.campaignId, savedCampaignFeed.feedId);
}
}
private static FeedItemOperation newSitelinkFeedItemAddOperation(
SitelinksDataHolder sitelinksData, String text, String finalUrl) {
// Create the FeedItemAttributeValues for our text values.
FeedItemAttributeValue linkTextAttributeValue = new FeedItemAttributeValue();
linkTextAttributeValue.feedAttributeId = sitelinksData.LinkTextFeedAttributeId;
linkTextAttributeValue.stringValue = text;
FeedItemAttributeValue linkFinalUrlAttributeValue = new FeedItemAttributeValue();
linkFinalUrlAttributeValue.feedAttributeId = sitelinksData.LinkFinalUrlFeedAttributeId;
linkFinalUrlAttributeValue.stringValues = new string[] { finalUrl };
// Create the feed item and operation.
FeedItem item = new FeedItem();
item.feedId = sitelinksData.FeedId;
item.attributeValues =
new FeedItemAttributeValue[] {linkTextAttributeValue, linkFinalUrlAttributeValue};
FeedItemOperation operation = new FeedItemOperation();
operation.operand = item;
operation.@operator = Operator.ADD;
return operation;
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="RegexMatch.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
// Match is the result class for a regex search.
// It returns the location, length, and substring for
// the entire match as well as every captured group.
// Match is also used during the search to keep track of each capture for each group. This is
// done using the "_matches" array. _matches[x] represents an array of the captures for group x.
// This array consists of start and length pairs, and may have empty entries at the end. _matchcount[x]
// stores how many captures a group has. Note that _matchcount[x]*2 is the length of all the valid
// values in _matches. _matchcount[x]*2-2 is the Start of the last capture, and _matchcount[x]*2-1 is the
// Length of the last capture
//
// For example, if group 2 has one capture starting at position 4 with length 6,
// _matchcount[2] == 1
// _matches[2][0] == 4
// _matches[2][1] == 6
//
// Values in the _matches array can also be negative. This happens when using the balanced match
// construct, "(?<start-end>...)". When the "end" group matches, a capture is added for both the "start"
// and "end" groups. The capture added for "start" receives the negative values, and these values point to
// the next capture to be balanced. They do NOT point to the capture that "end" just balanced out. The negative
// values are indices into the _matches array transformed by the formula -3-x. This formula also untransforms.
//
namespace System.Text.RegularExpressions {
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Security.Permissions;
using System.Globalization;
/// <devdoc>
/// <para>
/// Represents
/// the results from a single regular expression match.
/// </para>
/// </devdoc>
#if !SILVERLIGHT
[ Serializable() ]
#endif
public class Match : Group {
internal static Match _empty = new Match(null, 1, String.Empty, 0, 0, 0);
internal GroupCollection _groupcoll;
// input to the match
internal Regex _regex;
internal int _textbeg;
internal int _textpos;
internal int _textend;
internal int _textstart;
// output from the match
internal int[][] _matches;
internal int[] _matchcount;
internal bool _balancing; // whether we've done any balancing with this match. If we
// have done balancing, we'll need to do extra work in Tidy().
/// <devdoc>
/// <para>
/// Returns an empty Match object.
/// </para>
/// </devdoc>
public static Match Empty {
get {
return _empty;
}
}
/*
* Nonpublic constructor
*/
internal Match(Regex regex, int capcount, String text, int begpos, int len, int startpos)
: base(text, new int[2], 0) {
_regex = regex;
_matchcount = new int[capcount];
_matches = new int[capcount][];
_matches[0] = _caps;
_textbeg = begpos;
_textend = begpos + len;
_textstart = startpos;
_balancing = false;
// No need for an exception here. This is only called internally, so we'll use an Assert instead
System.Diagnostics.Debug.Assert(!(_textbeg < 0 || _textstart < _textbeg || _textend < _textstart || _text.Length < _textend),
"The parameters are out of range.");
}
/*
* Nonpublic set-text method
*/
internal virtual void Reset(Regex regex, String text, int textbeg, int textend, int textstart) {
_regex = regex;
_text = text;
_textbeg = textbeg;
_textend = textend;
_textstart = textstart;
for (int i = 0; i < _matchcount.Length; i++) {
_matchcount[i] = 0;
}
_balancing = false;
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public virtual GroupCollection Groups {
get {
if (_groupcoll == null)
_groupcoll = new GroupCollection(this, null);
return _groupcoll;
}
}
/*
* Returns the next match
*/
/// <devdoc>
/// <para>Returns a new Match with the results for the next match, starting
/// at the position at which the last match ended (at the character beyond the last
/// matched character).</para>
/// </devdoc>
public Match NextMatch() {
if (_regex == null)
return this;
return _regex.Run(false, _length, _text, _textbeg, _textend - _textbeg, _textpos);
}
/*
* Return the result string (using the replacement pattern)
*/
/// <devdoc>
/// <para>
/// Returns the expansion of the passed replacement pattern. For
/// example, if the replacement pattern is ?$1$2?, Result returns the concatenation
/// of Group(1).ToString() and Group(2).ToString().
/// </para>
/// </devdoc>
public virtual String Result(String replacement) {
RegexReplacement repl;
if (replacement == null)
throw new ArgumentNullException("replacement");
if (_regex == null)
throw new NotSupportedException(SR.GetString(SR.NoResultOnFailed));
repl = (RegexReplacement)_regex.replref.Get();
if (repl == null || !repl.Pattern.Equals(replacement)) {
repl = RegexParser.ParseReplacement(replacement, _regex.caps, _regex.capsize, _regex.capnames, _regex.roptions);
_regex.replref.Cache(repl);
}
return repl.Replacement(this);
}
/*
* Used by the replacement code
*/
internal virtual String GroupToStringImpl(int groupnum) {
int c = _matchcount[groupnum];
if (c == 0)
return String.Empty;
int [] matches = _matches[groupnum];
return _text.Substring(matches[(c - 1) * 2], matches[(c * 2) - 1]);
}
/*
* Used by the replacement code
*/
internal String LastGroupToStringImpl() {
return GroupToStringImpl(_matchcount.Length - 1);
}
/*
* Convert to a thread-safe object by precomputing cache contents
*/
/// <devdoc>
/// <para>
/// Returns a Match instance equivalent to the one supplied that is safe to share
/// between multiple threads.
/// </para>
/// </devdoc>
#if !SILVERLIGHT
#if !DISABLE_CAS_USE
[HostProtection(Synchronization=true)]
#endif
static public Match Synchronized(Match inner) {
#else
static internal Match Synchronized(Match inner) {
#endif
if (inner == null)
throw new ArgumentNullException("inner");
int numgroups = inner._matchcount.Length;
// Populate all groups by looking at each one
for (int i = 0; i < numgroups; i++) {
Group group = inner.Groups[i];
// Depends on the fact that Group.Synchronized just
// operates on and returns the same instance
System.Text.RegularExpressions.Group.Synchronized(group);
}
return inner;
}
/*
* Nonpublic builder: add a capture to the group specified by "cap"
*/
internal virtual void AddMatch(int cap, int start, int len) {
int capcount;
if (_matches[cap] == null)
_matches[cap] = new int[2];
capcount = _matchcount[cap];
if (capcount * 2 + 2 > _matches[cap].Length) {
int[] oldmatches = _matches[cap];
int[] newmatches = new int[capcount * 8];
for (int j = 0; j < capcount * 2; j++)
newmatches[j] = oldmatches[j];
_matches[cap] = newmatches;
}
_matches[cap][capcount * 2] = start;
_matches[cap][capcount * 2 + 1] = len;
_matchcount[cap] = capcount + 1;
}
/*
* Nonpublic builder: Add a capture to balance the specified group. This is used by the
balanced match construct. (?<foo-foo2>...)
If there were no such thing as backtracking, this would be as simple as calling RemoveMatch(cap).
However, since we have backtracking, we need to keep track of everything.
*/
internal virtual void BalanceMatch(int cap) {
int capcount;
int target;
_balancing = true;
// we'll look at the last capture first
capcount = _matchcount[cap];
target = capcount * 2 - 2;
// first see if it is negative, and therefore is a reference to the next available
// capture group for balancing. If it is, we'll reset target to point to that capture.
if (_matches[cap][target] < 0)
target = -3 - _matches[cap][target];
// move back to the previous capture
target -= 2;
// if the previous capture is a reference, just copy that reference to the end. Otherwise, point to it.
if (target >= 0 && _matches[cap][target] < 0)
AddMatch(cap, _matches[cap][target], _matches[cap][target+1]);
else
AddMatch(cap, -3 - target, -4 - target /* == -3 - (target + 1) */ );
}
/*
* Nonpublic builder: removes a group match by capnum
*/
internal virtual void RemoveMatch(int cap) {
_matchcount[cap]--;
}
/*
* Nonpublic: tells if a group was matched by capnum
*/
internal virtual bool IsMatched(int cap) {
return cap < _matchcount.Length && _matchcount[cap] > 0 && _matches[cap][_matchcount[cap] * 2 - 1] != (-3 + 1);
}
/*
* Nonpublic: returns the index of the last specified matched group by capnum
*/
internal virtual int MatchIndex(int cap) {
int i = _matches[cap][_matchcount[cap] * 2 - 2];
if (i >= 0)
return i;
return _matches[cap][-3 - i];
}
/*
* Nonpublic: returns the length of the last specified matched group by capnum
*/
internal virtual int MatchLength(int cap) {
int i = _matches[cap][_matchcount[cap] * 2 - 1];
if (i >= 0)
return i;
return _matches[cap][-3 - i];
}
/*
* Nonpublic: tidy the match so that it can be used as an immutable result
*/
internal virtual void Tidy(int textpos) {
int[] interval;
interval = _matches[0];
_index = interval[0];
_length = interval[1];
_textpos = textpos;
_capcount = _matchcount[0];
if (_balancing) {
// The idea here is that we want to compact all of our unbalanced captures. To do that we
// use j basically as a count of how many unbalanced captures we have at any given time
// (really j is an index, but j/2 is the count). First we skip past all of the real captures
// until we find a balance captures. Then we check each subsequent entry. If it's a balance
// capture (it's negative), we decrement j. If it's a real capture, we increment j and copy
// it down to the last free position.
for (int cap = 0; cap < _matchcount.Length; cap++) {
int limit;
int[] matcharray;
limit = _matchcount[cap] * 2;
matcharray = _matches[cap];
int i = 0;
int j;
for (i = 0; i < limit; i++) {
if (matcharray[i] < 0)
break;
}
for (j = i; i < limit; i++) {
if (matcharray[i] < 0) {
// skip negative values
j--;
}
else {
// but if we find something positive (an actual capture), copy it back to the last
// unbalanced position.
if (i != j)
matcharray[j] = matcharray[i];
j++;
}
}
_matchcount[cap] = j / 2;
}
_balancing = false;
}
}
#if DBG
/// <internalonly/>
/// <devdoc>
/// </devdoc>
public bool Debug {
get {
if (_regex == null)
return false;
return _regex.Debug;
}
}
/// <internalonly/>
/// <devdoc>
/// </devdoc>
internal virtual void Dump() {
int i,j;
for (i = 0; i < _matchcount.Length; i++) {
System.Diagnostics.Debug.WriteLine("Capnum " + i.ToString(CultureInfo.InvariantCulture) + ":");
for (j = 0; j < _matchcount[i]; j++) {
String text = "";
if (_matches[i][j * 2] >= 0)
text = _text.Substring(_matches[i][j * 2], _matches[i][j * 2 + 1]);
System.Diagnostics.Debug.WriteLine(" (" + _matches[i][j * 2].ToString(CultureInfo.InvariantCulture) + "," + _matches[i][j * 2 + 1].ToString(CultureInfo.InvariantCulture) + ") " + text);
}
}
}
#endif
}
/*
* MatchSparse is for handling the case where slots are
* sparsely arranged (e.g., if somebody says use slot 100000)
*/
internal class MatchSparse : Match {
// the lookup hashtable
#if SILVERLIGHT
new internal Dictionary<Int32, Int32> _caps;
#else
new internal Hashtable _caps;
#endif
/*
* Nonpublic constructor
*/
#if SILVERLIGHT
internal MatchSparse(Regex regex, Dictionary<Int32, Int32> caps, int capcount,
#else
internal MatchSparse(Regex regex, Hashtable caps, int capcount,
#endif
String text, int begpos, int len, int startpos)
: base(regex, capcount, text, begpos, len, startpos) {
_caps = caps;
}
public override GroupCollection Groups {
get {
if (_groupcoll == null)
_groupcoll = new GroupCollection(this, _caps);
return _groupcoll;
}
}
#if DBG
internal override void Dump() {
if (_caps != null) {
#if SILVERLIGHT
IEnumerator<Int32> e = _caps.Keys.GetEnumerator();
#else
IEnumerator e = _caps.Keys.GetEnumerator();
#endif
while (e.MoveNext()) {
System.Diagnostics.Debug.WriteLine("Slot " + e.Current.ToString() + " -> " + _caps[e.Current].ToString());
}
}
base.Dump();
}
#endif
}
}
| |
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
namespace App.Data.Migrations
{
[DbContext(typeof(ApplicationDbContext))]
[Migration("00000000000000_CreateIdentitySchema")]
partial class CreateIdentitySchema
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
modelBuilder
.HasAnnotation("ProductVersion", "1.0.0-rc3")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRole", b =>
{
b.Property<string>("Id");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken();
b.Property<string>("Name")
.HasAnnotation("MaxLength", 256);
b.Property<string>("NormalizedName")
.HasAnnotation("MaxLength", 256);
b.HasKey("Id");
b.HasIndex("NormalizedName")
.HasName("RoleNameIndex");
b.ToTable("AspNetRoles");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRoleClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ClaimType");
b.Property<string>("ClaimValue");
b.Property<string>("RoleId")
.IsRequired();
b.HasKey("Id");
b.HasIndex("RoleId");
b.ToTable("AspNetRoleClaims");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ClaimType");
b.Property<string>("ClaimValue");
b.Property<string>("UserId")
.IsRequired();
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("AspNetUserClaims");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserLogin<string>", b =>
{
b.Property<string>("LoginProvider");
b.Property<string>("ProviderKey");
b.Property<string>("ProviderDisplayName");
b.Property<string>("UserId")
.IsRequired();
b.HasKey("LoginProvider", "ProviderKey");
b.HasIndex("UserId");
b.ToTable("AspNetUserLogins");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserRole<string>", b =>
{
b.Property<string>("UserId");
b.Property<string>("RoleId");
b.HasKey("UserId", "RoleId");
b.HasIndex("RoleId");
b.HasIndex("UserId");
b.ToTable("AspNetUserRoles");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserToken<string>", b =>
{
b.Property<string>("UserId");
b.Property<string>("LoginProvider");
b.Property<string>("Name");
b.Property<string>("Value");
b.HasKey("UserId", "LoginProvider", "Name");
b.ToTable("AspNetUserTokens");
});
modelBuilder.Entity("WebApplication.Models.ApplicationUser", b =>
{
b.Property<string>("Id");
b.Property<int>("AccessFailedCount");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken();
b.Property<string>("Email")
.HasAnnotation("MaxLength", 256);
b.Property<bool>("EmailConfirmed");
b.Property<bool>("LockoutEnabled");
b.Property<DateTimeOffset?>("LockoutEnd");
b.Property<string>("NormalizedEmail")
.HasAnnotation("MaxLength", 256);
b.Property<string>("NormalizedUserName")
.HasAnnotation("MaxLength", 256);
b.Property<string>("PasswordHash");
b.Property<string>("PhoneNumber");
b.Property<bool>("PhoneNumberConfirmed");
b.Property<string>("SecurityStamp");
b.Property<bool>("TwoFactorEnabled");
b.Property<string>("UserName")
.HasAnnotation("MaxLength", 256);
b.HasKey("Id");
b.HasIndex("NormalizedEmail")
.HasName("EmailIndex");
b.HasIndex("NormalizedUserName")
.IsUnique()
.HasName("UserNameIndex");
b.ToTable("AspNetUsers");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRoleClaim<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRole")
.WithMany("Claims")
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserClaim<string>", b =>
{
b.HasOne("WebApplication.Models.ApplicationUser")
.WithMany("Claims")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserLogin<string>", b =>
{
b.HasOne("WebApplication.Models.ApplicationUser")
.WithMany("Logins")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserRole<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRole")
.WithMany("Users")
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade);
b.HasOne("WebApplication.Models.ApplicationUser")
.WithMany("Roles")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
}
}
}
| |
// 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.CodeAnalysis;
using System.Runtime;
using System.ServiceModel.Diagnostics;
using System.Xml;
namespace System.ServiceModel.Channels
{
internal class RequestReplyCorrelator : IRequestReplyCorrelator
{
private Dictionary<Key, object> _states;
internal RequestReplyCorrelator()
{
_states = new Dictionary<Key, object>();
}
void IRequestReplyCorrelator.Add<T>(Message request, T state)
{
UniqueId messageId = request.Headers.MessageId;
Type stateType = typeof(T);
Key key = new Key(messageId, stateType);
// add the correlator key to the request, this will be needed for cleaning up the correlator table in case of
// channel aborting or faulting while there are pending requests
ICorrelatorKey value = state as ICorrelatorKey;
if (value != null)
{
value.RequestCorrelatorKey = key;
}
lock (_states)
{
_states.Add(key, state);
}
}
T IRequestReplyCorrelator.Find<T>(Message reply, bool remove)
{
UniqueId relatesTo = GetRelatesTo(reply);
Type stateType = typeof(T);
Key key = new Key(relatesTo, stateType);
T value;
lock (_states)
{
value = (T)_states[key];
if (remove)
{
_states.Remove(key);
}
}
return value;
}
// This method is used to remove the request from the correlator table when the
// reply is lost. This will avoid leaking the correlator table in cases where the
// channel faults or aborts while there are pending requests.
internal void RemoveRequest(ICorrelatorKey request)
{
Fx.Assert(request != null, "request cannot be null");
if (request.RequestCorrelatorKey != null)
{
lock (_states)
{
_states.Remove(request.RequestCorrelatorKey);
}
}
}
private UniqueId GetRelatesTo(Message reply)
{
UniqueId relatesTo = reply.Headers.RelatesTo;
if (relatesTo == null)
{
throw TraceUtility.ThrowHelperError(new ArgumentException(SR.SuppliedMessageIsNotAReplyItHasNoRelatesTo0), reply);
}
return relatesTo;
}
internal static bool AddressReply(Message reply, Message request)
{
ReplyToInfo info = RequestReplyCorrelator.ExtractReplyToInfo(request);
return RequestReplyCorrelator.AddressReply(reply, info);
}
internal static bool AddressReply(Message reply, ReplyToInfo info)
{
EndpointAddress destination = null;
if (info.HasFaultTo && (reply.IsFault))
{
destination = info.FaultTo;
}
else if (info.HasReplyTo)
{
destination = info.ReplyTo;
}
else if (reply.Version.Addressing == AddressingVersion.WSAddressingAugust2004)
{
if (info.HasFrom)
{
destination = info.From;
}
else
{
destination = EndpointAddress.AnonymousAddress;
}
}
if (destination != null)
{
destination.ApplyTo(reply);
return !destination.IsNone;
}
else
{
return true;
}
}
internal static ReplyToInfo ExtractReplyToInfo(Message message)
{
return new ReplyToInfo(message);
}
internal static void PrepareRequest(Message request)
{
MessageHeaders requestHeaders = request.Headers;
if (requestHeaders.MessageId == null)
{
requestHeaders.MessageId = new UniqueId();
}
request.Properties.AllowOutputBatching = false;
if (TraceUtility.PropagateUserActivity || TraceUtility.ShouldPropagateActivity)
{
TraceUtility.AddAmbientActivityToMessage(request);
}
}
internal static void PrepareReply(Message reply, UniqueId messageId)
{
if (object.ReferenceEquals(messageId, null))
{
throw TraceUtility.ThrowHelperError(new InvalidOperationException(SR.MissingMessageID), reply);
}
MessageHeaders replyHeaders = reply.Headers;
if (object.ReferenceEquals(replyHeaders.RelatesTo, null))
{
replyHeaders.RelatesTo = messageId;
}
if (TraceUtility.PropagateUserActivity || TraceUtility.ShouldPropagateActivity)
{
TraceUtility.AddAmbientActivityToMessage(reply);
}
}
internal static void PrepareReply(Message reply, Message request)
{
UniqueId messageId = request.Headers.MessageId;
if (messageId != null)
{
MessageHeaders replyHeaders = reply.Headers;
if (object.ReferenceEquals(replyHeaders.RelatesTo, null))
{
replyHeaders.RelatesTo = messageId;
}
}
if (TraceUtility.PropagateUserActivity || TraceUtility.ShouldPropagateActivity)
{
TraceUtility.AddAmbientActivityToMessage(reply);
}
}
internal struct ReplyToInfo
{
private readonly EndpointAddress _replyTo;
internal ReplyToInfo(Message message)
{
FaultTo = message.Headers.FaultTo;
_replyTo = message.Headers.ReplyTo;
if (message.Version.Addressing == AddressingVersion.WSAddressingAugust2004)
{
From = message.Headers.From;
}
else
{
From = null;
}
}
internal EndpointAddress FaultTo { get; }
internal EndpointAddress From { get; }
internal bool HasFaultTo
{
get { return !IsTrivial(FaultTo); }
}
internal bool HasFrom
{
get { return !IsTrivial(From); }
}
internal bool HasReplyTo
{
get { return !IsTrivial(ReplyTo); }
}
internal EndpointAddress ReplyTo
{
get { return _replyTo; }
}
private bool IsTrivial(EndpointAddress address)
{
// Note: even if address.IsAnonymous, it may have identity, reference parameters, etc.
return (address == null) || (address == EndpointAddress.AnonymousAddress);
}
}
internal class Key
{
internal UniqueId MessageId;
internal Type StateType;
internal Key(UniqueId messageId, Type stateType)
{
MessageId = messageId;
StateType = stateType;
}
public override bool Equals(object obj)
{
Key other = obj as Key;
if (other == null)
{
return false;
}
return other.MessageId == MessageId && other.StateType == StateType;
}
[SuppressMessage(FxCop.Category.Usage, "CA2303:FlagTypeGetHashCode", Justification = "The hashcode is not used for identity purposes for embedded types.")]
public override int GetHashCode()
{
return MessageId.GetHashCode() ^ StateType.GetHashCode();
}
public override string ToString()
{
return typeof(Key).ToString() + ": {" + MessageId + ", " + StateType.ToString() + "}";
}
}
}
}
| |
/*
* 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.Threading;
using log4net;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using BlockingQueue = OpenSim.Framework.BlockingQueue<OpenSim.Region.Framework.Interfaces.ITextureSender>;
using OpenSim.Services.Interfaces;
namespace OpenSim.Region.CoreModules.Agent.TextureDownload
{
public class TextureDownloadModule : IRegionModule
{
private static readonly ILog m_log
= LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
/// <summary>
/// There is one queue for all textures waiting to be sent, regardless of the requesting user.
/// </summary>
private readonly BlockingQueue m_queueSenders
= new BlockingQueue();
/// <summary>
/// Each user has their own texture download service.
/// </summary>
private readonly Dictionary<UUID, UserTextureDownloadService> m_userTextureServices =
new Dictionary<UUID, UserTextureDownloadService>();
private Scene m_scene;
private List<Scene> m_scenes = new List<Scene>();
public TextureDownloadModule()
{
}
#region IRegionModule Members
public void Initialise(Scene scene, IConfigSource config)
{
if (m_scene == null)
{
//m_log.Debug("Creating Texture download module");
m_scene = scene;
//m_thread = new Thread(new ThreadStart(ProcessTextureSenders));
//m_thread.Name = "ProcessTextureSenderThread";
//m_thread.IsBackground = true;
//m_thread.Start();
//ThreadTracker.Add(m_thread);
}
if (!m_scenes.Contains(scene))
{
m_scenes.Add(scene);
m_scene = scene;
m_scene.EventManager.OnNewClient += NewClient;
m_scene.EventManager.OnRemovePresence += EventManager_OnRemovePresence;
}
}
public void PostInitialise()
{
}
public void Close()
{
}
public string Name
{
get { return "TextureDownloadModule"; }
}
public bool IsSharedModule
{
get { return false; }
}
#endregion
/// <summary>
/// Cleanup the texture service related objects for the removed presence.
/// </summary>
/// <param name="agentId"> </param>
private void EventManager_OnRemovePresence(UUID agentId)
{
UserTextureDownloadService textureService;
lock (m_userTextureServices)
{
if (m_userTextureServices.TryGetValue(agentId, out textureService))
{
textureService.Close();
//m_log.DebugFormat("[TEXTURE MODULE]: Removing UserTextureServices from {0}", m_scene.RegionInfo.RegionName);
m_userTextureServices.Remove(agentId);
}
}
}
public void NewClient(IClientAPI client)
{
UserTextureDownloadService textureService;
lock (m_userTextureServices)
{
if (m_userTextureServices.TryGetValue(client.AgentId, out textureService))
{
textureService.Close();
//m_log.DebugFormat("[TEXTURE MODULE]: Removing outdated UserTextureServices from {0}", m_scene.RegionInfo.RegionName);
m_userTextureServices.Remove(client.AgentId);
}
m_userTextureServices.Add(client.AgentId, new UserTextureDownloadService(client, m_scene, m_queueSenders));
}
client.OnRequestTexture += TextureRequest;
}
/// I'm commenting this out, and replacing it with the implementation below, which
/// may return a null value. This is necessary for avoiding race conditions
/// recreating UserTextureServices for clients that have just been closed.
/// That behavior of always returning a UserTextureServices was causing the
/// A-B-A problem (mantis #2855).
///
///// <summary>
///// Does this user have a registered texture download service?
///// </summary>
///// <param name="userID"></param>
///// <param name="textureService"></param>
///// <returns>Always returns true, since a service is created if one does not already exist</returns>
//private bool TryGetUserTextureService(
// IClientAPI client, out UserTextureDownloadService textureService)
//{
// lock (m_userTextureServices)
// {
// if (m_userTextureServices.TryGetValue(client.AgentId, out textureService))
// {
// //m_log.DebugFormat("[TEXTURE MODULE]: Found existing UserTextureServices in ", m_scene.RegionInfo.RegionName);
// return true;
// }
// m_log.DebugFormat("[TEXTURE MODULE]: Creating new UserTextureServices in ", m_scene.RegionInfo.RegionName);
// textureService = new UserTextureDownloadService(client, m_scene, m_queueSenders);
// m_userTextureServices.Add(client.AgentId, textureService);
// return true;
// }
//}
/// <summary>
/// Does this user have a registered texture download service?
/// </summary>
/// <param name="userID"></param>
/// <param name="textureService"></param>
/// <returns>A UserTextureDownloadService or null in the output parameter, and true or false accordingly.</returns>
private bool TryGetUserTextureService(IClientAPI client, out UserTextureDownloadService textureService)
{
lock (m_userTextureServices)
{
if (m_userTextureServices.TryGetValue(client.AgentId, out textureService))
{
//m_log.DebugFormat("[TEXTURE MODULE]: Found existing UserTextureServices in ", m_scene.RegionInfo.RegionName);
return true;
}
textureService = null;
return false;
}
}
/// <summary>
/// Start the process of requesting a given texture.
/// </summary>
/// <param name="sender"> </param>
/// <param name="e"></param>
public void TextureRequest(Object sender, TextureRequestArgs e)
{
IClientAPI client = (IClientAPI)sender;
if (e.Priority == 1016001f) // Preview
{
if (client.Scene is Scene)
{
Scene scene = (Scene)client.Scene;
ScenePresence sp = scene.GetScenePresence(client.AgentId);
if (sp == null) // Deny unknown user
return;
IInventoryService invService = scene.InventoryService;
if (invService.GetRootFolder(client.AgentId) == null) // Deny no inventory
return;
// Diva 2009-08-13: this test doesn't make any sense to many devs
//if (profile.UserProfile.GodLevel < 200 && profile.RootFolder.FindAsset(e.RequestedAssetID) == null) // Deny if not owned
//{
// m_log.WarnFormat("[TEXTURE]: user {0} doesn't have permissions to texture {1}");
// return;
//}
m_log.Debug("Texture preview");
}
}
UserTextureDownloadService textureService;
if (TryGetUserTextureService(client, out textureService))
{
textureService.HandleTextureRequest(e);
}
}
/// <summary>
/// Entry point for the thread dedicated to processing the texture queue.
/// </summary>
public void ProcessTextureSenders()
{
ITextureSender sender = null;
try
{
while (true)
{
sender = m_queueSenders.Dequeue();
if (sender.Cancel)
{
TextureSent(sender);
sender.Cancel = false;
}
else
{
bool finished = sender.SendTexturePacket();
if (finished)
{
TextureSent(sender);
}
else
{
m_queueSenders.Enqueue(sender);
}
}
// Make sure that any sender we currently have can get garbage collected
sender = null;
//m_log.InfoFormat("[TEXTURE] Texture sender queue size: {0}", m_queueSenders.Count());
}
}
catch (Exception e)
{
// TODO: Let users in the sim and those entering it and possibly an external watchdog know what has happened
m_log.ErrorFormat(
"[TEXTURE]: Texture send thread terminating with exception. PLEASE REBOOT YOUR SIM - TEXTURES WILL NOT BE AVAILABLE UNTIL YOU DO. Exception is {0}",
e);
}
}
/// <summary>
/// Called when the texture has finished sending.
/// </summary>
/// <param name="sender"></param>
private void TextureSent(ITextureSender sender)
{
sender.Sending = false;
//m_log.DebugFormat("[TEXTURE]: Removing download stat for {0}", sender.assetID);
m_scene.StatsReporter.AddPendingDownloads(-1);
}
}
}
| |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#if !SILVERLIGHT
using System.Diagnostics.Contracts;
using System;
namespace System.Collections.Specialized
{
// Summary:
// Represents a collection of strings.
//[Serializable]
public class StringCollection : IList, ICollection, IEnumerable
{
// Summary:
// Initializes a new instance of the System.Collections.Specialized.StringCollection
// class.
//public StringCollection();
// Summary:
// Gets the number of strings contained in the System.Collections.Specialized.StringCollection.
//
// Returns:
// The number of strings contained in the System.Collections.Specialized.StringCollection.
extern public virtual int Count { get; }
//
// Summary:
// Gets a value indicating whether the System.Collections.Specialized.StringCollection
// is read-only.
//
// Returns:
// This property always returns false.
extern public bool IsReadOnly { get; }
//
// Summary:
// Gets a value indicating whether access to the System.Collections.Specialized.StringCollection
// is synchronized (thread safe).
//
// Returns:
// This property always returns false.
public bool IsSynchronized {
get
{
Contract.Ensures(!Contract.Result<bool>());
return false;
}
}
//
// Summary:
// Gets an object that can be used to synchronize access to the System.Collections.Specialized.StringCollection.
//
// Returns:
// An object that can be used to synchronize access to the System.Collections.Specialized.StringCollection.
extern public object SyncRoot { get; }
// Summary:
// Gets or sets the element at the specified index.
//
// Parameters:
// index:
// The zero-based index of the entry to get or set.
//
// Returns:
// The element at the specified index.
//
// Exceptions:
// System.ArgumentOutOfRangeException:
// index is less than zero. -or- index is equal to or greater than System.Collections.Specialized.StringCollection.Count.
public string this[int index]
{
get
{
Contract.Requires(index >= 0);
Contract.Requires(index < this.Count);
return default(string);
}
set {
Contract.Requires(index >= 0);
Contract.Requires(index < this.Count);
}
}
// Summary:
// Adds a string to the end of the System.Collections.Specialized.StringCollection.
//
// Parameters:
// value:
// The string to add to the end of the System.Collections.Specialized.StringCollection.
// The value can be null.
//
// Returns:
// The zero-based index at which the new element is inserted.
public int Add(string value)
{
Contract.Ensures(Contract.Result<int>() == Contract.OldValue(Count));
Contract.Ensures(this.Count == Contract.OldValue(this.Count) + 1);
return default(int);
}
//
// Summary:
// Copies the elements of a string array to the end of the System.Collections.Specialized.StringCollection.
//
// Parameters:
// value:
// An array of strings to add to the end of the System.Collections.Specialized.StringCollection.
// The array itself can not be null but it can contain elements that are null.
//
// Exceptions:
// System.ArgumentNullException:
// value is null.
public void AddRange(string[] value)
{
Contract.Requires(value != null);
}
//
// Summary:
// Removes all the strings from the System.Collections.Specialized.StringCollection.
extern public void Clear();
//
// Summary:
// Determines whether the specified string is in the System.Collections.Specialized.StringCollection.
//
// Parameters:
// value:
// The string to locate in the System.Collections.Specialized.StringCollection.
// The value can be null.
//
// Returns:
// true if value is found in the System.Collections.Specialized.StringCollection;
// otherwise, false.
[Pure]
public bool Contains(string value)
{
Contract.Ensures(!Contract.Result<bool>() || Count > 0);
return default(bool);
}
//
// Summary:
// Copies the entire System.Collections.Specialized.StringCollection values
// to a one-dimensional array of strings, starting at the specified index of
// the target array.
//
// Parameters:
// array:
// The one-dimensional array of strings that is the destination of the elements
// copied from System.Collections.Specialized.StringCollection. The System.Array
// must have zero-based indexing.
//
// index:
// The zero-based index in array at which copying begins.
//
// Exceptions:
// System.ArgumentNullException:
// array is null.
//
// System.ArgumentOutOfRangeException:
// index is less than zero.
//
// System.ArgumentException:
// array is multidimensional. -or- index is equal to or greater than the length
// of array. -or- The number of elements in the source System.Collections.Specialized.StringCollection
// is greater than the available space from index to the end of the destination
// array.
//
// System.InvalidCastException:
// The type of the source System.Collections.Specialized.StringCollection cannot
// be cast automatically to the type of the destination array.
extern public void CopyTo(string[] array, int index);
extern void System.Collections.ICollection.CopyTo(Array array, int index);
extern IEnumerator IEnumerable.GetEnumerator();
extern int IList.Add(object value);
extern bool IList.Contains(object value);
extern int IList.IndexOf(object value);
extern void IList.Insert(int index, object value);
extern void IList.Remove(object value);
extern bool IList.IsFixedSize { get; }
extern bool IList.IsReadOnly { get; }
extern object IList.this[int index] { get; set; }
//
// Summary:
// Returns a System.Collections.Specialized.StringEnumerator that iterates through
// the System.Collections.Specialized.StringCollection.
//
// Returns:
// A System.Collections.Specialized.StringEnumerator for the System.Collections.Specialized.StringCollection.
public StringEnumerator GetEnumerator()
{
Contract.Ensures(Contract.Result<StringEnumerator>() != null);
return default(StringEnumerator);
}
//
// Summary:
// Searches for the specified string and returns the zero-based index of the
// first occurrence within the System.Collections.Specialized.StringCollection.
//
// Parameters:
// value:
// The string to locate. The value can be null.
//
// Returns:
// The zero-based index of the first occurrence of value in the System.Collections.Specialized.StringCollection,
// if found; otherwise, -1.
public int IndexOf(string value)
{
Contract.Ensures(Contract.Result<int>() >= -1);
Contract.Ensures(Contract.Result<int>() < this.Count);
return default(int);
}
//
// Summary:
// Inserts a string into the System.Collections.Specialized.StringCollection
// at the specified index.
//
// Parameters:
// index:
// The zero-based index at which value is inserted.
//
// value:
// The string to insert. The value can be null.
//
// Exceptions:
// System.ArgumentOutOfRangeException:
// index is less than zero. -or- index greater than System.Collections.Specialized.StringCollection.Count.
public void Insert(int index, string value)
{
Contract.Requires(index >= 0);
Contract.Requires(index <= Count);
Contract.Ensures(Count == Contract.OldValue(Count) + 1);
}
//
// Summary:
// Removes the first occurrence of a specific string from the System.Collections.Specialized.StringCollection.
//
// Parameters:
// value:
// The string to remove from the System.Collections.Specialized.StringCollection.
// The value can be null.
extern public void Remove(string value);
//
// Summary:
// Removes the string at the specified index of the System.Collections.Specialized.StringCollection.
//
// Parameters:
// index:
// The zero-based index of the string to remove.
//
// Exceptions:
// System.ArgumentOutOfRangeException:
// index is less than zero. -or- index is equal to or greater than System.Collections.Specialized.StringCollection.Count.
extern public void RemoveAt(int index);
}
}
#endif
| |
/*
* MathObject.cs - The JScript Math object.
*
* Copyright (C) 2003 Southern Storm Software, Pty Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
namespace Microsoft.JScript
{
using System;
public class MathObject : JSObject
{
// e, the base of natural algorithms
public const double E = 2.7182818284590452354;
// the natural logarithm of 10
public const double LN10 = 2.302585092994046;
// the natural logarithm of 2
public const double LN2 = 0.6931471805599453;
// the base-2 logarithm of e
public const double LOG2E = 1.4426950408889634;
// the base-10 logarithm of e
public const double LOG10E = 0.4342944819032518;
// pi - the ratio of the circumference of a circle to its diameter
public const double PI = 3.14159265358979323846;
// the square root of 1/2
public const double SQRT1_2 = 0.7071067811865476;
// the square root of 2
public const double SQRT2 = 1.4142135623730951;
// internal state
private static Random rnd;
// static constructor
static MathObject()
{
rnd = new Random();
}
// internal constructor
internal MathObject(ScriptObject parent)
: base(parent)
{
EngineInstance inst = EngineInstance.GetEngineInstance(engine);
Put("E", E,
PropertyAttributes.DontEnum|
PropertyAttributes.DontDelete|
PropertyAttributes.ReadOnly);
Put("LN10", LN10,
PropertyAttributes.DontEnum|
PropertyAttributes.DontDelete|
PropertyAttributes.ReadOnly);
Put("LN2", LN2,
PropertyAttributes.DontEnum|
PropertyAttributes.DontDelete|
PropertyAttributes.ReadOnly);
Put("LOG2E", LOG2E,
PropertyAttributes.DontEnum|
PropertyAttributes.DontDelete|
PropertyAttributes.ReadOnly);
Put("LOG10E", LOG10E,
PropertyAttributes.DontEnum|
PropertyAttributes.DontDelete|
PropertyAttributes.ReadOnly);
Put("PI", PI,
PropertyAttributes.DontEnum|
PropertyAttributes.DontDelete|
PropertyAttributes.ReadOnly);
Put("SQRT1_2", SQRT1_2,
PropertyAttributes.DontEnum|
PropertyAttributes.DontDelete|
PropertyAttributes.ReadOnly);
Put("SQRT2", SQRT2,
PropertyAttributes.DontEnum|
PropertyAttributes.DontDelete|
PropertyAttributes.ReadOnly);
AddBuiltin(inst, "abs");
AddBuiltin(inst, "acos");
AddBuiltin(inst, "asin");
AddBuiltin(inst, "atan");
AddBuiltin(inst, "atan2");
AddBuiltin(inst, "ceil");
AddBuiltin(inst, "exp");
AddBuiltin(inst, "floor");
AddBuiltin(inst, "log");
AddBuiltin(inst, "max");
AddBuiltin(inst, "min");
AddBuiltin(inst, "pow");
AddBuiltin(inst, "random");
AddBuiltin(inst, "round");
AddBuiltin(inst, "sin");
AddBuiltin(inst, "sqrt");
AddBuiltin(inst, "tan");
}
// compute the absolute value of an integer
[JSFunctionAttribute(0, JSBuiltin.Math_abs)]
public static Double abs(Double d)
{
return Math.Abs(d);
}
// calculate the arc cosine of x
[JSFunctionAttribute(0, JSBuiltin.Math_acos)]
public static Double acos(Double x)
{
return Math.Acos(x);
}
// calculate the arc sine of x
[JSFunctionAttribute(0, JSBuiltin.Math_asin)]
public static Double asin(Double x)
{
return Math.Asin(x);
}
// calculate the arc tangent of x
[JSFunctionAttribute(0, JSBuiltin.Math_atan)]
public static Double atan(Double x)
{
return Math.Atan(x);
}
// calculate the arc tangent of two values
[JSFunctionAttribute(0, JSBuiltin.Math_atan2)]
public static Double atan2(Double dy, Double dx)
{
return Math.Atan2(dy, dx);
}
// calculate the smallest integral value not less than x
[JSFunctionAttribute(0, JSBuiltin.Math_ceil)]
public static Double ceil(Double x)
{
return Math.Ceiling(x);
}
// calculate the cosin value of x
[JSFunctionAttribute(0, JSBuiltin.Math_cos)]
public static Double cos(Double x)
{
return Math.Cos(x);
}
// returns the value of E raised to the power of x
[JSFunctionAttribute(0, JSBuiltin.Math_exp)]
public static Double exp(Double x)
{
return Math.Exp(x);
}
// return the greatest integral value not greater than x
[JSFunctionAttribute(0, JSBuiltin.Math_floor)]
public static Double floor(Double x)
{
return Math.Floor(x);
}
// return the natural logarithm of x
[JSFunctionAttribute(0, JSBuiltin.Math_log)]
public static Double log(Double x)
{
return Math.Log(x);
}
// returns the greater value of two, or more, numbers
[JSFunctionAttribute
(JSFunctionAttributeEnum.HasVarArgs, JSBuiltin.Math_max)]
public static Double max(params Object[] args)
{
Double dx, dy;
if(args == null || args.Length < 1)
{
return Double.NegativeInfinity;
}
else
{
dx = args[0] is Double ?
(Double)args[0] : Convert.ToNumber(args[0]);
}
if(args.Length < 2)
{
return dx;
}
else
{
dy = dx = args[1] is Double ?
(Double)args[1] : Convert.ToNumber(args[1]);
}
Double max = dx.CompareTo(dy) < 0 ? dy : dx;
if(args.Length > 2)
{
foreach(Object o in args)
{
max = MathObject.max(max, o);
}
}
return max;
}
// returns the smaller value of two, or more, numbers
[JSFunctionAttribute
(JSFunctionAttributeEnum.HasVarArgs, JSBuiltin.Math_max)]
public static Double min(params Object[] args)
{
Double dx, dy;
if(args == null || args.Length < 1)
{
return Double.NegativeInfinity;
}
else
{
dx = args[0] is Double ?
(Double)args[0] : Convert.ToNumber(args[0]);
}
if(args.Length < 2)
{
return dx;
}
else
{
dy = dx = args[1] is Double ?
(Double)args[1] : Convert.ToNumber(args[1]);
}
Double min = dx.CompareTo(dy) < 0 ? dx : dy;
if(args.Length > 2)
{
foreach(Object o in args)
{
min = MathObject.min(min, o);
}
}
return min;
}
// returns the value of x raised to the power of y
[JSFunctionAttribute(0, JSBuiltin.Math_pow)]
public static Double pow(Double x, Double y)
{
return Math.Pow(x, y);
}
// returns a random number
public static Double random()
{
// paranoid
if(rnd == null)
{
rnd = new Random();
}
return (Double)rnd.Next();
}
// round to nearest integer, away from zero
[JSFunctionAttribute(0, JSBuiltin.Math_round)]
public static Double round(Double d)
{
return Math.Round(d);
}
// returns the sine of x
[JSFunctionAttribute(0, JSBuiltin.Math_sin)]
public static Double sin(Double x)
{
return Math.Sin(x);
}
// returns the non-negative square root of x
[JSFunctionAttribute(0, JSBuiltin.Math_sqrt)]
public static Double sqrt(Double x)
{
return Math.Sqrt(x);
}
// returns the tangent of x
[JSFunctionAttribute(0, JSBuiltin.Math_tan)]
public static Double tan(Double x)
{
return Math.Tan(x);
}
}; // class MathObject
public sealed class LenientMathObject : MathObject
{
public new System.Object abs;
public new System.Object acos;
public new System.Object asin;
public new System.Object atan;
public new System.Object atan2;
public new System.Object ceil;
public new System.Object cos;
public new System.Object exp;
public new System.Object floor;
public new System.Object log;
public new System.Object max;
public new System.Object min;
public new System.Object pow;
public new System.Object random;
public new System.Object round;
public new System.Object sin;
public new System.Object sqrt;
public new System.Object tan;
internal LenientMathObject(ScriptObject parent, FunctionPrototype prototype)
: base(parent)
{
EngineInstance inst = EngineInstance.GetEngineInstance(engine);
abs = Get("abs");
acos = Get("acos");
asin = Get("asin");
atan = Get("atan");
atan2 = Get("atan2");
ceil = Get("ceil");
cos = Get("cos");
exp = Get("exp");
floor = Get("floor");
log = Get("log");
max = Get("max");
min = Get("min");
pow = Get("pow");
random = Get("random");
round = Get("round");
sin = Get("sin");
sqrt = Get("sqrt");
tan = Get("tan");
}
}; // class LenientMathObject
}; // namespace Microsoft.JScript
| |
/*
* Copyright (c) 2007-2009 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 Box2D.Collision.Shapes;
using Box2D.Common;
namespace Box2D.Collision
{
public enum SeparationType
{
e_points,
e_faceA,
e_faceB
};
public struct b2SeparationFunction
{
// TODO_ERIN might not need to return the separation
public float Initialize(ref b2SimplexCache cache,
b2DistanceProxy proxyA, ref b2Sweep sweepA,
b2DistanceProxy proxyB, ref b2Sweep sweepB,
float t1, ref b2Transform xfA, ref b2Transform xfB)
{
m_proxyA = proxyA;
m_proxyB = proxyB;
int count = cache.count;
Debug.Assert(0 < count && count < 3);
m_sweepA = sweepA;
m_sweepB = sweepB;
if (count == 1)
{
m_type = SeparationType.e_points;
b2Vec2 localPointA = m_proxyA.m_vertices[(int)cache.indexA[0]];
b2Vec2 localPointB = m_proxyB.m_vertices[(int)cache.indexB[0]];
float pointAx = (xfA.q.c * localPointA.x - xfA.q.s * localPointA.y) + xfA.p.x;
float pointAy = (xfA.q.s * localPointA.x + xfA.q.c * localPointA.y) + xfA.p.y;
float pointBx = (xfB.q.c * localPointB.x - xfB.q.s * localPointB.y) + xfB.p.x;
float pointBy = (xfB.q.s * localPointB.x + xfB.q.c * localPointB.y) + xfB.p.y;
m_axis.x = pointBx - pointAx;
m_axis.y = pointBy - pointAy;
float s = m_axis.Normalize();
return s;
}
else if (cache.indexA[0] == cache.indexA[1])
{
// Two points on B and one on A.
m_type = SeparationType.e_faceB;
b2Vec2 localPointB1 = proxyB.m_vertices[(int)cache.indexB[0]];
b2Vec2 localPointB2 = proxyB.m_vertices[(int)cache.indexB[1]];
float b21x = localPointB2.x - localPointB1.x;
float b21y = localPointB2.y - localPointB1.y;
m_axis.x = -b21y;
m_axis.y = b21x;
// m_axis = b2Math.b2Cross(localPointB2 - localPointB1, 1.0f);
m_axis.Normalize();
float normalx = xfB.q.c * m_axis.x - xfB.q.s * m_axis.y;
float normaly = xfB.q.s * m_axis.x + xfB.q.c * m_axis.y;
m_localPoint.x = 0.5f * (localPointB1.x + localPointB2.x);
m_localPoint.y = 0.5f * (localPointB1.y + localPointB2.y);
float pointBx = (xfB.q.c * m_localPoint.x - xfB.q.s * m_localPoint.y) + xfB.p.x;
float pointBy = (xfB.q.s * m_localPoint.x + xfB.q.c * m_localPoint.y) + xfB.p.y;
b2Vec2 localPointA = proxyA.m_vertices[(int)cache.indexA[0]];
float pointAx = (xfA.q.c * localPointA.x - xfA.q.s * localPointA.y) + xfA.p.x;
float pointAy = (xfA.q.s * localPointA.x + xfA.q.c * localPointA.y) + xfA.p.y;
float aminusbx = pointAx - pointBx;
float aminusby = pointAy - pointBy;
float s = aminusbx * normalx + aminusby * normaly;
if (s < 0.0f)
{
m_axis.x = -m_axis.x;
m_axis.y = -m_axis.y;
s = -s;
}
return s;
}
else
{
// Two points on A and one or two points on B.
m_type = SeparationType.e_faceA;
b2Vec2 localPointA1 = m_proxyA.m_vertices[cache.indexA[0]];
b2Vec2 localPointA2 = m_proxyA.m_vertices[cache.indexA[1]];
float a2minusa1x = localPointA2.x - localPointA1.x;
float a2minusa1y = localPointA2.y - localPointA1.y;
//m_axis = a2minusa1.UnitCross();// b2Math.b2Cross(localPointA2 - localPointA1, 1.0f);
m_axis.x = a2minusa1y;
m_axis.y = -a2minusa1x;
m_axis.Normalize();
float normalx = xfA.q.c * m_axis.x - xfA.q.s * m_axis.y;
float normaly = xfA.q.s * m_axis.x + xfA.q.c * m_axis.y;
m_localPoint.x = 0.5f * (localPointA1.x + localPointA2.x);
m_localPoint.y = 0.5f * (localPointA1.y + localPointA2.y);
float pointAx = (xfA.q.c * m_localPoint.x - xfA.q.s * m_localPoint.y) + xfA.p.x;
float pointAy = (xfA.q.s * m_localPoint.x + xfA.q.c * m_localPoint.y) + xfA.p.y;
b2Vec2 localPointB = m_proxyB.m_vertices[cache.indexB[0]];
float pointBx = (xfB.q.c * localPointB.x - xfB.q.s * localPointB.y) + xfB.p.x;
float pointBy = (xfB.q.s * localPointB.x + xfB.q.c * localPointB.y) + xfB.p.y;
float bminusax = pointBx - pointAx;
float bminusay = pointBy - pointAy;
float s = bminusax * normalx + bminusay * normaly;
if (s < 0.0f)
{
m_axis.x = -m_axis.x;
m_axis.y = -m_axis.y;
s = -s;
}
return s;
}
}
public float FindMinSeparation(out int indexA, out int indexB, float t)
{
b2Transform xfA, xfB;
m_sweepA.GetTransform(out xfA, t);
m_sweepB.GetTransform(out xfB, t);
switch (m_type)
{
case SeparationType.e_points:
{
b2Vec2 axisA;
axisA.x = xfA.q.c * m_axis.x + xfA.q.s * m_axis.y;
axisA.y = -xfA.q.s * m_axis.x + xfA.q.c * m_axis.y;
b2Vec2 axisB;
axisB.x = xfB.q.c * -m_axis.x + xfB.q.s * -m_axis.y;
axisB.y = -xfB.q.s * -m_axis.x + xfB.q.c * -m_axis.y;
indexA = m_proxyA.GetSupport(ref axisA);
indexB = m_proxyB.GetSupport(ref axisB);
var vA = m_proxyA.m_vertices[indexA];
var vB = m_proxyB.m_vertices[indexB];
float pointAx = (xfA.q.c * vA.x - xfA.q.s * vA.y) + xfA.p.x;
float pointAy = (xfA.q.s * vA.x + xfA.q.c * vA.y) + xfA.p.y;
float pointBx = (xfB.q.c * vB.x - xfB.q.s * vB.y) + xfB.p.x;
float pointBy = (xfB.q.s * vB.x + xfB.q.c * vB.y) + xfB.p.y;
float distx = pointBx - pointAx;
float disty = pointBy - pointAy;
float separation = distx * m_axis.x + disty * m_axis.y;
return separation;
}
case SeparationType.e_faceA:
{
float normalx = xfA.q.c * m_axis.x - xfA.q.s * m_axis.y;
float normaly = xfA.q.s * m_axis.x + xfA.q.c * m_axis.y;
float pointAx = (xfA.q.c * m_localPoint.x - xfA.q.s * m_localPoint.y) + xfA.p.x;
float pointAy = (xfA.q.s * m_localPoint.x + xfA.q.c * m_localPoint.y) + xfA.p.y;
b2Vec2 axisB;
axisB.x = xfB.q.c * -normalx + xfB.q.s * -normaly;
axisB.y = -xfB.q.s * -normalx + xfB.q.c * -normaly;
indexA = -1;
indexB = m_proxyB.GetSupport(ref axisB);
var vB = m_proxyB.m_vertices[indexB];
float pointBx = (xfB.q.c * vB.x - xfB.q.s * vB.y) + xfB.p.x;
float pointBy = (xfB.q.s * vB.x + xfB.q.c * vB.y) + xfB.p.y;
float distx = pointBx - pointAx;
float disty = pointBy - pointAy;
float separation = distx * normalx + disty * normaly;
return separation;
}
case SeparationType.e_faceB:
{
float normalx = xfB.q.c * m_axis.x - xfB.q.s * m_axis.y;
float normaly = xfB.q.s * m_axis.x + xfB.q.c * m_axis.y;
float pointBx = (xfB.q.c * m_localPoint.x - xfB.q.s * m_localPoint.y) + xfB.p.x;
float pointBy = (xfB.q.s * m_localPoint.x + xfB.q.c * m_localPoint.y) + xfB.p.y;
b2Vec2 axisA;
axisA.x = xfA.q.c * -normalx + xfA.q.s * -normaly;
axisA.y = -xfA.q.s * -normalx + xfA.q.c * -normaly;
indexB = -1;
indexA = m_proxyA.GetSupport(ref axisA);
var vA = m_proxyA.m_vertices[indexA];
float pointAx = (xfA.q.c * vA.x - xfA.q.s * vA.y) + xfA.p.x;
float pointAy = (xfA.q.s * vA.x + xfA.q.c * vA.y) + xfA.p.y;
float distx = pointAx - pointBx;
float disty = pointAy - pointBy;
float separation = distx * normalx + disty * normaly;
return separation;
}
default:
Debug.Assert(false);
indexA = -1;
indexB = -1;
return 0.0f;
}
}
public float Evaluate(int indexA, int indexB, float t)
{
b2Transform xfA, xfB;
m_sweepA.GetTransform(out xfA, t);
m_sweepB.GetTransform(out xfB, t);
switch (m_type)
{
case SeparationType.e_points:
{
float axisAx = xfA.q.c * m_axis.x + xfA.q.s * m_axis.y;
float axisAy = -xfA.q.s * m_axis.x + xfA.q.c * m_axis.y;
//float axisBx = xfB.q.c * -axisAx + xfB.q.s * -axisAy;
//float axisBy = -xfB.q.s * -axisAx + xfB.q.c * -axisAy;
var vA = m_proxyA.m_vertices[indexA];
var vB = m_proxyB.m_vertices[indexB];
float pointAx = (xfA.q.c * vA.x - xfA.q.s * vA.y) + xfA.p.x;
float pointAy = (xfA.q.s * vA.x + xfA.q.c * vA.y) + xfA.p.y;
float pointBx = (xfB.q.c * vB.x - xfB.q.s * vB.y) + xfB.p.x;
float pointBy = (xfB.q.s * vB.x + xfB.q.c * vB.y) + xfB.p.y;
float distx = pointBx - pointAx;
float disty = pointBy - pointAy;
float separation = distx * m_axis.x + disty * m_axis.y;
return separation;
}
case SeparationType.e_faceA:
{
float normalx = xfA.q.c * m_axis.x - xfA.q.s * m_axis.y;
float normaly = xfA.q.s * m_axis.x + xfA.q.c * m_axis.y;
float pointAx = (xfA.q.c * m_localPoint.x - xfA.q.s * m_localPoint.y) + xfA.p.x;
float pointAy = (xfA.q.s * m_localPoint.x + xfA.q.c * m_localPoint.y) + xfA.p.y;
//float axisBx = xfB.q.c * -normalx + xfB.q.s * -normaly;
//float axisBy = -xfB.q.s * -normalx + xfB.q.c * -normaly;
var vB = m_proxyB.m_vertices[indexB];
float pointBx = (xfB.q.c * vB.x - xfB.q.s * vB.y) + xfB.p.x;
float pointBy = (xfB.q.s * vB.x + xfB.q.c * vB.y) + xfB.p.y;
float distx = pointBx - pointAx;
float disty = pointBy - pointAy;
float separation = distx * normalx + disty * normaly;
return separation;
}
case SeparationType.e_faceB:
{
float normalx = xfB.q.c * m_axis.x - xfB.q.s * m_axis.y;
float normaly = xfB.q.s * m_axis.x + xfB.q.c * m_axis.y;
float pointBx = (xfB.q.c * m_localPoint.x - xfB.q.s * m_localPoint.y) + xfB.p.x;
float pointBy = (xfB.q.s * m_localPoint.x + xfB.q.c * m_localPoint.y) + xfB.p.y;
//float axisAx = xfA.q.c * -normalx + xfA.q.s * -normaly;
//float axisAy = -xfA.q.s * -normalx + xfA.q.c * -normaly;
var vA = m_proxyA.m_vertices[indexA];
float pointAx = (xfA.q.c * vA.x - xfA.q.s * vA.y) + xfA.p.x;
float pointAy = (xfA.q.s * vA.x + xfA.q.c * vA.y) + xfA.p.y;
float distx = pointAx - pointBx;
float disty = pointAy - pointBy;
float separation = distx * normalx + disty * normaly;
return separation;
}
default:
Debug.Assert(false);
return 0.0f;
}
}
private b2DistanceProxy m_proxyA;
private b2DistanceProxy m_proxyB;
private b2Sweep m_sweepA, m_sweepB;
private SeparationType m_type;
private b2Vec2 m_localPoint;
private b2Vec2 m_axis;
}
/// Input parameters for b2TimeOfImpact
public struct b2TOIInput
{
public static b2TOIInput Zero = b2TOIInput.Create();
public static b2TOIInput Create()
{
var toi = new b2TOIInput();
toi.proxyA = b2DistanceProxy.Create();
toi.proxyB = b2DistanceProxy.Create();
toi.sweepA = new b2Sweep();
toi.sweepB = new b2Sweep();
return toi;
}
public b2DistanceProxy proxyA;
public b2DistanceProxy proxyB;
public b2Sweep sweepA;
public b2Sweep sweepB;
public float tMax; // defines sweep interval [0, tMax]
}
public enum b2ImpactState
{
e_unknown,
e_failed,
e_overlapped,
e_touching,
e_separated
};
// Output parameters for b2TimeOfImpact.
public struct b2TOIOutput
{
public b2ImpactState state;
public float t;
};
public class b2TimeOfImpact
{
public static int b2_toiCalls, b2_toiIters, b2_toiMaxIters;
public static int b2_toiRootIters, b2_toiMaxRootIters;
//Caches
static b2SimplexCache _cache = b2SimplexCache.Create();
// CCD via the local separating axis method. This seeks progression
// by computing the largest time at which separation is maintained.
public static void Compute(out b2TOIOutput output, ref b2TOIInput input)
{
++b2_toiCalls;
output.state = b2ImpactState.e_unknown;
output.t = input.tMax;
b2DistanceProxy proxyA = input.proxyA;
b2DistanceProxy proxyB = input.proxyB;
b2Sweep sweepA = input.sweepA;
b2Sweep sweepB = input.sweepB;
// Large rotations can make the root finder fail, so we normalize the
// sweep angles.
sweepA.Normalize();
sweepB.Normalize();
float tMax = input.tMax;
float totalRadius = proxyA.Radius + proxyB.Radius;
float target = Math.Max(b2Settings.b2_linearSlop, totalRadius - 3.0f * b2Settings.b2_linearSlop);
float tolerance = 0.25f * b2Settings.b2_linearSlop;
Debug.Assert(target > tolerance);
float t1 = 0.0f;
int k_maxIterations = 20; // TODO_ERIN b2Settings
int iter = 0;
// Prepare input for distance query.
b2SimplexCache cache = _cache;
b2DistanceInput distanceInput;
distanceInput.proxyA = input.proxyA;
distanceInput.proxyB = input.proxyB;
distanceInput.useRadii = false;
// The outer loop progressively attempts to compute new separating axes.
// This loop terminates when an axis is repeated (no progress is made).
while (true)
{
// Get the distance between shapes. We can also use the results
// to get a separating axis.
sweepA.GetTransform(out distanceInput.transformA, t1);
sweepB.GetTransform(out distanceInput.transformB, t1);
b2DistanceOutput distanceOutput;
b2Simplex.b2Distance(out distanceOutput, ref cache, ref distanceInput);
// If the shapes are overlapped, we give up on continuous collision.
if (distanceOutput.distance <= 0.0f)
{
// Failure!
output.state = b2ImpactState.e_overlapped;
output.t = 0.0f;
break;
}
if (distanceOutput.distance < target + tolerance)
{
// Victory!
output.state = b2ImpactState.e_touching;
output.t = t1;
break;
}
// Initialize the separating axis.
b2SeparationFunction fcn = new b2SeparationFunction();
fcn.Initialize(ref cache, proxyA, ref sweepA, proxyB, ref sweepB, t1,
ref distanceInput.transformA, ref distanceInput.transformB);
#if false
// Dump the curve seen by the root finder
{
int N = 100;
float dx = 1.0f / N;
float xs[N+1];
float fs[N+1];
float x = 0.0f;
for (int i = 0; i <= N; ++i)
{
sweepA.GetTransform(&xfA, x);
sweepB.GetTransform(&xfB, x);
float f = fcn.Evaluate(xfA, xfB) - target;
printf("%g %g\n", x, f);
xs[i] = x;
fs[i] = f;
x += dx;
}
}
#endif
// Compute the TOI on the separating axis. We do this by successively
// resolving the deepest point. This loop is bounded by the number of vertices.
bool done = false;
float t2 = tMax;
int pushBackIter = 0;
while(true)
{
// Find the deepest point at t2. Store the witness point indices.
int indexA, indexB;
float s2 = fcn.FindMinSeparation(out indexA, out indexB, t2);
// Is the final configuration separated?
if (s2 > target + tolerance)
{
// Victory!
output.state = b2ImpactState.e_separated;
output.t = tMax;
done = true;
break;
}
// Has the separation reached tolerance?
if (s2 > target - tolerance)
{
// Advance the sweeps
t1 = t2;
break;
}
// Compute the initial separation of the witness points.
float s1 = fcn.Evaluate(indexA, indexB, t1);
// Check for initial overlap. This might happen if the root finder
// runs out of iterations.
if (s1 < target - tolerance)
{
output.state = b2ImpactState.e_failed;
output.t = t1;
done = true;
break;
}
// Check for touching
if (s1 <= target + tolerance)
{
// Victory! t1 should hold the TOI (could be 0.0).
output.state = b2ImpactState.e_touching;
output.t = t1;
done = true;
break;
}
// Compute 1D root of: f(x) - target = 0
int rootIterCount;
float a1 = t1, a2 = t2;
for (rootIterCount = 0; rootIterCount != 50; ++rootIterCount)
{
// Use a mix of the secant rule and bisection.
float t;
if (rootIterCount % 1 == 1) // even/odd
{
// Secant rule to improve convergence.
t = a1 + (target - s1) * (a2 - a1) / (s2 - s1);
}
else
{
// Bisection to guarantee progress.
t = 0.5f * (a1 + a2);
}
float s = fcn.Evaluate(indexA, indexB, t);
if (b2Math.b2Abs(s - target) < tolerance)
{
// t2 holds a tentative value for t1
t2 = t;
break;
}
// Ensure we continue to bracket the root.
if (s > target)
{
a1 = t;
s1 = s;
}
else
{
a2 = t;
s2 = s;
}
++b2_toiRootIters;
}
b2_toiMaxRootIters = Math.Max(b2_toiMaxRootIters, rootIterCount);
++pushBackIter;
if (pushBackIter == b2Settings.b2_maxPolygonVertices)
{
break;
}
}
++iter;
++b2_toiIters;
if (done)
{
break;
}
if (iter == k_maxIterations)
{
// Root finder got stuck. Semi-victory.
output.state = b2ImpactState.e_failed;
output.t = t1;
break;
}
}
b2_toiMaxIters = Math.Max(b2_toiMaxIters, iter);
}
}
}
| |
using XPT.Games.Generic.Constants;
using XPT.Games.Generic.Maps;
using XPT.Games.Twinion.Entities;
namespace XPT.Games.Twinion.Maps {
/// <summary>
/// L3: Queen's Palace
/// </summary>
class TwMap07 : TwMap {
public override int MapIndex => 7;
public override int MapID => 0x0302;
protected override int RandomEncounterChance => 10;
protected override int RandomEncounterExtraCount => 0;
private const int MONSTERA = 1;
private const int MONSTERB = 2;
private const int HEALFOUNTAIN = 3;
private const int MANAFOUNTAIN = 4;
private const int QUEENGUARD = 5;
private const int SPRUNGTRAP = 1;
protected override void FnEvent01(TwPlayerServer player, MapEventType type, bool doMsgs) {
if (GetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.FINISHEDGAME) == 1) {
ShowText(player, type, doMsgs, "You see an empty, cracked throne.");
ShowText(player, type, doMsgs, "The Queen is no more.");
}
else {
if (GetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.DONEPROVING) == 1) {
ShowPortrait(player, type, doMsgs, QUEENAEOWYN);
ShowText(player, type, doMsgs, "A magnificent queen stands before you.");
ShowText(player, type, doMsgs, "Her beauty and strength awe all who see her, woman and man alike. This is Queen Aeowyn.");
ShowText(player, type, doMsgs, "'My champions, a key awaits you at the palace exit. Use it at the ancient gateway east of the main entrance.");
ShowText(player, type, doMsgs, "Another portal will lead you to the depths of this volcano, where none has dared yet visit.");
ShowText(player, type, doMsgs, "I require four pieces of an ancient map! I enjoin you with this task as a test of your loyalty.");
ShowText(player, type, doMsgs, "Reveal your purpose to no one! Go now! Seek the Kingdom of the Night Elves.");
ShowText(player, type, doMsgs, "I will meet you at your quest's end, that we may piece together the maps' meaning.'");
ShowText(player, type, doMsgs, "With a royal wave of dismissal, Aeowyn weaves a spell of parting and vanishes.");
SetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.DONEPROVING, 2);
}
else {
ShowText(player, type, doMsgs, "Queen Aeowyn must be off looking for clues.");
}
}
}
private void WallBlock(TwPlayerServer player, MapEventType type, bool doMsgs) {
SetWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), GetFacing(player, type, doMsgs));
}
protected override void FnEvent02(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowText(player, type, doMsgs, "This leads back to the Coliseum.");
TeleportParty(player, type, doMsgs, 3, 1, 127, Direction.North);
}
protected override void FnEvent03(TwPlayerServer player, MapEventType type, bool doMsgs) {
SetTileBlock(player, type, doMsgs, GetTile(player, type, doMsgs));
}
protected override void FnEvent04(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowText(player, type, doMsgs, "The warm waters soothe your pains.");
ModifyHealth(player, type, doMsgs, GetHealthMax(player, type, doMsgs));
}
protected override void FnEvent05(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowPortrait(player, type, doMsgs, FOUNTAIN);
ShowText(player, type, doMsgs, "Elaborate fountains mark the entryway to Queen Aeowyn's throne room.");
}
protected override void FnEvent06(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowText(player, type, doMsgs, "You fall into a pit and are impaled on razor sharp spears.");
DoDamage(player, type, doMsgs, GetHealthMax(player, type, doMsgs));
}
protected override void FnEvent07(TwPlayerServer player, MapEventType type, bool doMsgs) {
if (UsedItem(player, type, ref doMsgs, CROSSKEY, CROSSKEY)) {
ShowText(player, type, doMsgs, "The Cross Key unlocks the door!");
ClearWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), GetFacing(player, type, doMsgs));
SetWallItem(player, type, doMsgs, DOOR, GetTile(player, type, doMsgs), GetFacing(player, type, doMsgs));
}
else {
ShowText(player, type, doMsgs, "The door's lock is marked with an X.");
WallBlock(player, type, doMsgs);
}
}
protected override void FnEvent08(TwPlayerServer player, MapEventType type, bool doMsgs) {
if (GetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.HINTEDATDOOR) == 1) {
if (HasUsedSkill(player, type, ref doMsgs, DETECT_SKILL) >= 9 || HasUsedSpell(player, type, ref doMsgs, TRUE_SEEING_SPELL) >= 1 || UsedItem(player, type, ref doMsgs, HELMOFWISDOM, HELMOFWISDOM) || UsedItem(player, type, ref doMsgs, VALKYRIESHELM, VALKYRIESHELM) || UsedItem(player, type, ref doMsgs, RINGOFTHIEVES, RINGOFTHIEVES) || UsedItem(player, type, ref doMsgs, CRYSTALBALL, CRYSTALBALL)) {
ShowText(player, type, doMsgs, "You manage to find the marked stone the old thief mentioned. The door is now open.");
ClearWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), GetFacing(player, type, doMsgs));
SetWallItem(player, type, doMsgs, DOOR, GetTile(player, type, doMsgs), GetFacing(player, type, doMsgs));
}
else {
ShowText(player, type, doMsgs, "The stone must be here somewhere.");
ShowText(player, type, doMsgs, "Perhaps you are not skilled enough.");
WallBlock(player, type, doMsgs);
}
}
else {
ShowText(player, type, doMsgs, "Something seems out of place here, but you can't tell what.");
WallBlock(player, type, doMsgs);
}
}
protected override void FnEvent09(TwPlayerServer player, MapEventType type, bool doMsgs) {
if (GetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.HINTEDATDOOR) == 1) {
ShowText(player, type, doMsgs, "The old thief has slipped away into the shadows.");
}
else {
ShowPortrait(player, type, doMsgs, HUMANTHIEF);
ShowText(player, type, doMsgs, "An old thief stands to greet you.");
ShowText(player, type, doMsgs, "'Hail! You seem a bit puzzled and a lot lost.");
ShowText(player, type, doMsgs, "There's a wall to the southeast of here.");
ShowText(player, type, doMsgs, "There you'll find a stone that is marked with an ancient rune. Try detecting it to continue your way.'");
SetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.HINTEDATDOOR, 1);
}
}
protected override void FnEvent0A(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowText(player, type, doMsgs, "The final problem!");
ShowText(player, type, doMsgs, "There are short and long pathways to the Queen's chambers.");
ShowText(player, type, doMsgs, "Each has its own reward. Only one need be solved to continue, but the more explored, the greater the rewards.");
}
protected override void FnEvent0B(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowRunes(player, type, ref doMsgs, "The Queen's Hall of Records.");
}
protected override void FnEvent0C(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowRunes(player, type, ref doMsgs, "Studies on Nature and Science.");
}
protected override void FnEvent0D(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowRunes(player, type, ref doMsgs, "Classical.");
}
protected override void FnEvent0E(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowRunes(player, type, ref doMsgs, "Irrelevant.");
}
protected override void FnEvent0F(TwPlayerServer player, MapEventType type, bool doMsgs) {
switch (GetTile(player, type, doMsgs)) {
case 49:
if (GetFacing(player, type, doMsgs) == Direction.North) {
FlipStr(player, type, doMsgs);
}
break;
case 50:
if (GetFacing(player, type, doMsgs) == Direction.South) {
ShowRunes(player, type, ref doMsgs, "This book is entitled -CHESS-. It mentions how one space on a board belongs to whatever piece lands on it and captures it.");
}
break;
case 34:
if (GetFacing(player, type, doMsgs) == Direction.South) {
ShowRunes(player, type, ref doMsgs, "Another CHESS book- Bishop then Knight then Rook is how you march to face the King.");
}
break;
case 33:
if (GetFacing(player, type, doMsgs) == Direction.North) {
FlipStr(player, type, doMsgs);
}
break;
case 17:
if (GetFacing(player, type, doMsgs) == Direction.South) {
ShowRunes(player, type, ref doMsgs, "CHESS III- Changing from one piece to the next is the key to understanding the mastery of any arena.");
}
break;
case 18:
if (GetFacing(player, type, doMsgs) == Direction.North) {
FlipStr(player, type, doMsgs);
}
break;
}
}
private void FlipStr(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowText(player, type, doMsgs, "You pull a large volume from the shelf and flip randomly through the pages.");
}
protected override void FnEvent10(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowText(player, type, doMsgs, "Guttural curses and howls of agony from a battlefield to the east chill your bones.");
}
protected override void FnEvent11(TwPlayerServer player, MapEventType type, bool doMsgs) {
if ((GetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.DIDFIREBALL) == 0)) {
if (UsedItem(player, type, ref doMsgs, FLAMETONGUE, FLAMETONGUE) || UsedItem(player, type, ref doMsgs, FLAMEBLADE, FLAMEBLADE) || UsedItem(player, type, ref doMsgs, WRATHOFFAITH, WRATHOFFAITH) || UsedItem(player, type, ref doMsgs, STAFFOFJUSTICE, STAFFOFJUSTICE) || UsedItem(player, type, ref doMsgs, BOWOFFLAMES, BOWOFFLAMES) || UsedItem(player, type, ref doMsgs, AEGISDDRACO, AEGISDDRACO) || UsedItem(player, type, ref doMsgs, NEROSLYRE, NEROSLYRE) || UsedItem(player, type, ref doMsgs, SCROLLOFTHESUN, SCROLLOFTHESUN) || UsedItem(player, type, ref doMsgs, SCORCHEDSCROLL, SCORCHEDSCROLL)) {
switch (GetTile(player, type, doMsgs)) {
case 9:
ShowText(player, type, doMsgs, "The fireball travels down the corridor and fizzles.");
break;
case 24:
ShowText(player, type, doMsgs, "You launch a fireball across the chasm.");
ShowText(player, type, doMsgs, "In seconds it turns back upon you!");
DoDamage(player, type, doMsgs, GetHealthCurrent(player, type, doMsgs) / 6);
break;
case 25:
ShowText(player, type, doMsgs, "The fireball flies over the chasm into darkness.");
ShowText(player, type, doMsgs, "It then comes hurtling back at you, exploding before you can escape its wrath.");
DoDamage(player, type, doMsgs, GetHealthMax(player, type, doMsgs) / 8);
break;
case 41:
ShowText(player, type, doMsgs, "You send a fireball hurtling across the chasm.");
ShowText(player, type, doMsgs, "The booming report of an explosion alerts you that some trigger has been switched.");
ShowText(player, type, doMsgs, "A bridge extends out from this edge of the chasm, allowing you to proceed.");
SetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.DIDFIREBALL, 1);
ClearTileBlock(player, type, doMsgs, 42);
SetFloorItem(player, type, doMsgs, 0, 42);
break;
}
}
else {
ShowText(player, type, doMsgs, "The walls and floors here are scorched and charred with magical fire.");
ShowText(player, type, doMsgs, "Perhaps you can send some light across the chasm to see if any burning clues are visible.");
}
}
else {
ShowText(player, type, doMsgs, "The bridge you triggered earlier has now vanished.");
SetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.DIDFIREBALL, 0);
SetFloorItem(player, type, doMsgs, 1, 42);
}
}
protected override void FnEvent12(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowText(player, type, doMsgs, "'Travel through here at your own risk!' Signed-Lord Gnog.");
}
protected override void FnEvent13(TwPlayerServer player, MapEventType type, bool doMsgs) {
if ((GetFlag(player, type, doMsgs, FlagTypeTile, SPRUNGTRAP) == 0)) {
ShowText(player, type, doMsgs, "You set off a poisonous gas trap!");
SetDebuff(player, type, doMsgs, POISON, 8, 70);
SprungTrap(player, type, doMsgs);
}
}
protected override void FnEvent14(TwPlayerServer player, MapEventType type, bool doMsgs) {
if ((GetFlag(player, type, doMsgs, FlagTypeTile, SPRUNGTRAP) == 0)) {
ShowText(player, type, doMsgs, "Another trap is triggered, sending death darts tipped with poison showering down upon you.");
SetDebuff(player, type, doMsgs, POISON, 5, 60);
DoDamage(player, type, doMsgs, GetHealthCurrent(player, type, doMsgs) / 6);
SprungTrap(player, type, doMsgs);
}
}
private void SprungTrap(TwPlayerServer player, MapEventType type, bool doMsgs) {
SetFlag(player, type, doMsgs, FlagTypeTile, SPRUNGTRAP, 1);
}
protected override void FnEvent16(TwPlayerServer player, MapEventType type, bool doMsgs) {
DisableAutomaps(player, type, doMsgs);
ShowText(player, type, doMsgs, "You are unable to map this area.");
}
protected override void FnEvent17(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowText(player, type, doMsgs, "You could have sworn there was a door here a second ago.");
WallBlock(player, type, doMsgs);
ClearWallItem(player, type, doMsgs, GetTile(player, type, doMsgs), GetFacing(player, type, doMsgs));
}
protected override void FnEvent18(TwPlayerServer player, MapEventType type, bool doMsgs) {
if ((GetFlag(player, type, doMsgs, FlagTypeTile, SPRUNGTRAP) == 0)) {
switch (GetFacing(player, type, doMsgs)) {
case Direction.North:
SetFacing(player, type, doMsgs, Direction.West);
SprungTrap(player, type, doMsgs);
break;
case Direction.South:
SetFacing(player, type, doMsgs, Direction.East);
SprungTrap(player, type, doMsgs);
break;
case Direction.East:
SetFacing(player, type, doMsgs, Direction.South);
SprungTrap(player, type, doMsgs);
break;
case Direction.West:
SetFacing(player, type, doMsgs, Direction.East);
SprungTrap(player, type, doMsgs);
break;
}
}
}
protected override void FnEvent19(TwPlayerServer player, MapEventType type, bool doMsgs) {
if ((GetFlag(player, type, doMsgs, FlagTypeTile, SPRUNGTRAP) == 0)) {
switch (GetFacing(player, type, doMsgs)) {
case Direction.North:
SetFacing(player, type, doMsgs, Direction.South);
SprungTrap(player, type, doMsgs);
break;
case Direction.South:
SetFacing(player, type, doMsgs, Direction.West);
SprungTrap(player, type, doMsgs);
break;
case Direction.East:
SetFacing(player, type, doMsgs, Direction.North);
SprungTrap(player, type, doMsgs);
break;
case Direction.West:
SetFacing(player, type, doMsgs, Direction.East);
SprungTrap(player, type, doMsgs);
break;
}
}
}
protected override void FnEvent1A(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowText(player, type, doMsgs, "'Hail, Queen Aeowyn! All would-be champions, approach and report.'");
}
protected override void FnEvent1B(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowText(player, type, doMsgs, "The air is thick with the stench of battle and death. This Arena overflows with those who would be the Queen's champions.");
}
protected override void FnEvent1C(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowText(player, type, doMsgs, "An enormous Barbarian stands over his most recent kill. He turns and charges at you!");
AddEncounter(player, type, doMsgs, 01, 35);
}
protected override void FnEvent1D(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowText(player, type, doMsgs, "An ominous Wizard admires the fallen hero he just incinerated. He then fires a barrage of fireballs at you!");
DoDamage(player, type, doMsgs, GetHealthCurrent(player, type, doMsgs) / 6);
AddEncounter(player, type, doMsgs, 01, 36);
}
protected override void FnEvent1E(TwPlayerServer player, MapEventType type, bool doMsgs) {
int i = 0;
if ((GetFlag(player, type, doMsgs, FlagTypeParty, QUEENGUARD) == 0)) {
ShowPortrait(player, type, doMsgs, DWARFKNIGHT);
ShowText(player, type, doMsgs, "One of the Queen's Guards is here. 'No stealing!'");
ShowText(player, type, doMsgs, "I'm sure you'll obey his wish!!");
SetFlag(player, type, doMsgs, FlagTypeParty, QUEENGUARD, 1);
}
else if (GetFlag(player, type, doMsgs, FlagTypeParty, QUEENGUARD) == 1) {
ShowPortrait(player, type, doMsgs, DWARFKNIGHT);
ShowText(player, type, doMsgs, "The Guard is much more agitated. 'Be off with you! I've no kindness towards loitering fools.'");
SetFlag(player, type, doMsgs, FlagTypeParty, QUEENGUARD, 2);
}
else {
ShowText(player, type, doMsgs, "'ENOUGH! I have had enough of you!'");
ShowText(player, type, doMsgs, "'GUARDS!!!!!'");
SetTreasure(player, type, doMsgs, LONGSWORD, CROSSBOW, ELIXIROFHEALTH, 0, 0, 0);
for (i = 1; i <= 6; i++) {
AddEncounter(player, type, doMsgs, i, 40);
}
SetFlag(player, type, doMsgs, FlagTypeParty, QUEENGUARD, 0);
}
}
protected override void FnEvent1F(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowText(player, type, doMsgs, "A mob prepares to attack!");
AddEncounter(player, type, doMsgs, 01, 10);
AddEncounter(player, type, doMsgs, 02, 11);
AddEncounter(player, type, doMsgs, 03, 20);
AddEncounter(player, type, doMsgs, 04, 17);
AddEncounter(player, type, doMsgs, 05, 33);
AddEncounter(player, type, doMsgs, 06, 33);
}
protected override void FnEvent20(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowText(player, type, doMsgs, "Young warriors leap at you!");
AddEncounter(player, type, doMsgs, 01, 31);
AddEncounter(player, type, doMsgs, 02, 32);
AddEncounter(player, type, doMsgs, 03, 31);
AddEncounter(player, type, doMsgs, 04, 32);
}
protected override void FnEvent21(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowText(player, type, doMsgs, "A seasoned party launches an offensive!");
AddEncounter(player, type, doMsgs, 01, 25);
AddEncounter(player, type, doMsgs, 02, 26);
AddEncounter(player, type, doMsgs, 03, 27);
AddEncounter(player, type, doMsgs, 04, 28);
AddEncounter(player, type, doMsgs, 05, 29);
AddEncounter(player, type, doMsgs, 06, 30);
}
protected override void FnEvent22(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowPortrait(player, type, doMsgs, DWARFKNIGHT);
ShowText(player, type, doMsgs, "This place offers a vantage point of the entire combat field.");
ShowText(player, type, doMsgs, "The Master of Arms grins broadly as you enter.");
ShowText(player, type, doMsgs, "'Here, look, see that? A wizard taking on a warrior!");
ShowText(player, type, doMsgs, "If that knight were better trained, he'd have known not to challenge while his sword was in its sheath!'");
}
protected override void FnEvent23(TwPlayerServer player, MapEventType type, bool doMsgs) {
DisableAutomaps(player, type, doMsgs);
ShowText(player, type, doMsgs, "The thieves who inhabit this area spring upon you!");
AddEncounter(player, type, doMsgs, 01, 32);
AddEncounter(player, type, doMsgs, 02, 32);
AddEncounter(player, type, doMsgs, 03, 28);
AddEncounter(player, type, doMsgs, 04, 28);
}
protected override void FnEvent24(TwPlayerServer player, MapEventType type, bool doMsgs) {
int i = 0;
if (GetFlag(player, type, doMsgs, FlagTypeParty, MONSTERA) == 0) {
ShowText(player, type, doMsgs, "Vicious beasts snarl at you.");
if (GetPartyCount(player, type, doMsgs) < 3) {
for (i = 1; i <= 2; i++) {
AddEncounter(player, type, doMsgs, i, 39);
}
}
else {
for (i = 1; i <= 5; i++) {
AddEncounter(player, type, doMsgs, i, 39);
}
}
SetFlag(player, type, doMsgs, FlagTypeParty, MONSTERA, 1);
}
else if (GetFlag(player, type, doMsgs, FlagTypeParty, MONSTERA) == 1) {
ShowText(player, type, doMsgs, "Some passing adventurers notice the slain beasts here. They then challenge you to combat.");
SetTreasure(player, type, doMsgs, IRONCUTLASS, HEALPOTION, 0, 0, 0, 250);
for (i = 1; i <= 4; i++) {
AddEncounter(player, type, doMsgs, i, 36);
}
SetFlag(player, type, doMsgs, FlagTypeParty, MONSTERA, 2);
}
else {
ShowText(player, type, doMsgs, "Corpses stripped of all possessions litter this area.");
SetFlag(player, type, doMsgs, FlagTypeParty, MONSTERA, 0);
}
}
protected override void FnEvent25(TwPlayerServer player, MapEventType type, bool doMsgs) {
int i = 0;
if (GetFlag(player, type, doMsgs, FlagTypeParty, MONSTERB) == 0) {
ShowText(player, type, doMsgs, "Vicious panthers growl as you approach.");
for (i = 1; i <= 4; i++) {
AddEncounter(player, type, doMsgs, i, 38);
}
SetFlag(player, type, doMsgs, FlagTypeParty, MONSTERB, 1);
}
else if (GetFlag(player, type, doMsgs, FlagTypeParty, MONSTERB) == 1) {
ShowText(player, type, doMsgs, "Oozing slime coats the carcasses on the floor. The slime rears up as you approach!");
for (i = 1; i <= 4; i++) {
AddEncounter(player, type, doMsgs, i, 37);
}
SetFlag(player, type, doMsgs, FlagTypeParty, MONSTERB, 2);
}
else {
ShowText(player, type, doMsgs, "A slick, viscous fluid covers the area.");
SetFlag(player, type, doMsgs, FlagTypeParty, MONSTERB, 0);
}
}
protected override void FnEvent26(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowPortrait(player, type, doMsgs, TROLLCLERIC);
ShowText(player, type, doMsgs, "'These walls are trickery. You need advice from one wiser than I. Beware of the dark dungeon rooms, for they are impossible to map!!'");
}
protected override void FnEvent27(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowPortrait(player, type, doMsgs, FOUNTAIN);
int timesused = 0;
timesused = 0;
if (GetFlag(player, type, doMsgs, FlagTypeParty, HEALFOUNTAIN) < 3) {
timesused = GetFlag(player, type, doMsgs, FlagTypeParty, MANAFOUNTAIN);
ShowText(player, type, doMsgs, "The magic of the cool waters heals your wounds.");
ModifyHealth(player, type, doMsgs, GetHealthMax(player, type, doMsgs));
timesused++;
SetFlag(player, type, doMsgs, FlagTypeParty, HEALFOUNTAIN, timesused);
}
else {
ShowText(player, type, doMsgs, "The waters offer no refreshment.");
}
}
protected override void FnEvent28(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowPortrait(player, type, doMsgs, FOUNTAIN);
int timesused = 0;
timesused = 0;
if (GetFlag(player, type, doMsgs, FlagTypeParty, MANAFOUNTAIN) < 3) {
timesused = GetFlag(player, type, doMsgs, FlagTypeParty, MANAFOUNTAIN);
ShowText(player, type, doMsgs, "The magic of the cool waters restores your mana.");
ModifyMana(player, type, doMsgs, 1000);
timesused++;
SetFlag(player, type, doMsgs, FlagTypeParty, MANAFOUNTAIN, timesused);
}
else {
ShowText(player, type, doMsgs, "The waters offer no refreshment.");
}
}
protected override void FnEvent29(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowPortrait(player, type, doMsgs, GNOMEBARBARIAN);
ShowText(player, type, doMsgs, "--Lord Galabryan III--");
}
protected override void FnEvent2A(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowPortrait(player, type, doMsgs, DWARFKNIGHT);
ShowText(player, type, doMsgs, "--King Leowyn--");
}
protected override void FnEvent2B(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowPortrait(player, type, doMsgs, HUMANBARBARIAN);
ShowText(player, type, doMsgs, "--King Theowayen--");
}
protected override void FnEvent2C(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowPortrait(player, type, doMsgs, DWARFKNIGHT);
ShowText(player, type, doMsgs, "--King Cleowyn--");
}
protected override void FnEvent2D(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowPortrait(player, type, doMsgs, HUMANWIZARD);
ShowText(player, type, doMsgs, "--Arnakkian Slowfoot--");
}
protected override void FnEvent2E(TwPlayerServer player, MapEventType type, bool doMsgs) {
if (GetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.FINISHEDGAME) == 1) {
ShowPortrait(player, type, doMsgs, QUEENAEOWYN);
ShowText(player, type, doMsgs, " --Queen Aeowyn--");
ShowText(player, type, doMsgs, "--recently deceased--");
}
else {
ShowText(player, type, doMsgs, " Reserved for:");
ShowText(player, type, doMsgs, "--Queen Aeowyn--");
}
}
protected override void FnEvent2F(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowText(player, type, doMsgs, "Through here is the Corridor of Ancestry.");
ShowText(player, type, doMsgs, "The Queen's heritage shall not be forgotten.");
}
protected override void FnEvent34(TwPlayerServer player, MapEventType type, bool doMsgs) {
if (GetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.DONEPROVING) == 2) {
ShowText(player, type, doMsgs, "The waters become calm, allowing you to pass.");
}
else {
ShowText(player, type, doMsgs, "A mystical force prevents you from moving freely, and sends you back to the floor.");
TeleportParty(player, type, doMsgs, 3, 2, 142, Direction.East);
}
}
protected override void FnEvent35(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowText(player, type, doMsgs, "You are confused and disoriented in this pitch black room. The torchlight is diffused by some murky smoke.");
ShowText(player, type, doMsgs, "You are unable to map this area.");
DisableAutomaps(player, type, doMsgs);
}
protected override void FnEvent36(TwPlayerServer player, MapEventType type, bool doMsgs) {
if (GetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.DONEPROVING) == 2) {
ShowText(player, type, doMsgs, "This portal will take you to the main entrance.");
if (HasItem(player, type, doMsgs, QUEENSKEY) || IsTrue(GetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.DEEPPORTALS))) {
TeleportParty(player, type, doMsgs, 1, 1, 204, Direction.East);
}
else {
ShowText(player, type, doMsgs, "In a glass case by the door is the key promised you by the Queen.");
GiveItem(player, type, doMsgs, QUEENSKEY);
TeleportParty(player, type, doMsgs, 1, 1, 204, Direction.East);
}
}
else {
ShowText(player, type, doMsgs, "Away! You cannot use this teleport!");
}
}
protected override void FnEvent37(TwPlayerServer player, MapEventType type, bool doMsgs) {
if (GetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.ENDGAMETELE) == 1) {
if (GetPartyCount(player, type, doMsgs) == 1) {
ShowText(player, type, doMsgs, "You may proceed.");
TeleportParty(player, type, doMsgs, 3, 2, 189, Direction.East);
}
}
}
protected override void FnEvent38(TwPlayerServer player, MapEventType type, bool doMsgs) {
if (GetPartyCount(player, type, doMsgs) == 1) {
ShowText(player, type, doMsgs, "Onward you go to the next teleport.");
TeleportParty(player, type, doMsgs, 4, 3, 0, Direction.South);
}
else {
ShowText(player, type, doMsgs, "ALONE! ONLY ALONE MAY YOU PROCEED!!!");
DoDamage(player, type, doMsgs, GetHealthMax(player, type, doMsgs) / 2);
TeleportParty(player, type, doMsgs, 3, 2, 142, Direction.West);
}
}
protected override void FnEvent39(TwPlayerServer player, MapEventType type, bool doMsgs) {
if (GetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.DIDFIREBALL) == 1) {
ShowText(player, type, doMsgs, "The trigger has released a drawbridge of sorts, allowing you to pass over the chasm.");
ClearTileBlock(player, type, doMsgs, 42);
SetFloorItem(player, type, doMsgs, 0, 42);
}
else {
ShowText(player, type, doMsgs, "You plummet to your death in the deep chasm.");
DoDamage(player, type, doMsgs, GetHealthMax(player, type, doMsgs));
}
}
protected override void FnEvent3A(TwPlayerServer player, MapEventType type, bool doMsgs) {
if (HasUsedSkill(player, type, ref doMsgs, DETECT_SKILL) >= 9 || HasUsedSpell(player, type, ref doMsgs, TRUE_SEEING_SPELL) >= 1 || UsedItem(player, type, ref doMsgs, HELMOFWISDOM, HELMOFWISDOM) || UsedItem(player, type, ref doMsgs, VALKYRIESHELM, VALKYRIESHELM) || UsedItem(player, type, ref doMsgs, RINGOFTHIEVES, RINGOFTHIEVES) || UsedItem(player, type, ref doMsgs, CRYSTALBALL, CRYSTALBALL)) {
ShowText(player, type, doMsgs, "You discern light seeping through the crack of a secret door!");
SetWallItem(player, type, doMsgs, DOOR, GetTile(player, type, doMsgs), GetFacing(player, type, doMsgs));
ClearWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), GetFacing(player, type, doMsgs));
}
}
protected override void FnEvent3B(TwPlayerServer player, MapEventType type, bool doMsgs) {
int flag = 0;
int exps = 0;
switch (GetTile(player, type, doMsgs)) {
case 94:
flag = TwIndexes.DIDUPPERRIGHT;
exps = 25000;
break;
case 57:
flag = TwIndexes.DIDMIDDLEUP;
exps = 15000;
break;
case 217:
flag = TwIndexes.DIDMIDDLELOW;
exps = 20000;
break;
case 234:
flag = TwIndexes.DIDLOWERRIGHT;
exps = 25000;
break;
}
if ((GetFlag(player, type, doMsgs, FlagTypeDungeon, flag) == 0)) {
ShowPortrait(player, type, doMsgs, QUEENAEOWYN);
TextStr(player, type, doMsgs);
Queen(player, type, doMsgs);
// GiveWeapon(player, type, doMsgs);
DoneProving(player, type, doMsgs);
SetFlag(player, type, doMsgs, FlagTypeDungeon, flag, 1);
ModifyExperience(player, type, doMsgs, exps);
}
}
private void TextStr(TwPlayerServer player, MapEventType type, bool doMsgs) {
switch (GetTile(player, type, doMsgs)) {
case 94:
ShowText(player, type, doMsgs, "You've conquered the chasm, I grant you your reward!");
break;
case 57:
ShowText(player, type, doMsgs, "Well done! Did you enjoy the Hall of Ancestry!?!");
break;
case 217:
ShowText(player, type, doMsgs, "Impressive, how you managed to pass through the arena!");
break;
case 234:
ShowText(player, type, doMsgs, "The Gauntlet you ran was not as hard as some others!");
break;
}
}
private void DoneProving(TwPlayerServer player, MapEventType type, bool doMsgs) {
if ((GetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.DONEPROVING) == 0)) {
SetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.DONEPROVING, 1);
}
}
private void Queen(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowText(player, type, doMsgs, "Now, to my throne room, I will wait for you there!");
}
protected override void FnEvent3C(TwPlayerServer player, MapEventType type, bool doMsgs) {
if ((GetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.WIZSPELL) == 0)) {
if (GetGuild(player, type, doMsgs) == WIZARD || GetGuild(player, type, doMsgs) == THIEF) {
GiveSpell(player, type, doMsgs, FIREBALL_SPELL, 1);
ShowPortrait(player, type, doMsgs, FOUNTAIN);
ShowText(player, type, doMsgs, "The steaming fountain's waters offer a powerful source of energy.");
SetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.WIZSPELL, 1);
}
else {
ShowPortrait(player, type, doMsgs, FOUNTAIN);
ShowText(player, type, doMsgs, "You are scalded by the burning waters.");
DoDamage(player, type, doMsgs, GetHealthMax(player, type, doMsgs) / 6);
}
}
}
protected override void FnEvent3D(TwPlayerServer player, MapEventType type, bool doMsgs) {
if ((GetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.LORDGNOG) == 0)) {
ShowText(player, type, doMsgs, "An elderly wizard sits here, poring over books.");
ShowText(player, type, doMsgs, "'We meet at last. My envoys have told me so much about you.");
ShowText(player, type, doMsgs, "They've helped me keep track of your achievements and failures.");
ShowText(player, type, doMsgs, "Have you enjoyed my traps? Ah, well, some do, some don't.");
ShowText(player, type, doMsgs, "Since you've found me, perhaps you'd like to try for a little revenge.");
ShowText(player, type, doMsgs, "Come! Let's get on with it.'");
SetTreasure(player, type, doMsgs, MANDRAKESTAFF, TRANCETALISMAN, SLIVERBAR, 0, 0, 2000);
}
AddEncounter(player, type, doMsgs, 01, 34);
}
protected override void FnEvent3E(TwPlayerServer player, MapEventType type, bool doMsgs) {
if ((GetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.LORDGNOG) == 0)) {
SetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.LORDGNOG, 1);
}
}
protected override void FnEvent3F(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowText(player, type, doMsgs, "To the entrance of the palace.");
TeleportParty(player, type, doMsgs, 3, 2, 128, Direction.East);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Threading.Tasks;
using System.Timers;
using GalaSoft.MvvmLight;
using PropertyChanged;
using Toggl.Phoebe.Analytics;
using Toggl.Phoebe.Data.DataObjects;
using Toggl.Phoebe.Data.Models;
using Toggl.Phoebe.Data.Utils;
using Toggl.Phoebe.Data.ViewModels;
using XPlatUtils;
namespace Toggl.Phoebe.Data.ViewModels
{
[ImplementPropertyChanged]
public class EditTimeEntryGroupViewModel : ViewModelBase, IDisposable
{
private TimeEntryModel model;
private Timer durationTimer;
private List<TimeEntryData> timeEntryList;
EditTimeEntryGroupViewModel (TimeEntryModel model, List<TimeEntryData> timeEntryList)
{
this.model = model;
this.timeEntryList = timeEntryList;
this.durationTimer = new Timer();
this.model.PropertyChanged += OnPropertyChange;
this.durationTimer.Elapsed += DurationTimerCallback;
ServiceContainer.Resolve<ITracker> ().CurrentScreen = "Edit Grouped Time Entry";
UpdateView ();
}
public static async Task<EditTimeEntryGroupViewModel> Init (List<string> timeEntryIds)
{
var timeEntryList = await GetTimeEntryDataList (timeEntryIds);
var model = new TimeEntryModel (timeEntryList.Last ());
await model.LoadAsync ();
return new EditTimeEntryGroupViewModel (model, timeEntryList);
}
public void Dispose ()
{
durationTimer.Elapsed -= DurationTimerCallback;
durationTimer.Dispose ();
model.PropertyChanged -= OnPropertyChange;
model = null;
}
#region viewModel State properties
public bool IsRunning { get; set; }
public string Duration { get; set; }
public DateTime StartDate { get; set; }
public DateTime StopDate { get; set; }
public string ProjectName { get; set; }
public string ClientName { get; set; }
public string Description { get; set; }
public Guid WorkspaceId { get; set; }
public int ProjectColor { get; set; }
public ObservableRangeCollection<TimeEntryData> TimeEntryCollection { get; set; }
#endregion
public async Task SetProjectAndTask (Guid projectId, Guid taskId)
{
Guid newWorkspaceId;
// Set project to Model
if (projectId == Guid.Empty) {
model.Project = null;
model.Task = null;
newWorkspaceId = model.Workspace.Id;
} else {
var projectModel = new ProjectModel (projectId);
await projectModel.LoadAsync ();
model.Project = projectModel;
model.Workspace = new WorkspaceModel (projectModel.Workspace);
model.Task = taskId != Guid.Empty ? new TaskModel (taskId) : null;
newWorkspaceId = projectModel.Workspace.Id;
}
// Edit in a straight way the time entries.
foreach (var item in timeEntryList) {
if (projectId == Guid.Empty) {
item.ProjectId = null;
} else {
item.ProjectId = projectId;
}
if (taskId == Guid.Empty) {
item.TaskId = null;
} else {
item.TaskId = projectId;
}
// Change workspace according to project selected
item.WorkspaceId = newWorkspaceId;
Model<TimeEntryData>.MarkDirty (item);
}
UpdateView ();
}
public void ChangeTimeEntryDuration (TimeSpan newDuration, TimeEntryData timeEntryData)
{
// TODO: for the moment, old style methods
// using existing models.
var entryModel = new TimeEntryModel (timeEntryData);
entryModel.SetDuration (newDuration);
timeEntryList [timeEntryList.IndexOf (p => p.Id == entryModel.Id)] = entryModel.Data;
UpdateView ();
ServiceContainer.Resolve<ITracker> ().CurrentScreen = "Change Group Duration";
}
public async Task SaveModel ()
{
var dataStore = ServiceContainer.Resolve<IDataStore> ();
var saveTasks = new List<Task> ();
foreach (var item in timeEntryList) {
item.Description = Description;
Model<TimeEntryData>.MarkDirty (item);
saveTasks.Add (dataStore.PutAsync (item));
}
await Task.WhenAll (saveTasks);
}
private void OnPropertyChange (object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == "Data" ||
e.PropertyName == "StartTime" ||
e.PropertyName == "Duration" ||
e.PropertyName == "StopTime") {
UpdateView ();
}
}
private void UpdateView ()
{
// Ensure that this content runs in UI thread
ServiceContainer.Resolve<IPlatformUtils> ().DispatchOnUIThread (() => {
StartDate = timeEntryList.FirstOrDefault ().StartTime.ToLocalTime ();
StopDate = model.StopTime.HasValue ? model.StopTime.Value.ToLocalTime () : DateTime.UtcNow.ToLocalTime ();
// TODO: check substring function for long times
var listDuration = GetTimeEntryListDuration (timeEntryList);
Duration = TimeSpan.FromSeconds (listDuration.TotalSeconds).ToString ().Substring (0, 8);
Description = model.Description;
ProjectName = model.Project != null ? model.Project.Name : string.Empty;
ProjectColor = model.Project != null ? model.Project.Color : 0;
WorkspaceId = model.Workspace.Id;
if (model.Project != null) {
if (model.Project.Client != null) {
ClientName = model.Project.Client.Name;
}
}
if (model.State == TimeEntryState.Running && !IsRunning) {
IsRunning = true;
durationTimer.Start ();
} else if (model.State != TimeEntryState.Running) {
IsRunning = false;
durationTimer.Stop ();
}
if (TimeEntryCollection == null) {
TimeEntryCollection = new ObservableRangeCollection<TimeEntryData> ();
} else {
TimeEntryCollection.Clear ();
}
TimeEntryCollection.AddRange (timeEntryList);
});
}
private void DurationTimerCallback (object sender, ElapsedEventArgs e)
{
var duration = model.GetDuration ();
durationTimer.Interval = 1000 - duration.Milliseconds;
// Update on UI Thread
ServiceContainer.Resolve<IPlatformUtils> ().DispatchOnUIThread (() => {
Duration = TimeSpan.FromSeconds (duration.TotalSeconds).ToString ().Substring (0, 8);
});
}
#region Time Entry list utils
private static async Task<List<TimeEntryData>> GetTimeEntryDataList (List<string> ids)
{
var store = ServiceContainer.Resolve<IDataStore> ();
var list = new List<TimeEntryData> (ids.Count);
foreach (var stringGuid in ids) {
var guid = new Guid (stringGuid);
var rows = await store.Table<TimeEntryData> ()
.Where (r => r.Id == guid && r.DeletedAt == null)
.ToListAsync();
list.Add (rows.FirstOrDefault ());
}
return list;
}
public TimeSpan GetTimeEntryListDuration (List<TimeEntryData> timeEntries)
{
TimeSpan duration = TimeSpan.Zero;
foreach (var item in timeEntries) {
duration += TimeEntryModel.GetDuration (item, Time.UtcNow);
}
return duration;
}
#endregion
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.