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. using Xunit; using System; using System.Collections.Generic; using System.Threading.Tasks; using System.Threading; namespace System.IO.Tests { public class MemoryStreamTests { [Fact] public static void MemoryStream_Write_BeyondCapacity() { using (MemoryStream memoryStream = new MemoryStream()) { long origLength = memoryStream.Length; byte[] bytes = new byte[10]; for (int i = 0; i < bytes.Length; i++) bytes[i] = (byte)i; int spanPastEnd = 5; memoryStream.Seek(spanPastEnd, SeekOrigin.End); Assert.Equal(memoryStream.Length + spanPastEnd, memoryStream.Position); // Test Write memoryStream.Write(bytes, 0, bytes.Length); long pos = memoryStream.Position; Assert.Equal(pos, origLength + spanPastEnd + bytes.Length); Assert.Equal(memoryStream.Length, origLength + spanPastEnd + bytes.Length); // Verify bytes were correct. memoryStream.Position = origLength; byte[] newData = new byte[bytes.Length + spanPastEnd]; int n = memoryStream.Read(newData, 0, newData.Length); Assert.Equal(n, newData.Length); for (int i = 0; i < spanPastEnd; i++) Assert.Equal(0, newData[i]); for (int i = 0; i < bytes.Length; i++) Assert.Equal(bytes[i], newData[i + spanPastEnd]); } } [Fact] public static void MemoryStream_WriteByte_BeyondCapacity() { using (MemoryStream memoryStream = new MemoryStream()) { long origLength = memoryStream.Length; byte[] bytes = new byte[10]; for (int i = 0; i < bytes.Length; i++) bytes[i] = (byte)i; int spanPastEnd = 5; memoryStream.Seek(spanPastEnd, SeekOrigin.End); Assert.Equal(memoryStream.Length + spanPastEnd, memoryStream.Position); // Test WriteByte origLength = memoryStream.Length; memoryStream.Position = memoryStream.Length + spanPastEnd; memoryStream.WriteByte(0x42); long expected = origLength + spanPastEnd + 1; Assert.Equal(expected, memoryStream.Position); Assert.Equal(expected, memoryStream.Length); } } [Fact] public static void MemoryStream_GetPositionTest_Negative() { int iArrLen = 100; byte[] bArr = new byte[iArrLen]; using (MemoryStream ms = new MemoryStream(bArr)) { long iCurrentPos = ms.Position; for (int i = -1; i > -6; i--) { Assert.Throws<ArgumentOutOfRangeException>(() => ms.Position = i); Assert.Equal(ms.Position, iCurrentPos); } } } [Fact] public static void MemoryStream_LengthTest() { using (MemoryStream ms2 = new MemoryStream()) { // [] Get the Length when position is at length ms2.SetLength(50); ms2.Position = 50; StreamWriter sw2 = new StreamWriter(ms2); for (char c = 'a'; c < 'f'; c++) sw2.Write(c); sw2.Flush(); Assert.Equal(55, ms2.Length); // Somewhere in the middle (set the length to be shorter.) ms2.SetLength(30); Assert.Equal(30, ms2.Length); Assert.Equal(30, ms2.Position); // Increase the length ms2.SetLength(100); Assert.Equal(100, ms2.Length); Assert.Equal(30, ms2.Position); } } [Fact] public static void MemoryStream_LengthTest_Negative() { using (MemoryStream ms2 = new MemoryStream()) { Assert.Throws<ArgumentOutOfRangeException>(() => ms2.SetLength(Int64.MaxValue)); Assert.Throws<ArgumentOutOfRangeException>(() => ms2.SetLength(-2)); } } [Fact] public static void MemoryStream_ReadTest_Negative() { MemoryStream ms2 = new MemoryStream(); Assert.Throws<ArgumentNullException>(() => ms2.Read(null, 0, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => ms2.Read(new byte[] { 1 }, -1, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => ms2.Read(new byte[] { 1 }, 0, -1)); AssertExtensions.Throws<ArgumentException>(null, () => ms2.Read(new byte[] { 1 }, 2, 0)); AssertExtensions.Throws<ArgumentException>(null, () => ms2.Read(new byte[] { 1 }, 0, 2)); ms2.Dispose(); Assert.Throws<ObjectDisposedException>(() => ms2.Read(new byte[] { 1 }, 0, 1)); } [Fact] public static void MemoryStream_WriteToTests() { using (MemoryStream ms2 = new MemoryStream()) { byte[] bytArrRet; byte[] bytArr = new byte[] { byte.MinValue, byte.MaxValue, 1, 2, 3, 4, 5, 6, 128, 250 }; // [] Write to FileStream, check the filestream ms2.Write(bytArr, 0, bytArr.Length); using (MemoryStream readonlyStream = new MemoryStream()) { ms2.WriteTo(readonlyStream); readonlyStream.Flush(); readonlyStream.Position = 0; bytArrRet = new byte[(int)readonlyStream.Length]; readonlyStream.Read(bytArrRet, 0, (int)readonlyStream.Length); for (int i = 0; i < bytArr.Length; i++) { Assert.Equal(bytArr[i], bytArrRet[i]); } } } // [] Write to memoryStream, check the memoryStream using (MemoryStream ms2 = new MemoryStream()) using (MemoryStream ms3 = new MemoryStream()) { byte[] bytArrRet; byte[] bytArr = new byte[] { byte.MinValue, byte.MaxValue, 1, 2, 3, 4, 5, 6, 128, 250 }; ms2.Write(bytArr, 0, bytArr.Length); ms2.WriteTo(ms3); ms3.Position = 0; bytArrRet = new byte[(int)ms3.Length]; ms3.Read(bytArrRet, 0, (int)ms3.Length); for (int i = 0; i < bytArr.Length; i++) { Assert.Equal(bytArr[i], bytArrRet[i]); } } } [Fact] public static void MemoryStream_WriteToTests_Negative() { using (MemoryStream ms2 = new MemoryStream()) { Assert.Throws<ArgumentNullException>(() => ms2.WriteTo(null)); ms2.Write(new byte[] { 1 }, 0, 1); MemoryStream readonlyStream = new MemoryStream(new byte[1028], false); Assert.Throws<NotSupportedException>(() => ms2.WriteTo(readonlyStream)); readonlyStream.Dispose(); // [] Pass in a closed stream Assert.Throws<ObjectDisposedException>(() => ms2.WriteTo(readonlyStream)); } } [Fact] public static void MemoryStream_CopyTo_Invalid() { MemoryStream memoryStream; using (memoryStream = new MemoryStream()) { AssertExtensions.Throws<ArgumentNullException>("destination", () => memoryStream.CopyTo(destination: null)); // Validate the destination parameter first. AssertExtensions.Throws<ArgumentNullException>("destination", () => memoryStream.CopyTo(destination: null, bufferSize: 0)); AssertExtensions.Throws<ArgumentNullException>("destination", () => memoryStream.CopyTo(destination: null, bufferSize: -1)); // Then bufferSize. AssertExtensions.Throws<ArgumentOutOfRangeException>("bufferSize", () => memoryStream.CopyTo(Stream.Null, bufferSize: 0)); // 0-length buffer doesn't make sense. AssertExtensions.Throws<ArgumentOutOfRangeException>("bufferSize", () => memoryStream.CopyTo(Stream.Null, bufferSize: -1)); } // After the Stream is disposed, we should fail on all CopyTos. AssertExtensions.Throws<ArgumentOutOfRangeException>("bufferSize", () => memoryStream.CopyTo(Stream.Null, bufferSize: 0)); // Not before bufferSize is validated. AssertExtensions.Throws<ArgumentOutOfRangeException>("bufferSize", () => memoryStream.CopyTo(Stream.Null, bufferSize: -1)); MemoryStream disposedStream = memoryStream; // We should throw first for the source being disposed... Assert.Throws<ObjectDisposedException>(() => memoryStream.CopyTo(disposedStream, 1)); // Then for the destination being disposed. memoryStream = new MemoryStream(); Assert.Throws<ObjectDisposedException>(() => memoryStream.CopyTo(disposedStream, 1)); // Then we should check whether we can't read but can write, which isn't possible for non-subclassed MemoryStreams. // THen we should check whether the destination can read but can't write. var readOnlyStream = new DelegateStream( canReadFunc: () => true, canWriteFunc: () => false ); Assert.Throws<NotSupportedException>(() => memoryStream.CopyTo(readOnlyStream, 1)); } [Theory] [MemberData(nameof(CopyToData))] public void CopyTo(Stream source, byte[] expected) { using (var destination = new MemoryStream()) { source.CopyTo(destination); Assert.InRange(source.Position, source.Length, int.MaxValue); // Copying the data should have read to the end of the stream or stayed past the end. Assert.Equal(expected, destination.ToArray()); } } public static IEnumerable<object[]> CopyToData() { // Stream is positioned @ beginning of data var data1 = new byte[] { 1, 2, 3 }; var stream1 = new MemoryStream(data1); yield return new object[] { stream1, data1 }; // Stream is positioned in the middle of data var data2 = new byte[] { 0xff, 0xf3, 0xf0 }; var stream2 = new MemoryStream(data2) { Position = 1 }; yield return new object[] { stream2, new byte[] { 0xf3, 0xf0 } }; // Stream is positioned after end of data var data3 = data2; var stream3 = new MemoryStream(data3) { Position = data3.Length + 1 }; yield return new object[] { stream3, Array.Empty<byte>() }; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Abp.Configuration; using Abp.Dependency; using Abp.Domain.Services; using Abp.Domain.Uow; using Abp.Extensions; using Castle.Core.Internal; namespace Abp.Notifications { /// <summary> /// Used to distribute notifications to users. /// </summary> public class DefaultNotificationDistributer : DomainService, INotificationDistributer { private readonly INotificationConfiguration _notificationConfiguration; private readonly INotificationDefinitionManager _notificationDefinitionManager; private readonly INotificationStore _notificationStore; private readonly IUnitOfWorkManager _unitOfWorkManager; private readonly IGuidGenerator _guidGenerator; private readonly IIocResolver _iocResolver; /// <summary> /// Initializes a new instance of the <see cref="NotificationDistributionJob"/> class. /// </summary> public DefaultNotificationDistributer( INotificationConfiguration notificationConfiguration, INotificationDefinitionManager notificationDefinitionManager, INotificationStore notificationStore, IUnitOfWorkManager unitOfWorkManager, IGuidGenerator guidGenerator, IIocResolver iocResolver) { _notificationConfiguration = notificationConfiguration; _notificationDefinitionManager = notificationDefinitionManager; _notificationStore = notificationStore; _unitOfWorkManager = unitOfWorkManager; _guidGenerator = guidGenerator; _iocResolver = iocResolver; } public async Task DistributeAsync(Guid notificationId) { await _unitOfWorkManager.WithUnitOfWorkAsync(async () => { var notificationInfo = await _notificationStore.GetNotificationOrNullAsync(notificationId); if (notificationInfo == null) { Logger.Warn( "NotificationDistributionJob can not continue since could not found notification by id: " + notificationId); return; } var users = await GetUsersAsync(notificationInfo); var userNotifications = await SaveUserNotificationsAsync(users, notificationInfo); await _notificationStore.DeleteNotificationAsync(notificationInfo); await NotifyAsync(userNotifications.ToArray()); }); } protected virtual async Task<UserIdentifier[]> GetUsersAsync(NotificationInfo notificationInfo) { List<UserIdentifier> userIds; if (!notificationInfo.UserIds.IsNullOrEmpty()) { //Directly get from UserIds userIds = notificationInfo .UserIds .Split(",") .Select(uidAsStr => UserIdentifier.Parse(uidAsStr)) .Where(uid => SettingManager.GetSettingValueForUser<bool>(NotificationSettingNames.ReceiveNotifications, uid.TenantId, uid.UserId)) .ToList(); } else { //Get subscribed users var tenantIds = GetTenantIds(notificationInfo); List<NotificationSubscriptionInfo> subscriptions; if (tenantIds.IsNullOrEmpty() || (tenantIds.Length == 1 && tenantIds[0] == NotificationInfo.AllTenantIds.To<int>())) { //Get all subscribed users of all tenants subscriptions = await _notificationStore.GetSubscriptionsAsync( notificationInfo.NotificationName, notificationInfo.EntityTypeName, notificationInfo.EntityId ); } else { //Get all subscribed users of specified tenant(s) subscriptions = await _notificationStore.GetSubscriptionsAsync( tenantIds, notificationInfo.NotificationName, notificationInfo.EntityTypeName, notificationInfo.EntityId ); } //Remove invalid subscriptions var invalidSubscriptions = new Dictionary<Guid, NotificationSubscriptionInfo>(); //TODO: Group subscriptions per tenant for potential performance improvement foreach (var subscription in subscriptions) { using (CurrentUnitOfWork.SetTenantId(subscription.TenantId)) { if (!await _notificationDefinitionManager.IsAvailableAsync(notificationInfo.NotificationName, new UserIdentifier(subscription.TenantId, subscription.UserId)) || !SettingManager.GetSettingValueForUser<bool>(NotificationSettingNames.ReceiveNotifications, subscription.TenantId, subscription.UserId)) { invalidSubscriptions[subscription.Id] = subscription; } } } subscriptions.RemoveAll(s => invalidSubscriptions.ContainsKey(s.Id)); //Get user ids userIds = subscriptions .Select(s => new UserIdentifier(s.TenantId, s.UserId)) .ToList(); } if (!notificationInfo.ExcludedUserIds.IsNullOrEmpty()) { //Exclude specified users. var excludedUserIds = notificationInfo .ExcludedUserIds .Split(",") .Select(uidAsStr => UserIdentifier.Parse(uidAsStr)) .ToList(); userIds.RemoveAll(uid => excludedUserIds.Any(euid => euid.Equals(uid))); } return userIds.ToArray(); } protected virtual UserIdentifier[] GetUsers(NotificationInfo notificationInfo) { return _unitOfWorkManager.WithUnitOfWork(() => { List<UserIdentifier> userIds; if (!notificationInfo.UserIds.IsNullOrEmpty()) { //Directly get from UserIds userIds = notificationInfo .UserIds .Split(",") .Select(uidAsStr => UserIdentifier.Parse(uidAsStr)) .Where(uid => SettingManager.GetSettingValueForUser<bool>(NotificationSettingNames.ReceiveNotifications, uid.TenantId, uid.UserId)) .ToList(); } else { //Get subscribed users var tenantIds = GetTenantIds(notificationInfo); List<NotificationSubscriptionInfo> subscriptions; if (tenantIds.IsNullOrEmpty() || (tenantIds.Length == 1 && tenantIds[0] == NotificationInfo.AllTenantIds.To<int>())) { //Get all subscribed users of all tenants subscriptions = _notificationStore.GetSubscriptions( notificationInfo.NotificationName, notificationInfo.EntityTypeName, notificationInfo.EntityId ); } else { //Get all subscribed users of specified tenant(s) subscriptions = _notificationStore.GetSubscriptions( tenantIds, notificationInfo.NotificationName, notificationInfo.EntityTypeName, notificationInfo.EntityId ); } //Remove invalid subscriptions var invalidSubscriptions = new Dictionary<Guid, NotificationSubscriptionInfo>(); //TODO: Group subscriptions per tenant for potential performance improvement foreach (var subscription in subscriptions) { using (CurrentUnitOfWork.SetTenantId(subscription.TenantId)) { if (!_notificationDefinitionManager.IsAvailable(notificationInfo.NotificationName, new UserIdentifier(subscription.TenantId, subscription.UserId)) || !SettingManager.GetSettingValueForUser<bool>( NotificationSettingNames.ReceiveNotifications, subscription.TenantId, subscription.UserId)) { invalidSubscriptions[subscription.Id] = subscription; } } } subscriptions.RemoveAll(s => invalidSubscriptions.ContainsKey(s.Id)); //Get user ids userIds = subscriptions .Select(s => new UserIdentifier(s.TenantId, s.UserId)) .ToList(); } if (!notificationInfo.ExcludedUserIds.IsNullOrEmpty()) { //Exclude specified users. var excludedUserIds = notificationInfo .ExcludedUserIds .Split(",") .Select(uidAsStr => UserIdentifier.Parse(uidAsStr)) .ToList(); userIds.RemoveAll(uid => excludedUserIds.Any(euid => euid.Equals(uid))); } return userIds.ToArray(); }); } private static int?[] GetTenantIds(NotificationInfo notificationInfo) { if (notificationInfo.TenantIds.IsNullOrEmpty()) { return null; } return notificationInfo .TenantIds .Split(",") .Select(tenantIdAsStr => tenantIdAsStr == "null" ? (int?) null : (int?) tenantIdAsStr.To<int>()) .ToArray(); } protected virtual async Task<List<UserNotification>> SaveUserNotificationsAsync(UserIdentifier[] users, NotificationInfo notificationInfo) { return await _unitOfWorkManager.WithUnitOfWorkAsync(async () => { var userNotifications = new List<UserNotification>(); var tenantGroups = users.GroupBy(user => user.TenantId); foreach (var tenantGroup in tenantGroups) { using (_unitOfWorkManager.Current.SetTenantId(tenantGroup.Key)) { var tenantNotificationInfo = new TenantNotificationInfo(_guidGenerator.Create(), tenantGroup.Key, notificationInfo); await _notificationStore.InsertTenantNotificationAsync(tenantNotificationInfo); await _unitOfWorkManager.Current.SaveChangesAsync(); //To get tenantNotification.Id. var tenantNotification = tenantNotificationInfo.ToTenantNotification(); foreach (var user in tenantGroup) { var userNotification = new UserNotificationInfo(_guidGenerator.Create()) { TenantId = tenantGroup.Key, UserId = user.UserId, TenantNotificationId = tenantNotificationInfo.Id }; await _notificationStore.InsertUserNotificationAsync(userNotification); userNotifications.Add(userNotification.ToUserNotification(tenantNotification)); } await CurrentUnitOfWork.SaveChangesAsync(); //To get Ids of the notifications } } return userNotifications; }); } protected virtual List<UserNotification> SaveUserNotifications( UserIdentifier[] users, NotificationInfo notificationInfo) { return _unitOfWorkManager.WithUnitOfWork(() => { var userNotifications = new List<UserNotification>(); var tenantGroups = users.GroupBy(user => user.TenantId); foreach (var tenantGroup in tenantGroups) { using (_unitOfWorkManager.Current.SetTenantId(tenantGroup.Key)) { var tenantNotificationInfo = new TenantNotificationInfo(_guidGenerator.Create(), tenantGroup.Key, notificationInfo); _notificationStore.InsertTenantNotification(tenantNotificationInfo); _unitOfWorkManager.Current.SaveChanges(); //To get tenantNotification.Id. var tenantNotification = tenantNotificationInfo.ToTenantNotification(); foreach (var user in tenantGroup) { var userNotification = new UserNotificationInfo(_guidGenerator.Create()) { TenantId = tenantGroup.Key, UserId = user.UserId, TenantNotificationId = tenantNotificationInfo.Id }; _notificationStore.InsertUserNotification(userNotification); userNotifications.Add(userNotification.ToUserNotification(tenantNotification)); } CurrentUnitOfWork.SaveChanges(); //To get Ids of the notifications } } return userNotifications; }); } #region Protected methods protected virtual async Task NotifyAsync(UserNotification[] userNotifications) { foreach (var notifierType in _notificationConfiguration.Notifiers) { try { using (var notifier = _iocResolver.ResolveAsDisposable<IRealTimeNotifier>(notifierType)) { await notifier.Object.SendNotificationsAsync(userNotifications); } } catch (Exception ex) { Logger.Warn(ex.ToString(), ex); } } } #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. using System.Runtime.InteropServices; namespace System.Runtime { using System.Runtime.InteropServices; // CONTRACT with Runtime // The binder expects a RuntimeExport'ed method with name "CreateCommandLine" in the class library // Signature : public string[] fnname (); internal static class CommandLine { [NativeCallable(EntryPoint="InvokeExeMain", CallingConvention = CallingConvention.Cdecl)] public unsafe static int InvokeExeMain(IntPtr pfnUserMain) { string[] commandLine = InternalCreateCommandLine(); return RawCalliHelper.Call<int>(pfnUserMain, commandLine); } [RuntimeExport("CreateCommandLine")] public static string[] InternalCreateCommandLine() => InternalCreateCommandLine(includeArg0: false); internal static unsafe string[] InternalCreateCommandLine(bool includeArg0) { char* pCmdLine = Interop.mincore.GetCommandLine(); int nArgs = SegmentCommandLine(pCmdLine, null, includeArg0); string[] argArray = new string[nArgs]; SegmentCommandLine(pCmdLine, argArray, includeArg0); return argArray; } //---------------------------------------------------------------------------------------------------- // Splits a command line into argc/argv lists, using the VC7 parsing rules. Adapted from CLR's // SegmentCommandLine implementation. // // This functions interface mimics the CommandLineToArgvW api. // private static unsafe int SegmentCommandLine(char * pCmdLine, string[] argArray, bool includeArg0) { int nArgs = 0; char* psrc = pCmdLine; { // First, parse the program name (argv[0]). Argv[0] is parsed under special rules. Anything up to // the first whitespace outside a quoted subtring is accepted. Backslashes are treated as normal // characters. char* psrcOrig = psrc; int arg0Len = ScanArgument0(ref psrc, null); if (includeArg0) { if (argArray != null) { char[] arg0 = new char[arg0Len]; ScanArgument0(ref psrcOrig, arg0); argArray[nArgs] = new string(arg0); } nArgs++; } } bool inquote = false; // loop on each argument for (;;) { if (*psrc != '\0') { while (*psrc == ' ' || *psrc == '\t') { ++psrc; } } if (*psrc == '\0') break; // end of args // scan an argument char* psrcOrig = psrc; bool inquoteOrig = inquote; int argLen = ScanArgument(ref psrc, ref inquote, null); if (argArray != null) { char[] arg = new char[argLen]; ScanArgument(ref psrcOrig, ref inquoteOrig, arg); argArray[nArgs] = new string(arg); } nArgs++; } return nArgs; } private static unsafe int ScanArgument0(ref char* psrc, char[] arg) { // Argv[0] is parsed under special rules. Anything up to // the first whitespace outside a quoted subtring is accepted. Backslashes are treated as normal // characters. int charIdx = 0; bool inquote = false; for (;;) { char c = *psrc++; if (c == '"') { inquote = !inquote; continue; } if (c == '\0' || (!inquote && (c == ' ' || c == '\t'))) { psrc--; break; } if (arg != null) { arg[charIdx] = c; } charIdx++; } return charIdx; } private static unsafe int ScanArgument(ref char* psrc, ref bool inquote, char[] arg) { int charIdx = 0; // loop through scanning one argument for (;;) { bool copychar = true; // Rules: 2N backslashes + " ==> N backslashes and begin/end quote // 2N+1 backslashes + " ==> N backslashes + literal " // N backslashes ==> N backslashes int numslash = 0; while (*psrc == '\\') { // count number of backslashes for use below ++psrc; ++numslash; } if (*psrc == '"') { // if 2N backslashes before, start/end quote, otherwise copy literally if (numslash % 2 == 0) { if (inquote && psrc[1] == '"') { psrc++; // Double quote inside quoted string } else { // skip first quote char and copy second copychar = false; // don't copy quote inquote = !inquote; } } numslash /= 2; // divide numslash by two } // copy slashes while (numslash-- > 0) { if (arg != null) { arg[charIdx] = '\\'; } charIdx++; } // if at end of arg, break loop if (*psrc == '\0' || (!inquote && (*psrc == ' ' || *psrc == '\t'))) break; // copy character into argument if (copychar) { if (arg != null) { arg[charIdx] = *psrc; } charIdx++; } ++psrc; } return charIdx; } } }
/* * Copyright 2012-2015 Aerospike, Inc. * * Portions may be licensed to Aerospike, Inc. under one or more contributor * license agreements. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using Aerospike.Client; namespace Aerospike.Admin { public partial class UserEditForm : Form { private readonly AerospikeClient client; private readonly EditType editType; private readonly List<string> oldRoles; public UserEditForm(AerospikeClient client, EditType editType, UserRow user) { this.client = client; this.editType = editType; InitializeComponent(); switch (editType) { case EditType.CREATE: SetRoles(null); break; case EditType.EDIT: this.Text = "Edit User Roles"; userBox.Enabled = false; userBox.Text = user.name; passwordBox.Enabled = false; passwordVerifyBox.Enabled = false; SetRoles(user.roles); oldRoles = user.roles; break; } } private void CancelClicked(object sender, EventArgs e) { DialogResult = DialogResult.Cancel; this.Close(); } private void SaveClicked(object sender, EventArgs e) { try { SaveUser(); DialogResult = DialogResult.OK; this.Close(); } catch (Exception ex) { MessageBox.Show(ex.Message); } } private void SaveUser() { string user; string password; List<string> roles; switch (editType) { case EditType.CREATE: user = userBox.Text.Trim(); password = VerifyPassword(); roles = GetRoles(); client.CreateUser(null, user, password, roles); break; case EditType.EDIT: user = userBox.Text.Trim(); roles = GetRoles(); ReplaceRoles(user, roles); break; } } private string VerifyPassword() { string password = passwordBox.Text.Trim(); string passwordVerify = passwordVerifyBox.Text.Trim(); if (password.Length < 5 || password.Length > 30) { throw new Exception("Password must be between 5 and 30 characters in length."); } if (! password.Equals(passwordVerify)) { throw new Exception("Passwords do not match."); } return password; } private void SetRoles(List<string> rolesUser) { List<Role> rolesAll = Globals.GetAllRoles(); if (rolesUser != null) { foreach (Role role in rolesAll) { bool found = FindRole(rolesUser, role.name); rolesBox.Items.Add(role.name, found); } } else { foreach (Role role in rolesAll) { rolesBox.Items.Add(role.name, false); } } int height = rolesBox.GetItemRectangle(0).Height * rolesBox.Items.Count; if (height > 600) { height = 600; } this.Height += height - rolesBox.ClientSize.Height; //rolesBox.ClientSize = new Size(rolesBox.ClientSize.Width, height); } private List<string> GetRoles() { List<string> list = new List<string>(); int max = rolesBox.Items.Count; for (int i = 0; i < max; i++) { if (rolesBox.GetItemChecked(i)) { string text = rolesBox.GetItemText(rolesBox.Items[i]); list.Add(text); } } return list; } private void ReplaceRoles(string user, List<string> roles) { // Find grants. List<string> grantRoles = new List<string>(); foreach (string role in roles) { if (!FindRole(oldRoles, role)) { grantRoles.Add(role); } } // Find revokes. List<string> revokeRoles = new List<string>(); foreach (string oldRole in oldRoles) { if (!FindRole(roles, oldRole)) { revokeRoles.Add(oldRole); } } if (grantRoles.Count > 0) { client.GrantRoles(null, user, grantRoles); } if (revokeRoles.Count > 0) { client.RevokeRoles(null, user, revokeRoles); } } private static bool FindRole(List<string> roles, string search) { foreach (string role in roles) { if (role.Equals(search)) { return true; } } return false; } public string UserName { get { return userBox.Text.Trim(); } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace EvanBaCloudIPs.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); } } } }
// 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 global::System; using global::System.Reflection; using global::System.Diagnostics; using global::System.Collections.Generic; using global::System.Runtime.CompilerServices; using global::System.Reflection.Runtime.General; using global::System.Reflection.Runtime.TypeInfos; using global::System.Reflection.Runtime.MethodInfos; using global::System.Reflection.Runtime.ParameterInfos; using global::System.Reflection.Runtime.CustomAttributes; using global::Internal.Metadata.NativeFormat; using global::Internal.Reflection.Core.Execution; using global::Internal.Reflection.Extensibility; using global::Internal.Reflection.Tracing; namespace System.Reflection.Runtime.EventInfos { // // The runtime's implementation of EventInfo's // [DebuggerDisplay("{_debugName}")] internal sealed partial class RuntimeEventInfo : ExtensibleEventInfo, ITraceableTypeMember { // // eventHandle - the "tkEventDef" that identifies the event. // definingType - the "tkTypeDef" that defined the field (this is where you get the metadata reader that created eventHandle.) // contextType - the type that supplies the type context (i.e. substitutions for generic parameters.) Though you // get your raw information from "definingType", you report "contextType" as your DeclaringType property. // // For example: // // typeof(Foo<>).GetTypeInfo().DeclaredMembers // // The definingType and contextType are both Foo<> // // typeof(Foo<int,String>).GetTypeInfo().DeclaredMembers // // The definingType is "Foo<,>" // The contextType is "Foo<int,String>" // // We don't report any DeclaredMembers for arrays or generic parameters so those don't apply. // private RuntimeEventInfo(EventHandle eventHandle, RuntimeNamedTypeInfo definingTypeInfo, RuntimeTypeInfo contextTypeInfo) { _eventHandle = eventHandle; _definingTypeInfo = definingTypeInfo; _contextTypeInfo = contextTypeInfo; _reader = definingTypeInfo.Reader; _event = eventHandle.GetEvent(_reader); } public sealed override void AddEventHandler(Object target, Delegate handler) { MethodInfo addMethod = this.AddMethod; if (!addMethod.IsPublic) throw new InvalidOperationException(SR.InvalidOperation_NoPublicAddMethod); addMethod.Invoke(target, new Object[] { handler }); } public sealed override MethodInfo AddMethod { get { #if ENABLE_REFLECTION_TRACE if (ReflectionTrace.Enabled) ReflectionTrace.EventInfo_AddMethod(this); #endif foreach (MethodSemanticsHandle methodSemanticsHandle in _event.MethodSemantics) { MethodSemantics methodSemantics = methodSemanticsHandle.GetMethodSemantics(_reader); if (methodSemantics.Attributes == MethodSemanticsAttributes.AddOn) { return RuntimeNamedMethodInfo.GetRuntimeNamedMethodInfo(methodSemantics.Method, _definingTypeInfo, _contextTypeInfo); } } throw new BadImageFormatException(); // Added is a required method. } } public sealed override EventAttributes Attributes { get { return _event.Flags; } } public sealed override IEnumerable<CustomAttributeData> CustomAttributes { get { #if ENABLE_REFLECTION_TRACE if (ReflectionTrace.Enabled) ReflectionTrace.EventInfo_CustomAttributes(this); #endif foreach (CustomAttributeData cad in RuntimeCustomAttributeData.GetCustomAttributes(_definingTypeInfo.ReflectionDomain, _reader, _event.CustomAttributes)) yield return cad; ExecutionDomain executionDomain = _definingTypeInfo.ReflectionDomain as ExecutionDomain; if (executionDomain != null) { foreach (CustomAttributeData cad in executionDomain.ExecutionEnvironment.GetPsuedoCustomAttributes(_reader, _eventHandle, _definingTypeInfo.TypeDefinitionHandle)) yield return cad; } } } public sealed override Type DeclaringType { get { #if ENABLE_REFLECTION_TRACE if (ReflectionTrace.Enabled) ReflectionTrace.EventInfo_DeclaringType(this); #endif return _contextTypeInfo.AsType(); } } public sealed override bool Equals(Object obj) { RuntimeEventInfo other = obj as RuntimeEventInfo; if (other == null) return false; if (!(this._reader == other._reader)) return false; if (!(this._eventHandle.Equals(other._eventHandle))) return false; if (!(this._contextTypeInfo.Equals(other._contextTypeInfo))) return false; return true; } public sealed override int GetHashCode() { return _eventHandle.GetHashCode(); } public sealed override Type EventHandlerType { get { return _definingTypeInfo.ReflectionDomain.Resolve(_reader, _event.Type, _contextTypeInfo.TypeContext); } } public sealed override Module Module { get { return _definingTypeInfo.Module; } } public sealed override String Name { get { #if ENABLE_REFLECTION_TRACE if (ReflectionTrace.Enabled) ReflectionTrace.EventInfo_Name(this); #endif return _event.Name.GetString(_reader); } } public sealed override MethodInfo RaiseMethod { get { #if ENABLE_REFLECTION_TRACE if (ReflectionTrace.Enabled) ReflectionTrace.EventInfo_RaiseMethod(this); #endif foreach (MethodSemanticsHandle methodSemanticsHandle in _event.MethodSemantics) { MethodSemantics methodSemantics = methodSemanticsHandle.GetMethodSemantics(_reader); if (methodSemantics.Attributes == MethodSemanticsAttributes.Fire) { return RuntimeNamedMethodInfo.GetRuntimeNamedMethodInfo(methodSemantics.Method, _definingTypeInfo, _contextTypeInfo); } } return null; } } public sealed override void RemoveEventHandler(Object target, Delegate handler) { MethodInfo removeMethod = this.RemoveMethod; if (!removeMethod.IsPublic) throw new InvalidOperationException(SR.InvalidOperation_NoPublicRemoveMethod); removeMethod.Invoke(target, new Object[] { handler }); } public sealed override MethodInfo RemoveMethod { get { #if ENABLE_REFLECTION_TRACE if (ReflectionTrace.Enabled) ReflectionTrace.EventInfo_RemoveMethod(this); #endif foreach (MethodSemanticsHandle methodSemanticsHandle in _event.MethodSemantics) { MethodSemantics methodSemantics = methodSemanticsHandle.GetMethodSemantics(_reader); if (methodSemantics.Attributes == MethodSemanticsAttributes.RemoveOn) { return RuntimeNamedMethodInfo.GetRuntimeNamedMethodInfo(methodSemantics.Method, _definingTypeInfo, _contextTypeInfo); } } throw new BadImageFormatException(); // Removed is a required method. } } public sealed override String ToString() { MethodInfo addMethod = this.AddMethod; ParameterInfo[] parameters = addMethod.GetParameters(); if (parameters.Length == 0) throw new InvalidOperationException(); // Legacy: Why is a ToString() intentionally throwing an exception? RuntimeParameterInfo runtimeParameterInfo = (RuntimeParameterInfo)(parameters[0]); return runtimeParameterInfo.ParameterTypeString + " " + this.Name; } String ITraceableTypeMember.MemberName { get { return _event.Name.GetString(_reader); } } Type ITraceableTypeMember.ContainingType { get { return _contextTypeInfo.AsType(); } } private RuntimeEventInfo WithDebugName() { bool populateDebugNames = DeveloperExperienceState.DeveloperExperienceModeEnabled; #if DEBUG populateDebugNames = true; #endif if (!populateDebugNames) return this; if (_debugName == null) { _debugName = "Constructing..."; // Protect against any inadvertent reentrancy. _debugName = ((ITraceableTypeMember)this).MemberName; } return this; } private RuntimeNamedTypeInfo _definingTypeInfo; private EventHandle _eventHandle; private RuntimeTypeInfo _contextTypeInfo; private MetadataReader _reader; private Event _event; private String _debugName; } }
//----------------------------------------------------------------------- // <copyright file="EmulatorDataTypes.cs" company="Google Inc."> // Copyright 2016 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. // </copyright> //----------------------------------------------------------------------- using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using proto; /// @cond namespace Gvr.Internal { struct EmulatorGyroEvent { public readonly long timestamp; public readonly Vector3 value; public EmulatorGyroEvent(PhoneEvent.Types.GyroscopeEvent proto) { timestamp = proto.Timestamp; value = new Vector3(proto.X, proto.Y, proto.Z); } } struct EmulatorAccelEvent { public readonly long timestamp; public readonly Vector3 value; public EmulatorAccelEvent(PhoneEvent.Types.AccelerometerEvent proto) { timestamp = proto.Timestamp; value = new Vector3(proto.X, proto.Y, proto.Z); } } struct EmulatorTouchEvent { // Action constants. These should match the constants in the Android // MotionEvent: // http://developer.android.com/reference/android/view/MotionEvent.html#ACTION_CANCEL public enum Action { kActionDown = 0, kActionUp = 1, kActionMove = 2, kActionCancel = 3, kActionPointerDown = 5, kActionPointerUp = 6, kActionHoverMove = 7, kActionHoverEnter = 9, kActionHoverExit = 10 } // Use getActionMasked() and getActionPointer() instead. private readonly int action; public readonly int relativeTimestamp; public readonly List<Pointer> pointers; public struct Pointer { public readonly int fingerId; public readonly float normalizedX; public readonly float normalizedY; public Pointer(int fingerId, float normalizedX, float normalizedY) { this.fingerId = fingerId; this.normalizedX = normalizedX; this.normalizedY = normalizedY; } public override string ToString() { return string.Format("({0}, {1}, {2})", fingerId, normalizedX, normalizedY); } } public EmulatorTouchEvent(PhoneEvent.Types.MotionEvent proto, long lastDownTimeMs) { action = proto.Action; relativeTimestamp = (Action)(proto.Action & ACTION_MASK) == Action.kActionDown ? 0 : (int)(proto.Timestamp - lastDownTimeMs); pointers = new List<Pointer>(); foreach (PhoneEvent.Types.MotionEvent.Types.Pointer pointer in proto.PointersList) { pointers.Add( new Pointer(pointer.Id, pointer.NormalizedX, pointer.NormalizedY)); } } public EmulatorTouchEvent(Action action, int pointerId, int relativeTimestamp, List<Pointer> pointers) { int fingerIndex = 0; if (action == Action.kActionPointerDown || action == Action.kActionPointerUp) { fingerIndex = findPointerIndex(pointerId, pointers); if (fingerIndex == -1) { Debug.LogWarning("Could not find specific fingerId " + pointerId + " in the supplied list of pointers."); fingerIndex = 0; } } this.action = getActionUnmasked(action, fingerIndex); this.relativeTimestamp = relativeTimestamp; this.pointers = pointers; } // See Android's getActionMasked() and getActionIndex(). private static readonly int ACTION_POINTER_INDEX_SHIFT = 8; private static readonly int ACTION_POINTER_INDEX_MASK = 0xff00; private static readonly int ACTION_MASK = 0xff; public Action getActionMasked() { return (Action)(action & ACTION_MASK); } public Pointer getActionPointer() { int index = (action & ACTION_POINTER_INDEX_MASK) >> ACTION_POINTER_INDEX_SHIFT; return pointers[index]; } private static int getActionUnmasked(Action action, int fingerIndex) { return ((int)action) | (fingerIndex << ACTION_POINTER_INDEX_SHIFT); } private static int findPointerIndex(int fingerId, List<Pointer> pointers) { // Encode the fingerId info into the action, as Android does. See Android's // getActionMasked() and getActionIndex(). int fingerIndex = -1; for (int i = 0; i < pointers.Count; i++) { if (fingerId == pointers[i].fingerId) { fingerIndex = i; break; } } return fingerIndex; } public override string ToString() { System.Text.StringBuilder builder = new System.Text.StringBuilder(); builder.AppendFormat("t = {0}; A = {1}; P = {2}; N = {3}; [", relativeTimestamp, getActionMasked(), getActionPointer().fingerId, pointers.Count); for (int i = 0; i < pointers.Count; i++) { builder.Append(pointers[i]).Append(", "); } builder.Append("]"); return builder.ToString(); } } struct EmulatorOrientationEvent { public readonly long timestamp; public readonly Quaternion orientation; public EmulatorOrientationEvent(PhoneEvent.Types.OrientationEvent proto) { timestamp = proto.Timestamp; // Convert from right-handed coordinates to left-handed. orientation = new Quaternion(proto.X, proto.Y, -proto.Z, proto.W); } } struct EmulatorButtonEvent { // Codes as reported by the IC app (reuses Android KeyEvent codes). public enum ButtonCode { kNone = 0, // android.view.KeyEvent.KEYCODE_HOME kHome = 3, // android.view.KeyEvent.KEYCODE_VOLUME_UP kVolumeUp = 25, // android.view.KeyEvent.KEYCODE_VOLUME_DOWN kVolumeDown = 24, // android.view.KeyEvent.KEYCODE_ENTER kClick = 66, // android.view.KeyEvent.KEYCODE_MENU kApp = 82, } public readonly ButtonCode code; public readonly bool down; public EmulatorButtonEvent(PhoneEvent.Types.KeyEvent proto) { code = (ButtonCode)proto.Code; down = proto.Action == 0; } } } /// @endcond
using System; using System.Threading.Tasks; using System.Collections.Generic; using System.Numerics; using Nethereum.Hex.HexTypes; using Nethereum.ABI.FunctionEncoding.Attributes; using Nethereum.Web3; using Nethereum.RPC.Eth.DTOs; using Nethereum.Contracts.CQS; using Nethereum.Contracts.ContractHandlers; using Nethereum.Contracts; using System.Threading; using Nethereum.ENS.ETHRegistrarController.ContractDefinition; namespace Nethereum.ENS { public partial class ETHRegistrarControllerService { public static Task<TransactionReceipt> DeployContractAndWaitForReceiptAsync(Nethereum.Web3.Web3 web3, ETHRegistrarControllerDeployment eTHRegistrarControllerDeployment, CancellationTokenSource cancellationTokenSource = null) { return web3.Eth.GetContractDeploymentHandler<ETHRegistrarControllerDeployment>().SendRequestAndWaitForReceiptAsync(eTHRegistrarControllerDeployment, cancellationTokenSource); } public static Task<string> DeployContractAsync(Nethereum.Web3.Web3 web3, ETHRegistrarControllerDeployment eTHRegistrarControllerDeployment) { return web3.Eth.GetContractDeploymentHandler<ETHRegistrarControllerDeployment>().SendRequestAsync(eTHRegistrarControllerDeployment); } public static async Task<ETHRegistrarControllerService> DeployContractAndGetServiceAsync(Nethereum.Web3.Web3 web3, ETHRegistrarControllerDeployment eTHRegistrarControllerDeployment, CancellationTokenSource cancellationTokenSource = null) { var receipt = await DeployContractAndWaitForReceiptAsync(web3, eTHRegistrarControllerDeployment, cancellationTokenSource); return new ETHRegistrarControllerService(web3, receipt.ContractAddress); } protected Nethereum.Web3.Web3 Web3{ get; } public ContractHandler ContractHandler { get; } public ETHRegistrarControllerService(Nethereum.Web3.Web3 web3, string contractAddress) { Web3 = web3; ContractHandler = web3.Eth.GetContractHandler(contractAddress); } public Task<BigInteger> MIN_REGISTRATION_DURATIONQueryAsync(MIN_REGISTRATION_DURATIONFunction mIN_REGISTRATION_DURATIONFunction, BlockParameter blockParameter = null) { return ContractHandler.QueryAsync<MIN_REGISTRATION_DURATIONFunction, BigInteger>(mIN_REGISTRATION_DURATIONFunction, blockParameter); } public Task<BigInteger> MIN_REGISTRATION_DURATIONQueryAsync(BlockParameter blockParameter = null) { return ContractHandler.QueryAsync<MIN_REGISTRATION_DURATIONFunction, BigInteger>(null, blockParameter); } public Task<bool> AvailableQueryAsync(AvailableFunction availableFunction, BlockParameter blockParameter = null) { return ContractHandler.QueryAsync<AvailableFunction, bool>(availableFunction, blockParameter); } public Task<bool> AvailableQueryAsync(string name, BlockParameter blockParameter = null) { var availableFunction = new AvailableFunction(); availableFunction.Name = name; return ContractHandler.QueryAsync<AvailableFunction, bool>(availableFunction, blockParameter); } public Task<string> CommitRequestAsync(CommitFunction commitFunction) { return ContractHandler.SendRequestAsync(commitFunction); } public Task<TransactionReceipt> CommitRequestAndWaitForReceiptAsync(CommitFunction commitFunction, CancellationTokenSource cancellationToken = null) { return ContractHandler.SendRequestAndWaitForReceiptAsync(commitFunction, cancellationToken); } public Task<string> CommitRequestAsync(byte[] commitment) { var commitFunction = new CommitFunction(); commitFunction.Commitment = commitment; return ContractHandler.SendRequestAsync(commitFunction); } public Task<TransactionReceipt> CommitRequestAndWaitForReceiptAsync(byte[] commitment, CancellationTokenSource cancellationToken = null) { var commitFunction = new CommitFunction(); commitFunction.Commitment = commitment; return ContractHandler.SendRequestAndWaitForReceiptAsync(commitFunction, cancellationToken); } public Task<BigInteger> CommitmentsQueryAsync(CommitmentsFunction commitmentsFunction, BlockParameter blockParameter = null) { return ContractHandler.QueryAsync<CommitmentsFunction, BigInteger>(commitmentsFunction, blockParameter); } public Task<BigInteger> CommitmentsQueryAsync(byte[] returnValue1, BlockParameter blockParameter = null) { var commitmentsFunction = new CommitmentsFunction(); commitmentsFunction.ReturnValue1 = returnValue1; return ContractHandler.QueryAsync<CommitmentsFunction, BigInteger>(commitmentsFunction, blockParameter); } public Task<bool> IsOwnerQueryAsync(IsOwnerFunction isOwnerFunction, BlockParameter blockParameter = null) { return ContractHandler.QueryAsync<IsOwnerFunction, bool>(isOwnerFunction, blockParameter); } public Task<bool> IsOwnerQueryAsync(BlockParameter blockParameter = null) { return ContractHandler.QueryAsync<IsOwnerFunction, bool>(null, blockParameter); } public Task<byte[]> MakeCommitmentQueryAsync(MakeCommitmentFunction makeCommitmentFunction, BlockParameter blockParameter = null) { return ContractHandler.QueryAsync<MakeCommitmentFunction, byte[]>(makeCommitmentFunction, blockParameter); } public Task<byte[]> MakeCommitmentQueryAsync(string name, string owner, byte[] secret, BlockParameter blockParameter = null) { var makeCommitmentFunction = new MakeCommitmentFunction(); makeCommitmentFunction.Name = name; makeCommitmentFunction.Owner = owner; makeCommitmentFunction.Secret = secret; return ContractHandler.QueryAsync<MakeCommitmentFunction, byte[]>(makeCommitmentFunction, blockParameter); } public Task<byte[]> MakeCommitmentWithConfigQueryAsync(MakeCommitmentWithConfigFunction makeCommitmentWithConfigFunction, BlockParameter blockParameter = null) { return ContractHandler.QueryAsync<MakeCommitmentWithConfigFunction, byte[]>(makeCommitmentWithConfigFunction, blockParameter); } public Task<byte[]> MakeCommitmentWithConfigQueryAsync(string name, string owner, byte[] secret, string resolver, string addr, BlockParameter blockParameter = null) { var makeCommitmentWithConfigFunction = new MakeCommitmentWithConfigFunction(); makeCommitmentWithConfigFunction.Name = name; makeCommitmentWithConfigFunction.Owner = owner; makeCommitmentWithConfigFunction.Secret = secret; makeCommitmentWithConfigFunction.Resolver = resolver; makeCommitmentWithConfigFunction.Addr = addr; return ContractHandler.QueryAsync<MakeCommitmentWithConfigFunction, byte[]>(makeCommitmentWithConfigFunction, blockParameter); } public Task<BigInteger> MaxCommitmentAgeQueryAsync(MaxCommitmentAgeFunction maxCommitmentAgeFunction, BlockParameter blockParameter = null) { return ContractHandler.QueryAsync<MaxCommitmentAgeFunction, BigInteger>(maxCommitmentAgeFunction, blockParameter); } public Task<BigInteger> MaxCommitmentAgeQueryAsync(BlockParameter blockParameter = null) { return ContractHandler.QueryAsync<MaxCommitmentAgeFunction, BigInteger>(null, blockParameter); } public Task<BigInteger> MinCommitmentAgeQueryAsync(MinCommitmentAgeFunction minCommitmentAgeFunction, BlockParameter blockParameter = null) { return ContractHandler.QueryAsync<MinCommitmentAgeFunction, BigInteger>(minCommitmentAgeFunction, blockParameter); } public Task<BigInteger> MinCommitmentAgeQueryAsync(BlockParameter blockParameter = null) { return ContractHandler.QueryAsync<MinCommitmentAgeFunction, BigInteger>(null, blockParameter); } public Task<string> OwnerQueryAsync(OwnerFunction ownerFunction, BlockParameter blockParameter = null) { return ContractHandler.QueryAsync<OwnerFunction, string>(ownerFunction, blockParameter); } public Task<string> OwnerQueryAsync(BlockParameter blockParameter = null) { return ContractHandler.QueryAsync<OwnerFunction, string>(null, blockParameter); } public Task<string> RegisterRequestAsync(RegisterFunction registerFunction) { return ContractHandler.SendRequestAsync(registerFunction); } public Task<TransactionReceipt> RegisterRequestAndWaitForReceiptAsync(RegisterFunction registerFunction, CancellationTokenSource cancellationToken = null) { return ContractHandler.SendRequestAndWaitForReceiptAsync(registerFunction, cancellationToken); } public Task<string> RegisterRequestAsync(string name, string owner, BigInteger duration, byte[] secret) { var registerFunction = new RegisterFunction(); registerFunction.Name = name; registerFunction.Owner = owner; registerFunction.Duration = duration; registerFunction.Secret = secret; return ContractHandler.SendRequestAsync(registerFunction); } public Task<TransactionReceipt> RegisterRequestAndWaitForReceiptAsync(string name, string owner, BigInteger duration, byte[] secret, CancellationTokenSource cancellationToken = null) { var registerFunction = new RegisterFunction(); registerFunction.Name = name; registerFunction.Owner = owner; registerFunction.Duration = duration; registerFunction.Secret = secret; return ContractHandler.SendRequestAndWaitForReceiptAsync(registerFunction, cancellationToken); } public Task<string> RegisterWithConfigRequestAsync(RegisterWithConfigFunction registerWithConfigFunction) { return ContractHandler.SendRequestAsync(registerWithConfigFunction); } public Task<TransactionReceipt> RegisterWithConfigRequestAndWaitForReceiptAsync(RegisterWithConfigFunction registerWithConfigFunction, CancellationTokenSource cancellationToken = null) { return ContractHandler.SendRequestAndWaitForReceiptAsync(registerWithConfigFunction, cancellationToken); } public Task<string> RegisterWithConfigRequestAsync(string name, string owner, BigInteger duration, byte[] secret, string resolver, string addr) { var registerWithConfigFunction = new RegisterWithConfigFunction(); registerWithConfigFunction.Name = name; registerWithConfigFunction.Owner = owner; registerWithConfigFunction.Duration = duration; registerWithConfigFunction.Secret = secret; registerWithConfigFunction.Resolver = resolver; registerWithConfigFunction.Addr = addr; return ContractHandler.SendRequestAsync(registerWithConfigFunction); } public Task<TransactionReceipt> RegisterWithConfigRequestAndWaitForReceiptAsync(string name, string owner, BigInteger duration, byte[] secret, string resolver, string addr, CancellationTokenSource cancellationToken = null) { var registerWithConfigFunction = new RegisterWithConfigFunction(); registerWithConfigFunction.Name = name; registerWithConfigFunction.Owner = owner; registerWithConfigFunction.Duration = duration; registerWithConfigFunction.Secret = secret; registerWithConfigFunction.Resolver = resolver; registerWithConfigFunction.Addr = addr; return ContractHandler.SendRequestAndWaitForReceiptAsync(registerWithConfigFunction, cancellationToken); } public Task<string> RenewRequestAsync(RenewFunction renewFunction) { return ContractHandler.SendRequestAsync(renewFunction); } public Task<TransactionReceipt> RenewRequestAndWaitForReceiptAsync(RenewFunction renewFunction, CancellationTokenSource cancellationToken = null) { return ContractHandler.SendRequestAndWaitForReceiptAsync(renewFunction, cancellationToken); } public Task<string> RenewRequestAsync(string name, BigInteger duration) { var renewFunction = new RenewFunction(); renewFunction.Name = name; renewFunction.Duration = duration; return ContractHandler.SendRequestAsync(renewFunction); } public Task<TransactionReceipt> RenewRequestAndWaitForReceiptAsync(string name, BigInteger duration, CancellationTokenSource cancellationToken = null) { var renewFunction = new RenewFunction(); renewFunction.Name = name; renewFunction.Duration = duration; return ContractHandler.SendRequestAndWaitForReceiptAsync(renewFunction, cancellationToken); } public Task<string> RenounceOwnershipRequestAsync(RenounceOwnershipFunction renounceOwnershipFunction) { return ContractHandler.SendRequestAsync(renounceOwnershipFunction); } public Task<string> RenounceOwnershipRequestAsync() { return ContractHandler.SendRequestAsync<RenounceOwnershipFunction>(); } public Task<TransactionReceipt> RenounceOwnershipRequestAndWaitForReceiptAsync(RenounceOwnershipFunction renounceOwnershipFunction, CancellationTokenSource cancellationToken = null) { return ContractHandler.SendRequestAndWaitForReceiptAsync(renounceOwnershipFunction, cancellationToken); } public Task<TransactionReceipt> RenounceOwnershipRequestAndWaitForReceiptAsync(CancellationTokenSource cancellationToken = null) { return ContractHandler.SendRequestAndWaitForReceiptAsync<RenounceOwnershipFunction>(null, cancellationToken); } public Task<BigInteger> RentPriceQueryAsync(RentPriceFunction rentPriceFunction, BlockParameter blockParameter = null) { return ContractHandler.QueryAsync<RentPriceFunction, BigInteger>(rentPriceFunction, blockParameter); } public Task<BigInteger> RentPriceQueryAsync(string name, BigInteger duration, BlockParameter blockParameter = null) { var rentPriceFunction = new RentPriceFunction(); rentPriceFunction.Name = name; rentPriceFunction.Duration = duration; return ContractHandler.QueryAsync<RentPriceFunction, BigInteger>(rentPriceFunction, blockParameter); } public Task<string> SetCommitmentAgesRequestAsync(SetCommitmentAgesFunction setCommitmentAgesFunction) { return ContractHandler.SendRequestAsync(setCommitmentAgesFunction); } public Task<TransactionReceipt> SetCommitmentAgesRequestAndWaitForReceiptAsync(SetCommitmentAgesFunction setCommitmentAgesFunction, CancellationTokenSource cancellationToken = null) { return ContractHandler.SendRequestAndWaitForReceiptAsync(setCommitmentAgesFunction, cancellationToken); } public Task<string> SetCommitmentAgesRequestAsync(BigInteger minCommitmentAge, BigInteger maxCommitmentAge) { var setCommitmentAgesFunction = new SetCommitmentAgesFunction(); setCommitmentAgesFunction.MinCommitmentAge = minCommitmentAge; setCommitmentAgesFunction.MaxCommitmentAge = maxCommitmentAge; return ContractHandler.SendRequestAsync(setCommitmentAgesFunction); } public Task<TransactionReceipt> SetCommitmentAgesRequestAndWaitForReceiptAsync(BigInteger minCommitmentAge, BigInteger maxCommitmentAge, CancellationTokenSource cancellationToken = null) { var setCommitmentAgesFunction = new SetCommitmentAgesFunction(); setCommitmentAgesFunction.MinCommitmentAge = minCommitmentAge; setCommitmentAgesFunction.MaxCommitmentAge = maxCommitmentAge; return ContractHandler.SendRequestAndWaitForReceiptAsync(setCommitmentAgesFunction, cancellationToken); } public Task<string> SetPriceOracleRequestAsync(SetPriceOracleFunction setPriceOracleFunction) { return ContractHandler.SendRequestAsync(setPriceOracleFunction); } public Task<TransactionReceipt> SetPriceOracleRequestAndWaitForReceiptAsync(SetPriceOracleFunction setPriceOracleFunction, CancellationTokenSource cancellationToken = null) { return ContractHandler.SendRequestAndWaitForReceiptAsync(setPriceOracleFunction, cancellationToken); } public Task<string> SetPriceOracleRequestAsync(string prices) { var setPriceOracleFunction = new SetPriceOracleFunction(); setPriceOracleFunction.Prices = prices; return ContractHandler.SendRequestAsync(setPriceOracleFunction); } public Task<TransactionReceipt> SetPriceOracleRequestAndWaitForReceiptAsync(string prices, CancellationTokenSource cancellationToken = null) { var setPriceOracleFunction = new SetPriceOracleFunction(); setPriceOracleFunction.Prices = prices; return ContractHandler.SendRequestAndWaitForReceiptAsync(setPriceOracleFunction, cancellationToken); } public Task<bool> SupportsInterfaceQueryAsync(SupportsInterfaceFunction supportsInterfaceFunction, BlockParameter blockParameter = null) { return ContractHandler.QueryAsync<SupportsInterfaceFunction, bool>(supportsInterfaceFunction, blockParameter); } public Task<bool> SupportsInterfaceQueryAsync(byte[] interfaceID, BlockParameter blockParameter = null) { var supportsInterfaceFunction = new SupportsInterfaceFunction(); supportsInterfaceFunction.InterfaceID = interfaceID; return ContractHandler.QueryAsync<SupportsInterfaceFunction, bool>(supportsInterfaceFunction, blockParameter); } public Task<string> TransferOwnershipRequestAsync(TransferOwnershipFunction transferOwnershipFunction) { return ContractHandler.SendRequestAsync(transferOwnershipFunction); } public Task<TransactionReceipt> TransferOwnershipRequestAndWaitForReceiptAsync(TransferOwnershipFunction transferOwnershipFunction, CancellationTokenSource cancellationToken = null) { return ContractHandler.SendRequestAndWaitForReceiptAsync(transferOwnershipFunction, cancellationToken); } public Task<string> TransferOwnershipRequestAsync(string newOwner) { var transferOwnershipFunction = new TransferOwnershipFunction(); transferOwnershipFunction.NewOwner = newOwner; return ContractHandler.SendRequestAsync(transferOwnershipFunction); } public Task<TransactionReceipt> TransferOwnershipRequestAndWaitForReceiptAsync(string newOwner, CancellationTokenSource cancellationToken = null) { var transferOwnershipFunction = new TransferOwnershipFunction(); transferOwnershipFunction.NewOwner = newOwner; return ContractHandler.SendRequestAndWaitForReceiptAsync(transferOwnershipFunction, cancellationToken); } public Task<bool> ValidQueryAsync(ValidFunction validFunction, BlockParameter blockParameter = null) { return ContractHandler.QueryAsync<ValidFunction, bool>(validFunction, blockParameter); } public Task<bool> ValidQueryAsync(string name, BlockParameter blockParameter = null) { var validFunction = new ValidFunction(); validFunction.Name = name; return ContractHandler.QueryAsync<ValidFunction, bool>(validFunction, blockParameter); } public Task<string> WithdrawRequestAsync(WithdrawFunction withdrawFunction) { return ContractHandler.SendRequestAsync(withdrawFunction); } public Task<string> WithdrawRequestAsync() { return ContractHandler.SendRequestAsync<WithdrawFunction>(); } public Task<TransactionReceipt> WithdrawRequestAndWaitForReceiptAsync(WithdrawFunction withdrawFunction, CancellationTokenSource cancellationToken = null) { return ContractHandler.SendRequestAndWaitForReceiptAsync(withdrawFunction, cancellationToken); } public Task<TransactionReceipt> WithdrawRequestAndWaitForReceiptAsync(CancellationTokenSource cancellationToken = null) { return ContractHandler.SendRequestAndWaitForReceiptAsync<WithdrawFunction>(null, cancellationToken); } } }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ using System.Collections.Generic; using ParquetSharp.Column; using ParquetSharp.Hadoop.Metadata; using ParquetSharp.Schema; using static ParquetSharp.Schema.PrimitiveType; using static ParquetSharp.Schema.Type; namespace ParquetSharp.Tools.Util { public class MetadataUtils { public const double BAD_COMPRESSION_RATIO_CUTOFF = 0.97; public const double GOOD_COMPRESSION_RATIO_CUTOFF = 1.2; public static void showDetails(PrettyPrintWriter @out, ParquetMetadata meta) { showDetails(@out, meta.getFileMetaData()); long i = 1; foreach (BlockMetaData bmeta in meta.getBlocks()) { @out.println(); showDetails(@out, bmeta, i++); } } public static void showDetails(PrettyPrintWriter @out, FileMetaData meta) { @out.format("creator: %s%n", meta.getCreatedBy()); Dictionary<string, string> extra = meta.getKeyValueMetaData(); if (extra != null) { foreach (KeyValuePair<string, string> entry in extra) { @out.print("extra: "); @out.incrementTabLevel(); @out.format("%s = %s%n", entry.Key, entry.Value); @out.decrementTabLevel(); } } @out.println(); @out.format("file schema: %s%n", meta.getSchema().getName()); @out.rule('-'); showDetails(@out, meta.getSchema()); } public static void showDetails(PrettyPrintWriter @out, BlockMetaData meta) { showDetails(@out, meta, null); } private static void showDetails(PrettyPrintWriter @out, BlockMetaData meta, long? num) { long rows = meta.getRowCount(); long tbs = meta.getTotalByteSize(); long offset = meta.getStartingPos(); @out.format("row group%s: RC:%d TS:%d OFFSET:%d%n", (num == null ? "" : " " + num), rows, tbs, offset); @out.rule('-'); showDetails(@out, meta.getColumns()); } public static void showDetails(PrettyPrintWriter @out, ICollection<ColumnChunkMetaData> ccmeta) { Dictionary<string, object> chunks = new Dictionary<string, object>(); foreach (ColumnChunkMetaData cmeta in ccmeta) { string[] path = cmeta.getPath().toArray(); Dictionary<string, object> current = chunks; for (int i = 0; i < path.Length - 1; ++i) { object next; if (!current.TryGetValue(path[i], out next)) { next = new Dictionary<string, object>(); current.Add(path[i], next); } current = (Dictionary<string, object>)next; } current.put(path[path.Length - 1], cmeta); } showColumnChunkDetails(@out, chunks, 0); } private static void showColumnChunkDetails(PrettyPrintWriter @out, Dictionary<string, object> current, int depth) { foreach (KeyValuePair<string, object> entry in current) { string name = Strings.repeat(".", depth) + entry.Key; object value = entry.Value; if (value is Dictionary<string, object>) { @out.println(name + ": "); showColumnChunkDetails(@out, (Dictionary<string, object>)value, depth + 1); } else { @out.print(name + ": "); showDetails(@out, (ColumnChunkMetaData)value, false); } } } public static void showDetails(PrettyPrintWriter @out, ColumnChunkMetaData meta) { showDetails(@out, meta, true); } private static void showDetails(PrettyPrintWriter @out, ColumnChunkMetaData meta, bool name) { long doff = meta.getDictionaryPageOffset(); long foff = meta.getFirstDataPageOffset(); long tsize = meta.getTotalSize(); long usize = meta.getTotalUncompressedSize(); long count = meta.getValueCount(); double ratio = usize / (double)tsize; string encodings = Joiner.on(',').skipNulls().join(meta.getEncodings()); if (name) { string path = Joiner.on('.').skipNulls().join(meta.getPath()); @out.format("%s: ", path); } @out.format(" %s", meta.getType()); @out.format(" %s", meta.getCodec()); @out.format(" DO:%d", doff); @out.format(" FPO:%d", foff); @out.format(" SZ:%d/%d/%.2f", tsize, usize, ratio); @out.format(" VC:%d", count); if (encodings.Length > 0) @out.format(" ENC:%s", encodings); @out.println(); } public static void showDetails(PrettyPrintWriter @out, ColumnDescriptor desc) { string path = Joiner.on(".").skipNulls().join(desc.getPath()); PrimitiveTypeName type = desc.getType(); int defl = desc.getMaxDefinitionLevel(); int repl = desc.getMaxRepetitionLevel(); @out.format("column desc: %s T:%s R:%d D:%d%n", path, type, repl, defl); } public static void showDetails(PrettyPrintWriter @out, MessageType type) { List<string> cpath = new List<string>(); foreach (Type ftype in type.getFields()) { showDetails(@out, ftype, 0, type, cpath); } } public static void showDetails(PrettyPrintWriter @out, GroupType type) { showDetails(@out, type, 0, null, null); } public static void showDetails(PrettyPrintWriter @out, PrimitiveType type) { showDetails(@out, type, 0, null, null); } public static void showDetails(PrettyPrintWriter @out, Type type) { showDetails(@out, type, 0, null, null); } private static void showDetails(PrettyPrintWriter @out, GroupType type, int depth, MessageType container, List<string> cpath) { string name = Strings.repeat(".", depth) + type.getName(); Repetition rep = type.getRepetition(); int fcount = type.getFieldCount(); @out.format("%s: %s F:%d%n", name, rep, fcount); cpath.Add(type.getName()); foreach (Type ftype in type.getFields()) { showDetails(@out, ftype, depth + 1, container, cpath); } cpath.RemoveAt(cpath.Count - 1); } private static void showDetails(PrettyPrintWriter @out, PrimitiveType type, int depth, MessageType container, List<string> cpath) { string name = Strings.repeat(".", depth) + type.getName(); OriginalType? otype = type.getOriginalType(); Repetition rep = type.getRepetition(); PrimitiveTypeName ptype = type.getPrimitiveTypeName(); @out.format("%s: %s %s", name, rep, ptype); if (otype != null) @out.format(" O:%s", otype); if (container != null) { cpath.Add(type.getName()); string[] paths = cpath.ToArray(); cpath.RemoveAt(cpath.Count - 1); ColumnDescriptor desc = container.getColumnDescription(paths); int defl = desc.getMaxDefinitionLevel(); int repl = desc.getMaxRepetitionLevel(); @out.format(" R:%d D:%d", repl, defl); } @out.println(); } private static void showDetails(PrettyPrintWriter @out, Type type, int depth, MessageType container, List<string> cpath) { if (type is GroupType) { showDetails(@out, type.asGroupType(), depth, container, cpath); return; } else if (type is PrimitiveType) { showDetails(@out, type.asPrimitiveType(), depth, container, cpath); return; } } } }
// // DiverzaClient.cs // // Author: // Eddy Zavaleta <[email protected]> // // Copyright (c) 2013 Eddy Zavaleta, Mictlanix, and contributors. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using System.Collections.Generic; using System.Linq; using System.IO; using System.Net; using System.Net.Security; using System.Security.Cryptography.X509Certificates; using System.Text; using System.Xml; using Mictlanix.CFDv32; using Mictlanix.Diverza.Client.Internals; namespace Mictlanix.Diverza.Client { public class DiverzaClient { public static string DEVELOPMENT_URL = @"https://demotf.buzonfiscal.com/timbrado"; public static string PRODUCTION_URL = @"https://tf.buzonfiscal.com/timbrado"; public DiverzaClient (string url, X509Certificate2 cert) { TimeOut = 15 * 1000; Url = url; Certificate = cert; ServicePointManager.ServerCertificateValidationCallback = (object sp, X509Certificate c, X509Chain r, SslPolicyErrors e) => true; } public DiverzaClient (string url) : this(url, null) { } public int TimeOut { get; set; } public string Url { get; set; } public X509Certificate2 Certificate { get; set; } /// Request a stamp for cfd to the PAC and returns it. /// <exception cref="DiverzaClientException">Unexpected results when requesting stamp.</exception> public TimbreFiscalDigital Stamp (string id, Comprobante cfd) { var env = CreateEnvelope (id, cfd); string response = TryRequest (env); if(response.Length == 0) { throw new DiverzaClientException ("Bad response format."); } var doc = SoapEnvelope.FromXml (response); if(doc.Body.Length == 0) { throw new DiverzaClientException ("Bad response format."); } if(doc.Body[0] is TimbreFiscalDigital) { var tfd = doc.Body[0] as TimbreFiscalDigital; return new TimbreFiscalDigital { UUID = tfd.UUID, FechaTimbrado = tfd.FechaTimbrado, selloCFD = tfd.selloCFD, noCertificadoSAT = tfd.noCertificadoSAT, selloSAT = tfd.selloSAT }; } if(doc.Body[0] is SoapFault) { var fault = doc.Body[0] as SoapFault; throw new DiverzaClientException (fault.FaultCode, fault.FaultString); } return null; } SoapEnvelope CreateEnvelope(string id, Comprobante doc) { var request = new SoapEnvelope { Body = new RequestTimbradoCFD[] { new RequestTimbradoCFD { RefID = id, Documento = new Documento { Archivo = doc.ToXmlBytes (), Tipo = DocumentoTipo.XML, Version = doc.version }, InfoBasica = new InfoBasica { RfcEmisor = doc.Emisor.rfc, RfcReceptor = doc.Receptor.rfc, Serie = doc.serie } } } }; return request; } void DoGetRequest (string url, X509Certificate2 cert) { HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url); if (cert != null) { req.ClientCertificates.Add (cert); } using(var resp = req.GetResponse ()) { using(var stream = resp.GetResponseStream ()) { /*#if DEBUG using(var sr = new StreamReader (stream, Encoding.UTF8)) { System.Diagnostics.Debug.WriteLine (sr.ReadToEnd ()); } #endif*/ } } } string DoPostRequest (string url, X509Certificate2 cert, byte[] data) { var req = (HttpWebRequest)WebRequest.Create(url); req.ContentType = "text/xml; charset=utf-8"; req.Method = "POST"; req.ContentLength = data.Length; if (cert != null) { req.ClientCertificates.Add (cert); } using(var stream = req.GetRequestStream ()) { stream.Write (data, 0, data.Length); } using(var resp = req.GetResponse ()) { using(var stream = resp.GetResponseStream ()) { using(var sr = new StreamReader (stream, Encoding.UTF8)) { return sr.ReadToEnd (); } } } } string TryRequest (SoapEnvelope env) { var bytes = env.ToXmlBytes (); int time_out = TimeOut > 1000 ? TimeOut : 1000; string response = string.Empty; var dt = DateTime.Now; #if DEBUG System.Diagnostics.Debug.WriteLine (env.ToXmlString ()); #endif while((DateTime.Now - dt).TotalMilliseconds < time_out) { try { DoGetRequest (Url, Certificate); response = DoPostRequest (Url, Certificate, bytes); break; } catch(WebException ex) { #if DEBUG //System.Diagnostics.Debug.WriteLine (ex); #endif var hwr = ex.Response as HttpWebResponse; if (hwr != null && hwr.StatusCode == HttpStatusCode.InternalServerError) { using (var sr = new StreamReader(hwr.GetResponseStream())) { response = sr.ReadToEnd (); break; } } } } #if DEBUG System.Diagnostics.Debug.WriteLine (response); #endif return response; } } }
namespace KabMan.Client { partial class RoomDetail { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (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.components = new System.ComponentModel.Container(); DevExpress.XtraEditors.DXErrorProvider.ConditionValidationRule conditionValidationRule1 = new DevExpress.XtraEditors.DXErrorProvider.ConditionValidationRule(); DevExpress.XtraEditors.DXErrorProvider.ConditionValidationRule conditionValidationRule2 = new DevExpress.XtraEditors.DXErrorProvider.ConditionValidationRule(); this.layoutControl1 = new DevExpress.XtraLayout.LayoutControl(); this.BtnCancel = new DevExpress.XtraEditors.SimpleButton(); this.BtnSave = new DevExpress.XtraEditors.SimpleButton(); this.txtRoomName = new DevExpress.XtraEditors.TextEdit(); this.LookUpLocation = new DevExpress.XtraEditors.LookUpEdit(); this.CheckDataCenterExit = new DevExpress.XtraEditors.CheckEdit(); this.layoutControlGroup1 = new DevExpress.XtraLayout.LayoutControlGroup(); this.layoutControlItem2 = new DevExpress.XtraLayout.LayoutControlItem(); this.layoutControlItem1 = new DevExpress.XtraLayout.LayoutControlItem(); this.emptySpaceItem1 = new DevExpress.XtraLayout.EmptySpaceItem(); this.layoutControlItem3 = new DevExpress.XtraLayout.LayoutControlItem(); this.layoutControlItem4 = new DevExpress.XtraLayout.LayoutControlItem(); this.layoutControlItem5 = new DevExpress.XtraLayout.LayoutControlItem(); this.dxValidationProvider1 = new DevExpress.XtraEditors.DXErrorProvider.DXValidationProvider(this.components); ((System.ComponentModel.ISupportInitialize)(this.layoutControl1)).BeginInit(); this.layoutControl1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.txtRoomName.Properties)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.LookUpLocation.Properties)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.CheckDataCenterExit.Properties)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlGroup1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem2)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.emptySpaceItem1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem3)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem4)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem5)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.dxValidationProvider1)).BeginInit(); this.SuspendLayout(); // // layoutControl1 // this.layoutControl1.AllowCustomizationMenu = false; this.layoutControl1.Appearance.DisabledLayoutGroupCaption.ForeColor = System.Drawing.SystemColors.GrayText; this.layoutControl1.Appearance.DisabledLayoutGroupCaption.Options.UseForeColor = true; this.layoutControl1.Appearance.DisabledLayoutItem.ForeColor = System.Drawing.SystemColors.GrayText; this.layoutControl1.Appearance.DisabledLayoutItem.Options.UseForeColor = true; this.layoutControl1.Controls.Add(this.BtnCancel); this.layoutControl1.Controls.Add(this.BtnSave); this.layoutControl1.Controls.Add(this.txtRoomName); this.layoutControl1.Controls.Add(this.LookUpLocation); this.layoutControl1.Controls.Add(this.CheckDataCenterExit); this.layoutControl1.Dock = System.Windows.Forms.DockStyle.Fill; this.layoutControl1.Location = new System.Drawing.Point(0, 0); this.layoutControl1.Name = "layoutControl1"; this.layoutControl1.Root = this.layoutControlGroup1; this.layoutControl1.Size = new System.Drawing.Size(368, 128); this.layoutControl1.TabIndex = 0; this.layoutControl1.Text = "layoutControl1"; // // BtnCancel // this.BtnCancel.Appearance.BackColor = System.Drawing.SystemColors.ButtonFace; this.BtnCancel.Appearance.BackColor2 = System.Drawing.SystemColors.ButtonHighlight; this.BtnCancel.Appearance.BorderColor = System.Drawing.Color.DimGray; this.BtnCancel.Appearance.Options.UseBackColor = true; this.BtnCancel.Appearance.Options.UseBorderColor = true; this.BtnCancel.Appearance.Options.UseForeColor = true; this.BtnCancel.Location = new System.Drawing.Point(281, 99); this.BtnCancel.Name = "BtnCancel"; this.BtnCancel.Size = new System.Drawing.Size(81, 22); this.BtnCancel.StyleController = this.layoutControl1; this.BtnCancel.TabIndex = 1; this.BtnCancel.Text = "Cancel"; this.BtnCancel.Click += new System.EventHandler(this.BtnCancel_Click); // // BtnSave // this.BtnSave.Appearance.BackColor = System.Drawing.SystemColors.ButtonFace; this.BtnSave.Appearance.BackColor2 = System.Drawing.SystemColors.ButtonHighlight; this.BtnSave.Appearance.BorderColor = System.Drawing.Color.DimGray; this.BtnSave.Appearance.Options.UseBackColor = true; this.BtnSave.Appearance.Options.UseBorderColor = true; this.BtnSave.Appearance.Options.UseForeColor = true; this.BtnSave.Location = new System.Drawing.Point(189, 99); this.BtnSave.Name = "BtnSave"; this.BtnSave.Size = new System.Drawing.Size(81, 22); this.BtnSave.StyleController = this.layoutControl1; this.BtnSave.TabIndex = 1; this.BtnSave.Text = "Save"; this.BtnSave.Click += new System.EventHandler(this.BtnSave_Click); // // txtRoomName // this.txtRoomName.Location = new System.Drawing.Point(101, 38); this.txtRoomName.Name = "txtRoomName"; this.txtRoomName.Size = new System.Drawing.Size(261, 20); this.txtRoomName.StyleController = this.layoutControl1; this.txtRoomName.TabIndex = 1; conditionValidationRule1.ConditionOperator = DevExpress.XtraEditors.DXErrorProvider.ConditionOperator.IsNotBlank; conditionValidationRule1.ErrorText = "This value is not valid"; conditionValidationRule1.ErrorType = DevExpress.XtraEditors.DXErrorProvider.ErrorType.Warning; this.dxValidationProvider1.SetValidationRule(this.txtRoomName, conditionValidationRule1); // // LookUpLocation // this.LookUpLocation.Location = new System.Drawing.Point(101, 7); this.LookUpLocation.Name = "LookUpLocation"; this.LookUpLocation.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] { new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Combo)}); this.LookUpLocation.Properties.NullText = "Select to Location!"; this.LookUpLocation.Size = new System.Drawing.Size(261, 20); this.LookUpLocation.StyleController = this.layoutControl1; this.LookUpLocation.TabIndex = 4; conditionValidationRule2.ConditionOperator = DevExpress.XtraEditors.DXErrorProvider.ConditionOperator.IsNotBlank; conditionValidationRule2.ErrorText = "This value is not valid"; conditionValidationRule2.ErrorType = DevExpress.XtraEditors.DXErrorProvider.ErrorType.Warning; this.dxValidationProvider1.SetValidationRule(this.LookUpLocation, conditionValidationRule2); // // CheckDataCenterExit // this.CheckDataCenterExit.Location = new System.Drawing.Point(101, 69); this.CheckDataCenterExit.Name = "CheckDataCenterExit"; this.CheckDataCenterExit.Properties.Caption = ""; this.CheckDataCenterExit.Size = new System.Drawing.Size(261, 19); this.CheckDataCenterExit.StyleController = this.layoutControl1; this.CheckDataCenterExit.TabIndex = 1; // // layoutControlGroup1 // this.layoutControlGroup1.CustomizationFormText = "layoutControlGroup1"; this.layoutControlGroup1.Items.AddRange(new DevExpress.XtraLayout.BaseLayoutItem[] { this.layoutControlItem2, this.layoutControlItem1, this.emptySpaceItem1, this.layoutControlItem3, this.layoutControlItem4, this.layoutControlItem5}); this.layoutControlGroup1.Location = new System.Drawing.Point(0, 0); this.layoutControlGroup1.Name = "Root"; this.layoutControlGroup1.Size = new System.Drawing.Size(368, 128); this.layoutControlGroup1.Spacing = new DevExpress.XtraLayout.Utils.Padding(0, 0, 0, 0); this.layoutControlGroup1.Text = "Root"; this.layoutControlGroup1.TextVisible = false; // // layoutControlItem2 // this.layoutControlItem2.Control = this.txtRoomName; this.layoutControlItem2.CustomizationFormText = "Room Name :"; this.layoutControlItem2.Location = new System.Drawing.Point(0, 31); this.layoutControlItem2.Name = "layoutControlItem2"; this.layoutControlItem2.Size = new System.Drawing.Size(366, 31); this.layoutControlItem2.Text = "Data Center Name"; this.layoutControlItem2.TextLocation = DevExpress.Utils.Locations.Left; this.layoutControlItem2.TextSize = new System.Drawing.Size(89, 20); // // layoutControlItem1 // this.layoutControlItem1.Control = this.LookUpLocation; this.layoutControlItem1.CustomizationFormText = "Location :"; this.layoutControlItem1.Location = new System.Drawing.Point(0, 0); this.layoutControlItem1.Name = "layoutControlItem1"; this.layoutControlItem1.Size = new System.Drawing.Size(366, 31); this.layoutControlItem1.Text = "Location"; this.layoutControlItem1.TextLocation = DevExpress.Utils.Locations.Left; this.layoutControlItem1.TextSize = new System.Drawing.Size(89, 20); // // emptySpaceItem1 // this.emptySpaceItem1.CustomizationFormText = "emptySpaceItem1"; this.emptySpaceItem1.Location = new System.Drawing.Point(0, 92); this.emptySpaceItem1.Name = "emptySpaceItem1"; this.emptySpaceItem1.Size = new System.Drawing.Size(182, 34); this.emptySpaceItem1.Text = "emptySpaceItem1"; this.emptySpaceItem1.TextSize = new System.Drawing.Size(0, 0); // // layoutControlItem3 // this.layoutControlItem3.Control = this.BtnSave; this.layoutControlItem3.CustomizationFormText = "layoutControlItem3"; this.layoutControlItem3.Location = new System.Drawing.Point(182, 92); this.layoutControlItem3.Name = "layoutControlItem3"; this.layoutControlItem3.Size = new System.Drawing.Size(92, 34); this.layoutControlItem3.Text = "layoutControlItem3"; this.layoutControlItem3.TextLocation = DevExpress.Utils.Locations.Left; this.layoutControlItem3.TextSize = new System.Drawing.Size(0, 0); this.layoutControlItem3.TextToControlDistance = 0; this.layoutControlItem3.TextVisible = false; // // layoutControlItem4 // this.layoutControlItem4.Control = this.BtnCancel; this.layoutControlItem4.CustomizationFormText = "layoutControlItem4"; this.layoutControlItem4.Location = new System.Drawing.Point(274, 92); this.layoutControlItem4.Name = "layoutControlItem4"; this.layoutControlItem4.Size = new System.Drawing.Size(92, 34); this.layoutControlItem4.Text = "layoutControlItem4"; this.layoutControlItem4.TextLocation = DevExpress.Utils.Locations.Left; this.layoutControlItem4.TextSize = new System.Drawing.Size(0, 0); this.layoutControlItem4.TextToControlDistance = 0; this.layoutControlItem4.TextVisible = false; // // layoutControlItem5 // this.layoutControlItem5.Control = this.CheckDataCenterExit; this.layoutControlItem5.CustomizationFormText = "layoutControlItem5"; this.layoutControlItem5.Location = new System.Drawing.Point(0, 62); this.layoutControlItem5.Name = "layoutControlItem5"; this.layoutControlItem5.Size = new System.Drawing.Size(366, 30); this.layoutControlItem5.Text = "Data Center Exit"; this.layoutControlItem5.TextLocation = DevExpress.Utils.Locations.Left; this.layoutControlItem5.TextSize = new System.Drawing.Size(89, 0); // // RoomDetail // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(368, 128); this.Controls.Add(this.layoutControl1); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle; this.KeyPreview = true; this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "RoomDetail"; this.ShowInTaskbar = false; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; this.Text = "Data Center Detail"; this.Load += new System.EventHandler(this.RoomDetail_Load); this.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.RoomDetail_KeyPress); ((System.ComponentModel.ISupportInitialize)(this.layoutControl1)).EndInit(); this.layoutControl1.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.txtRoomName.Properties)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.LookUpLocation.Properties)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.CheckDataCenterExit.Properties)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlGroup1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem2)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.emptySpaceItem1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem3)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem4)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem5)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.dxValidationProvider1)).EndInit(); this.ResumeLayout(false); } #endregion private DevExpress.XtraLayout.LayoutControl layoutControl1; private DevExpress.XtraLayout.LayoutControlGroup layoutControlGroup1; private DevExpress.XtraEditors.SimpleButton BtnCancel; private DevExpress.XtraEditors.SimpleButton BtnSave; private DevExpress.XtraEditors.TextEdit txtRoomName; private DevExpress.XtraEditors.LookUpEdit LookUpLocation; private DevExpress.XtraLayout.LayoutControlItem layoutControlItem2; private DevExpress.XtraLayout.LayoutControlItem layoutControlItem1; private DevExpress.XtraLayout.EmptySpaceItem emptySpaceItem1; private DevExpress.XtraLayout.LayoutControlItem layoutControlItem3; private DevExpress.XtraLayout.LayoutControlItem layoutControlItem4; private DevExpress.XtraEditors.CheckEdit CheckDataCenterExit; private DevExpress.XtraLayout.LayoutControlItem layoutControlItem5; private DevExpress.XtraEditors.DXErrorProvider.DXValidationProvider dxValidationProvider1; } }
/* * 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 copyrightD * 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.Text; using System.Runtime.InteropServices; using OMV = OpenMetaverse; namespace OpenSim.Region.PhysicsModule.BulletS { // Classes to allow some type checking for the API // These hold pointers to allocated objects in the unmanaged space. // These classes are subclassed by the various physical implementations of // objects. In particular, there is a version for physical instances in // unmanaged memory ("unman") and one for in managed memory ("XNA"). // Currently, the instances of these classes are a reference to a // physical representation and this has no releationship to other // instances. Someday, refarb the usage of these classes so each instance // refers to a particular physical instance and this class controls reference // counts and such. This should be done along with adding BSShapes. public class BulletWorld { public BulletWorld(uint worldId, BSScene bss) { worldID = worldId; physicsScene = bss; } public uint worldID; // The scene is only in here so very low level routines have a handle to print debug/error messages public BSScene physicsScene; } // An allocated Bullet btRigidBody public class BulletBody { public BulletBody(uint id) { ID = id; collisionType = CollisionType.Static; } public uint ID; public CollisionType collisionType; public virtual void Clear() { } public virtual bool HasPhysicalBody { get { return false; } } // Apply the specificed collision mask into the physical world public virtual bool ApplyCollisionMask(BSScene physicsScene) { // Should assert the body has been added to the physical world. // (The collision masks are stored in the collision proxy cache which only exists for // a collision body that is in the world.) return physicsScene.PE.SetCollisionGroupMask(this, BulletSimData.CollisionTypeMasks[collisionType].group, BulletSimData.CollisionTypeMasks[collisionType].mask); } // Used for log messages for a unique display of the memory/object allocated to this instance public virtual string AddrString { get { return "unknown"; } } public override string ToString() { StringBuilder buff = new StringBuilder(); buff.Append("<id="); buff.Append(ID.ToString()); buff.Append(",p="); buff.Append(AddrString); buff.Append(",c="); buff.Append(collisionType); buff.Append(">"); return buff.ToString(); } } // Handle to btCollisionObject - a shape that can be added to a btRidgidBody public class BulletShape { public BulletShape() { shapeType = BSPhysicsShapeType.SHAPE_UNKNOWN; shapeKey = (System.UInt64)FixedShapeKey.KEY_NONE; isNativeShape = false; } public BSPhysicsShapeType shapeType; public System.UInt64 shapeKey; public bool isNativeShape; public virtual void Clear() { } public virtual bool HasPhysicalShape { get { return false; } } // Make another reference to this physical object. public virtual BulletShape Clone() { return new BulletShape(); } // Return 'true' if this and other refer to the same physical object public virtual bool ReferenceSame(BulletShape xx) { return false; } // Used for log messages for a unique display of the memory/object allocated to this instance public virtual string AddrString { get { return "unknown"; } } public override string ToString() { StringBuilder buff = new StringBuilder(); buff.Append("<p="); buff.Append(AddrString); buff.Append(",s="); buff.Append(shapeType.ToString()); buff.Append(",k="); buff.Append(shapeKey.ToString("X")); buff.Append(",n="); buff.Append(isNativeShape.ToString()); buff.Append(">"); return buff.ToString(); } } // An allocated Bullet btConstraint public class BulletConstraint { public BulletConstraint() { } public virtual void Clear() { } public virtual bool HasPhysicalConstraint { get { return false; } } // Used for log messages for a unique display of the memory/object allocated to this instance public virtual string AddrString { get { return "unknown"; } } } // An allocated HeightMapThing which holds various heightmap info. // Made a class rather than a struct so there would be only one // instance of this and C# will pass around pointers rather // than making copies. public class BulletHMapInfo { public BulletHMapInfo(uint id, float[] hm, float pSizeX, float pSizeY) { ID = id; heightMap = hm; heightMapHandle = GCHandle.Alloc(heightMap, GCHandleType.Pinned); minCoords = new OMV.Vector3(100f, 100f, 25f); maxCoords = new OMV.Vector3(101f, 101f, 26f); minZ = maxZ = 0f; sizeX = pSizeX; sizeY = pSizeY; } public uint ID; public float[] heightMap; public OMV.Vector3 terrainRegionBase; public OMV.Vector3 minCoords; public OMV.Vector3 maxCoords; public float sizeX, sizeY; public float minZ, maxZ; public BulletShape terrainShape; public BulletBody terrainBody; private GCHandle heightMapHandle; public void Release() { if(heightMapHandle.IsAllocated) heightMapHandle.Free(); } } // The general class of collsion object. public enum CollisionType { Avatar, PhantomToOthersAvatar, // An avatar that it phantom to other avatars but not to anything else Groundplane, Terrain, Static, Dynamic, VolumeDetect, // Linkset, // A linkset should be either Static or Dynamic LinksetChild, Unknown }; // Hold specification of group and mask collision flags for a CollisionType public struct CollisionTypeFilterGroup { public CollisionTypeFilterGroup(CollisionType t, uint g, uint m) { type = t; group = g; mask = m; } public CollisionType type; public uint group; public uint mask; }; public static class BulletSimData { // Map of collisionTypes to flags for collision groups and masks. // An object's 'group' is the collison groups this object belongs to // An object's 'filter' is the groups another object has to belong to in order to collide with me // A collision happens if ((obj1.group & obj2.filter) != 0) || ((obj2.group & obj1.filter) != 0) // // As mentioned above, don't use the CollisionFilterGroups definitions directly in the code // but, instead, use references to this dictionary. Finding and debugging // collision flag problems will be made easier. public static Dictionary<CollisionType, CollisionTypeFilterGroup> CollisionTypeMasks = new Dictionary<CollisionType, CollisionTypeFilterGroup>() { { CollisionType.Avatar, new CollisionTypeFilterGroup(CollisionType.Avatar, (uint)CollisionFilterGroups.BCharacterGroup, (uint)(CollisionFilterGroups.BAllGroup)) }, { CollisionType.PhantomToOthersAvatar, new CollisionTypeFilterGroup(CollisionType.PhantomToOthersAvatar, (uint)CollisionFilterGroups.BCharacterGroup, (uint)(CollisionFilterGroups.BAllGroup & ~CollisionFilterGroups.BCharacterGroup)) }, { CollisionType.Groundplane, new CollisionTypeFilterGroup(CollisionType.Groundplane, (uint)CollisionFilterGroups.BGroundPlaneGroup, // (uint)CollisionFilterGroups.BAllGroup) (uint)(CollisionFilterGroups.BCharacterGroup | CollisionFilterGroups.BSolidGroup)) }, { CollisionType.Terrain, new CollisionTypeFilterGroup(CollisionType.Terrain, (uint)CollisionFilterGroups.BTerrainGroup, (uint)(CollisionFilterGroups.BAllGroup & ~CollisionFilterGroups.BStaticGroup)) }, { CollisionType.Static, new CollisionTypeFilterGroup(CollisionType.Static, (uint)CollisionFilterGroups.BStaticGroup, (uint)(CollisionFilterGroups.BCharacterGroup | CollisionFilterGroups.BSolidGroup)) }, { CollisionType.Dynamic, new CollisionTypeFilterGroup(CollisionType.Dynamic, (uint)CollisionFilterGroups.BSolidGroup, (uint)(CollisionFilterGroups.BAllGroup)) }, { CollisionType.VolumeDetect, new CollisionTypeFilterGroup(CollisionType.VolumeDetect, (uint)CollisionFilterGroups.BSensorTrigger, (uint)(~CollisionFilterGroups.BSensorTrigger)) }, { CollisionType.LinksetChild, new CollisionTypeFilterGroup(CollisionType.LinksetChild, (uint)CollisionFilterGroups.BLinksetChildGroup, (uint)(CollisionFilterGroups.BNoneGroup)) // (uint)(CollisionFilterGroups.BCharacterGroup | CollisionFilterGroups.BSolidGroup)) }, }; } }
// // RenderCairo.cs // // Author: // Krzysztof Marecki // // Copyright (c) 2010 Krzysztof Marecki // // This file is part of the NReports project // This file is part of the My-FyiReporting project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections; using System.Globalization; using System.Threading; using fyiReporting.RDL; namespace fyiReporting.RdlGtkViewer { public class RenderCairo : IDisposable { Cairo.Context g; Pango.Layout layout; float scale = 1.0f; float dpiX = 96; float dpiY = 96; public RenderCairo(Cairo.Context g) : this(g, 1.0f) { } public RenderCairo(Cairo.Context g, float scale) { this.g = g; this.layout = Pango.CairoHelper.CreateLayout(g); this.scale = scale; g.Scale(scale, scale); } public void Dispose() { if (layout != null) { layout.Dispose(); } } internal float PixelsX(float x) { return (x * dpiX / 96.0f); } internal float PixelsY(float y) { return (y * dpiY / 96.0f); } private void ProcessPage(Cairo.Context g, IEnumerable p) { foreach (PageItem pi in p) { if (pi is PageTextHtml) { // PageTextHtml is actually a composite object (just like a page) ProcessHtml(pi as PageTextHtml, g); continue; } if (pi is PageLine) { PageLine pl = pi as PageLine; DrawLine( pl.SI.BColorLeft.ToCairoColor(), pl.SI.BStyleLeft, pl.SI.BWidthLeft, g, PixelsX(pl.X), PixelsY(pl.Y), PixelsX(pl.X2), PixelsY(pl.Y2) ); continue; } // RectangleF rect = new RectangleF(PixelsX(pi.X), PixelsY(pi.Y), PixelsX(pi.W), PixelsY(pi.H)); Cairo.Rectangle rect = new Cairo.Rectangle(PixelsX(pi.X), PixelsY(pi.Y), PixelsX(pi.W), PixelsY(pi.H)); if (pi.SI.BackgroundImage != null) { // put out any background image PageImage i = pi.SI.BackgroundImage; DrawImage(i, g, rect); continue; } if (pi is PageText) { PageText pt = pi as PageText; DrawString(pt, g, rect); } if (pi is PageImage) { PageImage i = pi as PageImage; DrawImage(i, g, rect); } if (pi is PageRectangle) { //DrawBackground(g, rect, pi.SI); } // else if (pi is PageEllipse) // { // PageEllipse pe = pi as PageEllipse; // DrawEllipse(pe, g, rect); // } // else if (pi is PagePie) // { // PagePie pp = pi as PagePie; // DrawPie(pp, g, rect); // } // else if (pi is PagePolygon) // { // PagePolygon ppo = pi as PagePolygon; // FillPolygon(ppo, g, rect); // } // else if (pi is PageCurve) // { // PageCurve pc = pi as PageCurve; // DrawCurve(pc.SI.BColorLeft, pc.SI.BStyleLeft, pc.SI.BWidthLeft, // g, pc.Points, pc.Offset, pc.Tension); // } // DrawBorder(pi, g, rect); } } private void ProcessHtml(PageTextHtml pth, Cairo.Context g) { // pth.Build(g); // Builds the subobjects that make up the html this.ProcessPage(g, pth); } private void DrawLine(Cairo.Color c, BorderStyleEnum bs, float w, Cairo.Context g, double x, double y, double x2, double y2) { if (bs == BorderStyleEnum.None//|| c.IsEmpty || w <= 0) // nothing to draw return; g.Save(); // Pen p = null; // p = new Pen(c, w); g.Color = c; g.LineWidth = w; switch (bs) { case BorderStyleEnum.Dashed: // p.DashStyle = DashStyle.Dash; g.SetDash(new double[] { 2, 1 }, 0.0); break; case BorderStyleEnum.Dotted: // p.DashStyle = DashStyle.Dot; g.SetDash(new double[] { 1 }, 0.0); break; case BorderStyleEnum.Double: case BorderStyleEnum.Groove: case BorderStyleEnum.Inset: case BorderStyleEnum.Solid: case BorderStyleEnum.Outset: case BorderStyleEnum.Ridge: case BorderStyleEnum.WindowInset: default: g.SetDash(new double[] { }, 0.0); break; } // g.DrawLine(p, x, y, x2, y2); g.MoveTo(x, y); g.LineTo(x2, y2); g.Stroke(); g.Restore(); } private void DrawImage(PageImage pi, Cairo.Context g, Cairo.Rectangle r) { // Stream strm = null; // System.Drawing.Image im = null; Gdk.Pixbuf im = null; try { // strm = new MemoryStream (pi.ImageData); // im = System.Drawing.Image.FromStream (strm); im = new Gdk.Pixbuf(pi.ImageData); DrawImageSized(pi, im, g, r); } finally { // if (strm != null) // strm.Close(); if (im != null) im.Dispose(); } } private void DrawImageSized(PageImage pi, Gdk.Pixbuf im, Cairo.Context g, Cairo.Rectangle r) { double height, width; // some work variables StyleInfo si = pi.SI; // adjust drawing rectangle based on padding // System.Drawing.RectangleF r2 = new System.Drawing.RectangleF(r.Left + PixelsX(si.PaddingLeft), // r.Top + PixelsY(si.PaddingTop), // r.Width - PixelsX(si.PaddingLeft + si.PaddingRight), // r.Height - PixelsY(si.PaddingTop + si.PaddingBottom)); Cairo.Rectangle r2 = new Cairo.Rectangle(r.X + PixelsX(si.PaddingLeft), r.Y + PixelsY(si.PaddingTop), r.Width - PixelsX(si.PaddingLeft + si.PaddingRight), r.Height - PixelsY(si.PaddingTop + si.PaddingBottom)); Cairo.Rectangle ir; // int work rectangle switch (pi.Sizing) { case ImageSizingEnum.AutoSize: // // Note: GDI+ will stretch an image when you only provide // // the left/top coordinates. This seems pretty stupid since // // it results in the image being out of focus even though // // you don't want the image resized. // if (g.DpiX == im.HorizontalResolution && // g.DpiY == im.VerticalResolution) float imwidth = PixelsX(im.Width); float imheight = PixelsX(im.Height); ir = new Cairo.Rectangle(Convert.ToInt32(r2.X), Convert.ToInt32(r2.Y), imwidth, imheight); // else // ir = new Cairo.Rectangle(Convert.ToInt32(r2.X), Convert.ToInt32(r2.Y), // Convert.ToInt32(r2.Width), Convert.ToInt32(r2.Height)); //g.DrawImage(im, ir); im = im.ScaleSimple((int)r2.Width, (int)r2.Height, Gdk.InterpType.Hyper); g.DrawPixbufRect(im, ir, scale); break; case ImageSizingEnum.Clip: // Region saveRegion = g.Clip; g.Save(); // Region clipRegion = new Region(g.Clip.GetRegionData()); // clipRegion.Intersect(r2); // g.Clip = clipRegion; g.Rectangle(r2); g.Clip(); // if (dpiX == im.HorizontalResolution && // dpiY == im.VerticalResolution) ir = new Cairo.Rectangle(Convert.ToInt32(r2.X), Convert.ToInt32(r2.Y), im.Width, im.Height); // else // ir = new Cairo.Rectangle(Convert.ToInt32(r2.X), Convert.ToInt32(r2.Y), // Convert.ToInt32(r2.Width), Convert.ToInt32(r2.Height)); // g.DrawImage(im, ir); g.DrawPixbufRect(im, r2, scale); // g.Clip = saveRegion; g.Restore(); break; case ImageSizingEnum.FitProportional: double ratioIm = (float)im.Height / (float)im.Width; double ratioR = r2.Height / r2.Width; height = r2.Height; width = r2.Width; if (ratioIm > ratioR) { // this means the rectangle width must be corrected width = height * (1 / ratioIm); } else if (ratioIm < ratioR) { // this means the ractangle height must be corrected height = width * ratioIm; } r2 = new Cairo.Rectangle(r2.X, r2.Y, width, height); g.DrawPixbufRect(im, r2, scale); break; case ImageSizingEnum.Fit: default: g.DrawPixbufRect(im, r2, scale); break; } } private void DrawString(PageText pt, Cairo.Context g, Cairo.Rectangle r) { StyleInfo si = pt.SI; string s = pt.Text; g.Save(); layout = Pango.CairoHelper.CreateLayout(g); // Font drawFont = null; // StringFormat drawFormat = null; // Brush drawBrush = null; // STYLE // System.Drawing.FontStyle fs = 0; // if (si.FontStyle == FontStyleEnum.Italic) // fs |= System.Drawing.FontStyle.Italic; //Pango fonts are scaled to 72dpi, Windows fonts uses 96dpi float fontsize = (si.FontSize * 72 / 96); var font = Pango.FontDescription.FromString(string.Format("{0} {1}", si.GetFontFamily().Name, fontsize * PixelsX(1))); if (si.FontStyle == FontStyleEnum.Italic) font.Style = Pango.Style.Italic; // // switch (si.TextDecoration) // { // case TextDecorationEnum.Underline: // fs |= System.Drawing.FontStyle.Underline; // break; // case TextDecorationEnum.LineThrough: // fs |= System.Drawing.FontStyle.Strikeout; // break; // case TextDecorationEnum.Overline: // case TextDecorationEnum.None: // break; // } // WEIGHT // switch (si.FontWeight) // { // case FontWeightEnum.Bold: // case FontWeightEnum.Bolder: // case FontWeightEnum.W500: // case FontWeightEnum.W600: // case FontWeightEnum.W700: // case FontWeightEnum.W800: // case FontWeightEnum.W900: // fs |= System.Drawing.FontStyle.Bold; // break; // default: // break; // } // try // { // drawFont = new Font(si.GetFontFamily(), si.FontSize, fs); // si.FontSize already in points // } // catch (ArgumentException) // { // drawFont = new Font("Arial", si.FontSize, fs); // if this fails we'll let the error pass thru // } //font.AbsoluteSize = (int)(PixelsX (si.FontSize)); switch (si.FontWeight) { case FontWeightEnum.Bold: case FontWeightEnum.Bolder: case FontWeightEnum.W500: case FontWeightEnum.W600: case FontWeightEnum.W700: case FontWeightEnum.W800: case FontWeightEnum.W900: font.Weight = Pango.Weight.Bold; break; } Pango.FontDescription oldfont = layout.FontDescription; layout.FontDescription = font; // ALIGNMENT // drawFormat = new StringFormat(); // switch (si.TextAlign) // { // case TextAlignEnum.Right: // drawFormat.Alignment = StringAlignment.Far; // break; // case TextAlignEnum.Center: // drawFormat.Alignment = StringAlignment.Center; // break; // case TextAlignEnum.Left: // default: // drawFormat.Alignment = StringAlignment.Near; // break; // } switch (si.TextAlign) { case TextAlignEnum.Right: layout.Alignment = Pango.Alignment.Right; break; case TextAlignEnum.Center: layout.Alignment = Pango.Alignment.Center; break; case TextAlignEnum.Left: default: layout.Alignment = Pango.Alignment.Left; break; } layout.Width = Pango.Units.FromPixels((int)(r.Width - si.PaddingLeft - si.PaddingRight - 2)); // layout.Width = (int)Pango.Units.FromPixels((int)r.Width); layout.SetText(s); // if (pt.SI.WritingMode == WritingModeEnum.tb_rl) // { // drawFormat.FormatFlags |= StringFormatFlags.DirectionRightToLeft; // drawFormat.FormatFlags |= StringFormatFlags.DirectionVertical; // } // switch (si.VerticalAlign) // { // case VerticalAlignEnum.Bottom: // drawFormat.LineAlignment = StringAlignment.Far; // break; // case VerticalAlignEnum.Middle: // drawFormat.LineAlignment = StringAlignment.Center; // break; // case VerticalAlignEnum.Top: // default: // drawFormat.LineAlignment = StringAlignment.Near; // break; // } // Pango.Rectangle logical; Pango.Rectangle ink; layout.GetExtents(out ink, out logical); double height = logical.Height / Pango.Scale.PangoScale; double y = 0; switch (si.VerticalAlign) { case VerticalAlignEnum.Top: y = r.Y + si.PaddingTop; break; case VerticalAlignEnum.Middle: y = r.Y + (r.Height - height) / 2; break; case VerticalAlignEnum.Bottom: y = r.Y + (r.Height - height) - si.PaddingBottom; break; } // draw the background DrawBackground(g, r, si); // adjust drawing rectangle based on padding // Cairo.Rectangle r2 = new Cairo.Rectangle(r.X + si.PaddingLeft, // r.Y + si.PaddingTop, // r.Width - si.PaddingLeft - si.PaddingRight, // r.Height - si.PaddingTop - si.PaddingBottom); Cairo.Rectangle box = new Cairo.Rectangle( r.X + si.PaddingLeft + 1, y, r.Width, r.Height); //drawBrush = new SolidBrush(si.Color); g.Color = si.Color.ToCairoColor(); // if (pt.NoClip) // request not to clip text // { // g.DrawString(pt.Text, drawFont, drawBrush, new PointF(r.Left, r.Top), drawFormat); // //HighlightString(g, pt, new RectangleF(r.Left, r.Top, float.MaxValue, float.MaxValue),drawFont, drawFormat); // } // else // { // g.DrawString(pt.Text, drawFont, drawBrush, r2, drawFormat); // //HighlightString(g, pt, r2, drawFont, drawFormat); // } g.MoveTo(box.X, box.Y); Pango.CairoHelper.ShowLayout(g, layout); layout.FontDescription = oldfont; g.Restore(); } private void DrawBackground(Cairo.Context g, Cairo.Rectangle rect, StyleInfo si) { // LinearGradientBrush linGrBrush = null; // SolidBrush sb = null; if (si.BackgroundColor.IsEmpty) return; g.Save(); Cairo.Color c = si.BackgroundColor.ToCairoColor(); Cairo.Gradient gradient = null; if (si.BackgroundGradientType != BackgroundGradientTypeEnum.None && !si.BackgroundGradientEndColor.IsEmpty) { Cairo.Color ec = si.BackgroundGradientEndColor.ToCairoColor(); switch (si.BackgroundGradientType) { case BackgroundGradientTypeEnum.LeftRight: // linGrBrush = new LinearGradientBrush(rect, c, ec, LinearGradientMode.Horizontal); gradient = new Cairo.LinearGradient(rect.X, rect.Y, rect.X + rect.Width, rect.Y); break; case BackgroundGradientTypeEnum.TopBottom: // linGrBrush = new LinearGradientBrush(rect, c, ec, LinearGradientMode.Vertical); gradient = new Cairo.LinearGradient(rect.X, rect.Y, rect.X, rect.Y + rect.Height); break; case BackgroundGradientTypeEnum.Center: // linGrBrush = new LinearGradientBrush(rect, c, ec, LinearGradientMode.Horizontal); throw new NotSupportedException(); // break; case BackgroundGradientTypeEnum.DiagonalLeft: // linGrBrush = new LinearGradientBrush(rect, c, ec, LinearGradientMode.ForwardDiagonal); gradient = new Cairo.LinearGradient(rect.X, rect.Y, rect.X + rect.Width, rect.Y + rect.Height); break; case BackgroundGradientTypeEnum.DiagonalRight: // linGrBrush = new LinearGradientBrush(rect, c, ec, LinearGradientMode.BackwardDiagonal); gradient = new Cairo.LinearGradient(rect.X + rect.Width, rect.Y + rect.Height, rect.X, rect.Y); break; case BackgroundGradientTypeEnum.HorizontalCenter: // linGrBrush = new LinearGradientBrush(rect, c, ec, LinearGradientMode.Horizontal); throw new NotSupportedException(); // break; case BackgroundGradientTypeEnum.VerticalCenter: // linGrBrush = new LinearGradientBrush(rect, c, ec, LinearGradientMode.Vertical); throw new NotSupportedException(); // break; default: break; } gradient.AddColorStop(0, c); gradient.AddColorStop(1, ec); } if (gradient != null) { //// g.FillRectangle(linGrBrush, rect); g.FillRectangle(rect, gradient); gradient.Destroy(); } else if (!si.BackgroundColor.IsEmpty) { g.FillRectangle(rect, c); // g.DrawRoundedRectangle (rect, 2, c, 1); // g.FillRoundedRectangle (rect, 8, c); } g.Restore(); } private void DrawBorder(PageItem pi, Cairo.Context g, Cairo.Rectangle r) { if (r.Height <= 0 || r.Width <= 0) // no bounding box to use return; double right = r.X + r.Width; double bottom = r.Y + r.Height; StyleInfo si = pi.SI; DrawLine(si.BColorTop.ToCairoColor(), si.BStyleTop, si.BWidthTop, g, r.X, r.Y, right, r.Y); DrawLine(si.BColorRight.ToCairoColor(), si.BStyleRight, si.BWidthRight, g, right, r.Y, right, bottom); DrawLine(si.BColorLeft.ToCairoColor(), si.BStyleLeft, si.BWidthLeft, g, r.X, r.Y, r.X, bottom); DrawLine(si.BColorBottom.ToCairoColor(), si.BStyleBottom, si.BWidthBottom, g, r.X, bottom, right, bottom); //if (si.) { // g.DrawRoundedRectangle (r, 8, si.BColorTop.ToCairoColor (), 1); //} } #region IRender implementation public void RunPages(Pages pgs) { //TODO : Why Cairo is broken when CurrentThread.CurrentCulture is set to local ? //At Linux when CurrentCulture is set to local culture, Cairo rendering is serious broken CultureInfo oldci = Thread.CurrentThread.CurrentCulture; Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture; try { foreach (Page p in pgs) { ProcessPage(g, p); break; } } finally { Thread.CurrentThread.CurrentCulture = oldci; } } public void RunPage(Page pgs) { //TODO : Why Cairo is broken when CurrentThread.CurrentCulture is set to local ? //At Linux when CurrentCulture is set to local culture, Cairo rendering is serious broken CultureInfo oldci = Thread.CurrentThread.CurrentCulture; Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture; try { ProcessPage(g, pgs); } finally { Thread.CurrentThread.CurrentCulture = oldci; } } #endregion } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. /*============================================================ * // // * * * Purpose: Provides access to files using the same interface as FileStream * * ===========================================================*/ namespace System.IO.IsolatedStorage { using System; using System.IO; using Microsoft.Win32; using Microsoft.Win32.SafeHandles; using System.Security; using System.Security.Permissions; using System.Threading; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Diagnostics.Contracts; [System.Runtime.InteropServices.ComVisible(true)] public class IsolatedStorageFileStream : FileStream { private const int s_BlockSize = 1024; // Should be a power of 2! // see usage before // changing this constant #if !FEATURE_PAL private const String s_BackSlash = "\\"; #else // s_BackSlash is initialized in the contructor with Path.DirectorySeparatorChar private readonly String s_BackSlash; #endif // !FEATURE_PAL private FileStream m_fs; private IsolatedStorageFile m_isf; private String m_GivenPath; private String m_FullPath; private bool m_OwnedStore; private IsolatedStorageFileStream() {} #if !FEATURE_ISOSTORE_LIGHT public IsolatedStorageFileStream(String path, FileMode mode) : this(path, mode, (mode == FileMode.Append ? FileAccess.Write : FileAccess.ReadWrite), FileShare.None, null) { } #endif // !FEATURE_ISOSTORE_LIGHT public IsolatedStorageFileStream(String path, FileMode mode, IsolatedStorageFile isf) : this(path, mode, (mode == FileMode.Append ? FileAccess.Write : FileAccess.ReadWrite), FileShare.None, isf) { } #if !FEATURE_ISOSTORE_LIGHT public IsolatedStorageFileStream(String path, FileMode mode, FileAccess access) : this(path, mode, access, access == FileAccess.Read? FileShare.Read: FileShare.None, DefaultBufferSize, null) { } #endif // !FEATURE_ISOSTORE_LIGHT public IsolatedStorageFileStream(String path, FileMode mode, FileAccess access, IsolatedStorageFile isf) : this(path, mode, access, access == FileAccess.Read? FileShare.Read: FileShare.None, DefaultBufferSize, isf) { } #if !FEATURE_ISOSTORE_LIGHT public IsolatedStorageFileStream(String path, FileMode mode, FileAccess access, FileShare share) : this(path, mode, access, share, DefaultBufferSize, null) { } #endif // !FEATURE_ISOSTORE_LIGHT public IsolatedStorageFileStream(String path, FileMode mode, FileAccess access, FileShare share, IsolatedStorageFile isf) : this(path, mode, access, share, DefaultBufferSize, isf) { } #if !FEATURE_ISOSTORE_LIGHT public IsolatedStorageFileStream(String path, FileMode mode, FileAccess access, FileShare share, int bufferSize) : this(path, mode, access, share, bufferSize, null) { } #endif // !FEATURE_ISOSTORE_LIGHT // If the isolated storage file is null, then we default to using a file // that is scoped by user, appdomain, and assembly. [System.Security.SecuritySafeCritical] // auto-generated public IsolatedStorageFileStream(String path, FileMode mode, FileAccess access, FileShare share, int bufferSize, IsolatedStorageFile isf) { if (path == null) throw new ArgumentNullException("path"); Contract.EndContractBlock(); #if FEATURE_PAL if (s_BackSlash == null) s_BackSlash = new String(System.IO.Path.DirectorySeparatorChar,1); #endif // FEATURE_PAL if ((path.Length == 0) || path.Equals(s_BackSlash)) throw new ArgumentException( Environment.GetResourceString( "IsolatedStorage_Path")); if (isf == null) { #if FEATURE_ISOSTORE_LIGHT throw new ArgumentNullException("isf"); #else // !FEATURE_ISOSTORE_LIGHT m_OwnedStore = true; isf = IsolatedStorageFile.GetUserStoreForDomain(); #endif // !FEATURE_ISOSTORE_LIGHT } if (isf.Disposed) throw new ObjectDisposedException(null, Environment.GetResourceString("IsolatedStorage_StoreNotOpen")); switch (mode) { case FileMode.CreateNew: // Assume new file case FileMode.Create: // Check for New file & Unreserve case FileMode.OpenOrCreate: // Check for new file case FileMode.Truncate: // Unreserve old file size case FileMode.Append: // Check for new file case FileMode.Open: // Open existing, else exception break; default: throw new ArgumentException(Environment.GetResourceString("IsolatedStorage_FileOpenMode")); } m_isf = isf; #if !FEATURE_CORECLR FileIOPermission fiop = new FileIOPermission(FileIOPermissionAccess.AllAccess, m_isf.RootDirectory); fiop.Assert(); fiop.PermitOnly(); #endif m_GivenPath = path; m_FullPath = m_isf.GetFullPath(m_GivenPath); #if FEATURE_ISOLATED_STORAGE_QUOTA_ENFORCEMENT ulong oldFileSize=0, newFileSize; bool fNewFile = false, fLock=false; RuntimeHelpers.PrepareConstrainedRegions(); try { // for finally Unlocking locked store // Cache the old file size if the file size could change // Also find if we are going to create a new file. switch (mode) { case FileMode.CreateNew: // Assume new file #if FEATURE_ISOSTORE_LIGHT // We are going to call Reserve so we need to lock the store. m_isf.Lock(ref fLock); #endif fNewFile = true; break; case FileMode.Create: // Check for New file & Unreserve case FileMode.OpenOrCreate: // Check for new file case FileMode.Truncate: // Unreserve old file size case FileMode.Append: // Check for new file m_isf.Lock(ref fLock); // oldFileSize needs to be // protected try { #if FEATURE_ISOSTORE_LIGHT oldFileSize = IsolatedStorageFile.RoundToBlockSize((ulong)(FileInfo.UnsafeCreateFileInfo(m_FullPath).Length)); #else oldFileSize = IsolatedStorageFile.RoundToBlockSize((ulong)LongPathFile.GetLength(m_FullPath)); #endif } catch (FileNotFoundException) { fNewFile = true; } catch { } break; case FileMode.Open: // Open existing, else exception break; } if (fNewFile) m_isf.ReserveOneBlock(); #endif // FEATURE_ISOLATED_STORAGE_QUOTA_ENFORCEMENT try { #if FEATURE_CORECLR // Since FileStream's .ctor won't do a demand, we need to do our access check here. m_isf.Demand(m_FullPath); #endif #if FEATURE_ISOSTORE_LIGHT m_fs = new FileStream(m_FullPath, mode, access, share, bufferSize, FileOptions.None, m_GivenPath, true); } catch (Exception e) { #else m_fs = new FileStream(m_FullPath, mode, access, share, bufferSize, FileOptions.None, m_GivenPath, true, true); } catch { #endif #if FEATURE_ISOLATED_STORAGE_QUOTA_ENFORCEMENT if (fNewFile) m_isf.UnreserveOneBlock(); #endif // FEATURE_ISOLATED_STORAGE_QUOTA_ENFORCEMENT #if FEATURE_ISOSTORE_LIGHT // IsoStore generally does not let arbitrary exceptions flow out: a // IsolatedStorageException is thrown instead (see examples in IsolatedStorageFile.cs // Keeping this scoped to coreclr just because changing the exception type thrown is a // breaking change and that should not be introduced into the desktop without deliberation. // // Note that GetIsolatedStorageException may set InnerException. To the real exception // Today it always does this, for debug and chk builds, and for other builds asks the host // if it is okay to do so. throw IsolatedStorageFile.GetIsolatedStorageException("IsolatedStorage_Operation_ISFS", e); #else throw; #endif // FEATURE_ISOSTORE_LIGHT } #if FEATURE_ISOLATED_STORAGE_QUOTA_ENFORCEMENT // make adjustment to the Reserve / Unreserve state if ((fNewFile == false) && ((mode == FileMode.Truncate) || (mode == FileMode.Create))) { newFileSize = IsolatedStorageFile.RoundToBlockSize((ulong)m_fs.Length); if (oldFileSize > newFileSize) m_isf.Unreserve(oldFileSize - newFileSize); else if (newFileSize > oldFileSize) // Can this happen ? m_isf.Reserve(newFileSize - oldFileSize); } } finally { if (fLock) m_isf.Unlock(); } #endif // FEATURE_ISOLATED_STORAGE_QUOTA_ENFORCEMENT #if !FEATURE_CORECLR CodeAccessPermission.RevertAll(); #endif } public override bool CanRead { [Pure] get { return m_fs.CanRead; } } public override bool CanWrite { [Pure] get { return m_fs.CanWrite; } } public override bool CanSeek { [Pure] get { return m_fs.CanSeek; } } public override bool IsAsync { get { return m_fs.IsAsync; } } public override long Length { get { return m_fs.Length; } } public override long Position { get { return m_fs.Position; } set { if (value < 0) { throw new ArgumentOutOfRangeException("value", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum")); } Contract.EndContractBlock(); Seek(value, SeekOrigin.Begin); } } #if FEATURE_LEGACYNETCF public new string Name { [SecurityCritical] get { return m_FullPath; } } #endif #if false unsafe private static void AsyncFSCallback(uint errorCode, uint numBytes, NativeOverlapped* pOverlapped) { NotPermittedError(); } #endif protected override void Dispose(bool disposing) { try { if (disposing) { try { if (m_fs != null) m_fs.Close(); } finally { if (m_OwnedStore && m_isf != null) m_isf.Close(); } } } finally { base.Dispose(disposing); } } public override void Flush() { m_fs.Flush(); } public override void Flush(Boolean flushToDisk) { m_fs.Flush(flushToDisk); } [Obsolete("This property has been deprecated. Please use IsolatedStorageFileStream's SafeFileHandle property instead. http://go.microsoft.com/fwlink/?linkid=14202")] public override IntPtr Handle { [System.Security.SecurityCritical] // auto-generated_required #if !FEATURE_CORECLR [SecurityPermissionAttribute(SecurityAction.InheritanceDemand, Flags=SecurityPermissionFlag.UnmanagedCode)] #endif get { NotPermittedError(); return Win32Native.INVALID_HANDLE_VALUE; } } public override SafeFileHandle SafeFileHandle { [System.Security.SecurityCritical] // auto-generated_required #if !FEATURE_CORECLR [SecurityPermissionAttribute(SecurityAction.InheritanceDemand, Flags=SecurityPermissionFlag.UnmanagedCode)] #endif get { NotPermittedError(); return null; } } [System.Security.SecuritySafeCritical] // auto-generated public override void SetLength(long value) { if (value < 0) throw new ArgumentOutOfRangeException("value", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); Contract.EndContractBlock(); #if FEATURE_ISOLATED_STORAGE_QUOTA_ENFORCEMENT bool locked = false; RuntimeHelpers.PrepareConstrainedRegions(); try { m_isf.Lock(ref locked); // oldLen needs to be protected #endif // FEATURE_ISOLATED_STORAGE_QUOTA_ENFORCEMENT ulong oldLen = (ulong)m_fs.Length; ulong newLen = (ulong)value; #if FEATURE_ISOLATED_STORAGE_QUOTA_ENFORCEMENT // Reserve before the operation. m_isf.Reserve(oldLen, newLen); try { #endif // FEATURE_ISOLATED_STORAGE_QUOTA_ENFORCEMENT ZeroInit(oldLen, newLen); m_fs.SetLength(value); #if FEATURE_ISOLATED_STORAGE_QUOTA_ENFORCEMENT } catch { // Undo the reserve m_isf.UndoReserveOperation(oldLen, newLen); throw; } // Unreserve if this operation reduced the file size. if (oldLen > newLen) { // params oldlen, newlength reversed on purpose. m_isf.UndoReserveOperation(newLen, oldLen); } } finally { if (locked) m_isf.Unlock(); } #endif // FEATURE_ISOLATED_STORAGE_QUOTA_ENFORCEMENT } public override void Lock(long position, long length) { if (position < 0 || length < 0) throw new ArgumentOutOfRangeException((position < 0 ? "position" : "length"), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); Contract.EndContractBlock(); m_fs.Lock(position, length); } public override void Unlock(long position, long length) { if (position < 0 || length < 0) throw new ArgumentOutOfRangeException((position < 0 ? "position" : "length"), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); Contract.EndContractBlock(); m_fs.Unlock(position, length); } // 0 out the allocated disk so that // untrusted apps won't be able to read garbage, which // is a security hole, if allowed. // This may not be necessary in some file systems ? private void ZeroInit(ulong oldLen, ulong newLen) { if (oldLen >= newLen) return; ulong rem = newLen - oldLen; byte[] buffer = new byte[s_BlockSize]; // buffer is zero inited // here by the runtime // memory allocator. // back up the current position. long pos = m_fs.Position; m_fs.Seek((long)oldLen, SeekOrigin.Begin); // If we have a small number of bytes to write, do that and // we are done. if (rem <= (ulong)s_BlockSize) { m_fs.Write(buffer, 0, (int)rem); m_fs.Position = pos; return; } // Block write is better than writing a byte in a loop // or all bytes. The number of bytes to write could // be very large. // Align to block size // allign = s_BlockSize - (int)(oldLen % s_BlockSize); // Converting % to & operation since s_BlockSize is a power of 2 int allign = s_BlockSize - (int)(oldLen & ((ulong)s_BlockSize - 1)); /* this will never happen since we already handled this case leaving this code here for documentation if ((ulong)allign > rem) allign = (int)rem; */ m_fs.Write(buffer, 0, allign); rem -= (ulong)allign; int nBlocks = (int)(rem / s_BlockSize); // Write out one block at a time. for (int i=0; i<nBlocks; ++i) m_fs.Write(buffer, 0, s_BlockSize); // Write out the remaining bytes. // m_fs.Write(buffer, 0, (int) (rem % s_BlockSize)); // Converting % to & operation since s_BlockSize is a power of 2 m_fs.Write(buffer, 0, (int) (rem & ((ulong)s_BlockSize - 1))); // restore the current position m_fs.Position = pos; } public override int Read(byte[] buffer, int offset, int count) { return m_fs.Read(buffer, offset, count); } public override int ReadByte() { return m_fs.ReadByte(); } [System.Security.SecuritySafeCritical] // auto-generated public override long Seek(long offset, SeekOrigin origin) { long ret; #if FEATURE_ISOLATED_STORAGE_QUOTA_ENFORCEMENT bool locked = false; RuntimeHelpers.PrepareConstrainedRegions(); try { m_isf.Lock(ref locked); // oldLen needs to be protected #endif // FEATURE_ISOLATED_STORAGE_QUOTA_ENFORCEMENT // Seek operation could increase the file size, make sure // that the quota is updated, and file is zeroed out ulong oldLen; ulong newLen; oldLen = (ulong) m_fs.Length; // Note that offset can be negative too. switch (origin) { case SeekOrigin.Begin: newLen = (ulong)((offset < 0)?0:offset); break; case SeekOrigin.Current: newLen = (ulong) ((m_fs.Position + offset) < 0 ? 0 : (m_fs.Position + offset)); break; case SeekOrigin.End: newLen = (ulong)((m_fs.Length + offset) < 0 ? 0 : (m_fs.Length + offset)); break; default: throw new ArgumentException( Environment.GetResourceString( "IsolatedStorage_SeekOrigin")); } #if FEATURE_ISOLATED_STORAGE_QUOTA_ENFORCEMENT m_isf.Reserve(oldLen, newLen); try { #endif // FEATURE_ISOLATED_STORAGE_QUOTA_ENFORCEMENT ZeroInit(oldLen, newLen); ret = m_fs.Seek(offset, origin); #if FEATURE_ISOLATED_STORAGE_QUOTA_ENFORCEMENT } catch { m_isf.UndoReserveOperation(oldLen, newLen); throw; } } finally { if (locked) m_isf.Unlock(); } #endif // FEATURE_ISOLATED_STORAGE_QUOTA_ENFORCEMENT return ret; } [System.Security.SecuritySafeCritical] // auto-generated public override void Write(byte[] buffer, int offset, int count) { #if FEATURE_ISOLATED_STORAGE_QUOTA_ENFORCEMENT bool locked = false; RuntimeHelpers.PrepareConstrainedRegions(); try { m_isf.Lock(ref locked); // oldLen needs to be protected ulong oldLen = (ulong)m_fs.Length; ulong newLen = (ulong)(m_fs.Position + count); m_isf.Reserve(oldLen, newLen); try { #endif // FEATURE_ISOLATED_STORAGE_QUOTA_ENFORCEMENT m_fs.Write(buffer, offset, count); #if FEATURE_ISOLATED_STORAGE_QUOTA_ENFORCEMENT } catch { m_isf.UndoReserveOperation(oldLen, newLen); throw; } } finally { if (locked) m_isf.Unlock(); } #endif } [System.Security.SecuritySafeCritical] // auto-generated public override void WriteByte(byte value) { #if FEATURE_ISOLATED_STORAGE_QUOTA_ENFORCEMENT bool locked = false; RuntimeHelpers.PrepareConstrainedRegions(); try { m_isf.Lock(ref locked); // oldLen needs to be protected ulong oldLen = (ulong)m_fs.Length; ulong newLen = (ulong)m_fs.Position + 1; m_isf.Reserve(oldLen, newLen); try { #endif // FEATURE_ISOLATED_STORAGE_QUOTA_ENFORCEMENT m_fs.WriteByte(value); #if FEATURE_ISOLATED_STORAGE_QUOTA_ENFORCEMENT } catch { m_isf.UndoReserveOperation(oldLen, newLen); throw; } } finally { if (locked) m_isf.Unlock(); } #endif // FEATURE_ISOLATED_STORAGE_QUOTA_ENFORCEMENT } [HostProtection(ExternalThreading=true)] public override IAsyncResult BeginRead(byte[] buffer, int offset, int numBytes, AsyncCallback userCallback, Object stateObject) { return m_fs.BeginRead(buffer, offset, numBytes, userCallback, stateObject); } public override int EndRead(IAsyncResult asyncResult) { if (asyncResult == null) throw new ArgumentNullException("asyncResult"); Contract.EndContractBlock(); // try-catch to avoid leaking path info return m_fs.EndRead(asyncResult); } [System.Security.SecuritySafeCritical] // auto-generated [HostProtection(ExternalThreading=true)] public override IAsyncResult BeginWrite(byte[] buffer, int offset, int numBytes, AsyncCallback userCallback, Object stateObject) { #if FEATURE_ISOLATED_STORAGE_QUOTA_ENFORCEMENT bool locked = false; RuntimeHelpers.PrepareConstrainedRegions(); try { m_isf.Lock(ref locked); // oldLen needs to be protected ulong oldLen = (ulong)m_fs.Length; ulong newLen = (ulong)m_fs.Position + (ulong)numBytes; m_isf.Reserve(oldLen, newLen); try { #endif // FEATURE_ISOLATED_STORAGE_QUOTA_ENFORCEMENT return m_fs.BeginWrite(buffer, offset, numBytes, userCallback, stateObject); #if FEATURE_ISOLATED_STORAGE_QUOTA_ENFORCEMENT } catch { m_isf.UndoReserveOperation(oldLen, newLen); throw; } } finally { if(locked) m_isf.Unlock(); } #endif // FEATURE_ISOLATED_STORAGE_QUOTA_ENFORCEMENT } public override void EndWrite(IAsyncResult asyncResult) { if (asyncResult == null) throw new ArgumentNullException("asyncResult"); Contract.EndContractBlock(); m_fs.EndWrite(asyncResult); } internal void NotPermittedError(String str) { throw new IsolatedStorageException(str); } internal void NotPermittedError() { NotPermittedError(Environment.GetResourceString( "IsolatedStorage_Operation_ISFS")); } } }
using System; using System.Collections.Generic; using Microsoft.Extensions.Logging; using Orleans.Configuration; using System.Threading.Tasks; using System.Threading; using Microsoft.Extensions.Options; using System.Linq; using Orleans.Internal; namespace Orleans.Runtime.MembershipService { /// <summary> /// Responsible for updating membership table with details about the local silo. /// </summary> internal class MembershipAgent : IHealthCheckParticipant, ILifecycleParticipant<ISiloLifecycle>, IDisposable, MembershipAgent.ITestAccessor { private readonly CancellationTokenSource cancellation = new CancellationTokenSource(); private readonly MembershipTableManager tableManager; private readonly ClusterHealthMonitor clusterHealthMonitor; private readonly ILocalSiloDetails localSilo; private readonly IFatalErrorHandler fatalErrorHandler; private readonly ClusterMembershipOptions clusterMembershipOptions; private readonly ILogger<MembershipAgent> log; private readonly IAsyncTimer iAmAliveTimer; private Func<DateTime> getUtcDateTime = () => DateTime.UtcNow; public MembershipAgent( MembershipTableManager tableManager, ClusterHealthMonitor clusterHealthMonitor, ILocalSiloDetails localSilo, IFatalErrorHandler fatalErrorHandler, IOptions<ClusterMembershipOptions> options, ILogger<MembershipAgent> log, IAsyncTimerFactory timerFactory) { this.tableManager = tableManager; this.clusterHealthMonitor = clusterHealthMonitor; this.localSilo = localSilo; this.fatalErrorHandler = fatalErrorHandler; this.clusterMembershipOptions = options.Value; this.log = log; this.iAmAliveTimer = timerFactory.Create( this.clusterMembershipOptions.IAmAliveTablePublishTimeout, nameof(UpdateIAmAlive)); } internal interface ITestAccessor { Action OnUpdateIAmAlive { get; set; } Func<DateTime> GetDateTime { get; set; } } Action ITestAccessor.OnUpdateIAmAlive { get; set; } Func<DateTime> ITestAccessor.GetDateTime { get => this.getUtcDateTime; set => this.getUtcDateTime = value ?? throw new ArgumentNullException(nameof(value)); } private async Task UpdateIAmAlive() { if (this.log.IsEnabled(LogLevel.Debug)) this.log.LogDebug("Starting periodic membership liveness timestamp updates"); try { TimeSpan? onceOffDelay = default; while (await this.iAmAliveTimer.NextTick(onceOffDelay) && !this.tableManager.CurrentStatus.IsTerminating()) { onceOffDelay = default; try { var stopwatch = ValueStopwatch.StartNew(); ((ITestAccessor)this).OnUpdateIAmAlive?.Invoke(); await this.tableManager.UpdateIAmAlive(); if (this.log.IsEnabled(LogLevel.Trace)) this.log.LogTrace("Updating IAmAlive took {Elapsed}", stopwatch.Elapsed); } catch (Exception exception) { this.log.LogError( (int)ErrorCode.MembershipUpdateIAmAliveFailure, "Failed to update table entry for this silo, will retry shortly: {Exception}", exception); // Retry quickly onceOffDelay = TimeSpan.FromMilliseconds(200); } } } catch (Exception exception) when (this.fatalErrorHandler.IsUnexpected(exception)) { this.log.LogError("Error updating liveness timestamp: {Exception}", exception); this.fatalErrorHandler.OnFatalException(this, nameof(UpdateIAmAlive), exception); } finally { if (this.log.IsEnabled(LogLevel.Debug)) this.log.LogDebug("Stopping periodic membership liveness timestamp updates"); } } private async Task BecomeActive() { this.log.LogInformation( (int)ErrorCode.MembershipBecomeActive, "-BecomeActive"); if (this.clusterMembershipOptions.ValidateInitialConnectivity) { await this.ValidateInitialConnectivity(); } else { this.log.LogWarning( (int)ErrorCode.MembershipSendingPreJoinPing, $"{nameof(ClusterMembershipOptions)}.{nameof(ClusterMembershipOptions.ValidateInitialConnectivity)} is set to false. This is NOT recommended for a production environment."); } try { await this.UpdateStatus(SiloStatus.Active); this.log.LogInformation( (int)ErrorCode.MembershipFinishBecomeActive, "-Finished BecomeActive."); } catch (Exception exception) { this.log.LogInformation( (int)ErrorCode.MembershipFailedToBecomeActive, "BecomeActive failed: {Exception}", exception); throw; } } private async Task ValidateInitialConnectivity() { // Continue attempting to validate connectivity until some reasonable timeout. var maxAttemptTime = this.clusterMembershipOptions.ProbeTimeout.Multiply(5 * this.clusterMembershipOptions.NumMissedProbesLimit); var attemptNumber = 1; var now = this.getUtcDateTime(); var attemptUntil = now + maxAttemptTime; var canContinue = true; while (true) { try { var activeSilos = new List<SiloAddress>(); foreach (var item in this.tableManager.MembershipTableSnapshot.Entries) { var entry = item.Value; if (entry.Status != SiloStatus.Active) continue; if (entry.SiloAddress.IsSameLogicalSilo(this.localSilo.SiloAddress)) continue; if (entry.HasMissedIAmAlivesSince(this.clusterMembershipOptions, now) != default) continue; activeSilos.Add(entry.SiloAddress); } var failedSilos = await this.clusterHealthMonitor.CheckClusterConnectivity(activeSilos.ToArray()); var successfulSilos = activeSilos.Where(s => !failedSilos.Contains(s)).ToList(); // If there were no failures, terminate the loop and return without error. if (failedSilos.Count == 0) break; this.log.LogError( (int)ErrorCode.MembershipJoiningPreconditionFailure, "Failed to get ping responses from {FailedCount} of {ActiveCount} active silos. " + "Newly joining silos validate connectivity with all active silos that have recently updated their 'I Am Alive' value before joining the cluster. " + "Successfully contacted: {SuccessfulSilos}. Silos which did not respond successfully are: {FailedSilos}. " + "Will continue attempting to validate connectivity until {Timeout}. Attempt #{Attempt}", failedSilos.Count, activeSilos.Count, Utils.EnumerableToString(successfulSilos), Utils.EnumerableToString(failedSilos), attemptUntil, attemptNumber); if (now + TimeSpan.FromSeconds(5) > attemptUntil) { canContinue = false; var msg = $"Failed to get ping responses from {failedSilos.Count} of {activeSilos.Count} active silos. " + "Newly joining silos validate connectivity with all active silos that have recently updated their 'I Am Alive' value before joining the cluster. " + $"Successfully contacted: {Utils.EnumerableToString(successfulSilos)}. Failed to get response from: {Utils.EnumerableToString(failedSilos)}"; throw new OrleansClusterConnectivityCheckFailedException(msg); } // Refresh membership after some delay and retry. await Task.Delay(TimeSpan.FromSeconds(5)); await this.tableManager.Refresh(); } catch (Exception exception) when (canContinue) { this.log.LogError("Failed to validate initial cluster connectivity: {Exception}", exception); await Task.Delay(TimeSpan.FromSeconds(1)); } ++attemptNumber; now = this.getUtcDateTime(); } } private async Task BecomeJoining() { this.log.Info(ErrorCode.MembershipJoining, "-Joining"); try { await this.UpdateStatus(SiloStatus.Joining); } catch (Exception exc) { this.log.Error(ErrorCode.MembershipFailedToJoin, "Error updating status to Joining", exc); throw; } } private async Task BecomeShuttingDown() { this.log.Info(ErrorCode.MembershipShutDown, "-Shutdown"); try { await this.UpdateStatus(SiloStatus.ShuttingDown); } catch (Exception exc) { this.log.Error(ErrorCode.MembershipFailedToShutdown, "Error updating status to ShuttingDown", exc); throw; } } private async Task BecomeStopping() { log.Info(ErrorCode.MembershipStop, "-Stop"); try { await this.UpdateStatus(SiloStatus.Stopping); } catch (Exception exc) { log.Error(ErrorCode.MembershipFailedToStop, "Error updating status to Stopping", exc); throw; } } private async Task BecomeDead() { this.log.LogInformation( (int)ErrorCode.MembershipKillMyself, "Updating status to Dead"); try { await this.UpdateStatus(SiloStatus.Dead); } catch (Exception exception) { this.log.LogError( (int)ErrorCode.MembershipFailedToKillMyself, "Failure updating status to " + nameof(SiloStatus.Dead) + ": {Exception}", exception); throw; } } private async Task UpdateStatus(SiloStatus status) { await this.tableManager.UpdateStatus(status); } void ILifecycleParticipant<ISiloLifecycle>.Participate(ISiloLifecycle lifecycle) { { Task OnRuntimeInitializeStart(CancellationToken ct) { return Task.CompletedTask; } async Task OnRuntimeInitializeStop(CancellationToken ct) { this.iAmAliveTimer.Dispose(); this.cancellation.Cancel(); await Task.WhenAny( Task.Run(() => this.BecomeDead()), Task.Delay(TimeSpan.FromMinutes(1))); } lifecycle.Subscribe( nameof(MembershipAgent), ServiceLifecycleStage.RuntimeInitialize, OnRuntimeInitializeStart, OnRuntimeInitializeStop); } { async Task AfterRuntimeGrainServicesStart(CancellationToken ct) { await Task.Run(() => this.BecomeJoining()); } Task AfterRuntimeGrainServicesStop(CancellationToken ct) => Task.CompletedTask; lifecycle.Subscribe( nameof(MembershipAgent), ServiceLifecycleStage.AfterRuntimeGrainServices, AfterRuntimeGrainServicesStart, AfterRuntimeGrainServicesStop); } { var tasks = new List<Task>(); async Task OnBecomeActiveStart(CancellationToken ct) { await Task.Run(() => this.BecomeActive()); tasks.Add(Task.Run(() => this.UpdateIAmAlive())); } async Task OnBecomeActiveStop(CancellationToken ct) { this.iAmAliveTimer.Dispose(); this.cancellation.Cancel(throwOnFirstException: false); var cancellationTask = ct.WhenCancelled(); if (ct.IsCancellationRequested) { await Task.Run(() => this.BecomeStopping()); } else { var task = await Task.WhenAny(cancellationTask, this.BecomeShuttingDown()); if (ReferenceEquals(task, cancellationTask)) { this.log.LogWarning("Graceful shutdown aborted: starting ungraceful shutdown"); await Task.Run(() => this.BecomeStopping()); } else { await Task.WhenAny(cancellationTask, Task.WhenAll(tasks)); } } } lifecycle.Subscribe( nameof(MembershipAgent), ServiceLifecycleStage.BecomeActive, OnBecomeActiveStart, OnBecomeActiveStop); } } public void Dispose() { this.iAmAliveTimer.Dispose(); } bool IHealthCheckable.CheckHealth(DateTime lastCheckTime) { var ok = this.iAmAliveTimer.CheckHealth(lastCheckTime); return ok; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Linq; using System.Threading; using Microsoft.VisualStudio.TestPlatform.UnitTestFramework; using Microsoft.Practices.Prism.PubSubEvents; namespace Microsoft.Patterns.Prism.PubSubEvents.Tests { [TestClass] public class PubSubEventFixture { [TestMethod] public void CanSubscribeAndRaiseEvent() { TestablePubSubEvent<string> pubSubEvent = new TestablePubSubEvent<string>(); bool published = false; pubSubEvent.Subscribe(delegate { published = true; }, ThreadOption.PublisherThread, true, delegate { return true; }); pubSubEvent.Publish(null); Assert.IsTrue(published); } [TestMethod] public void CanSubscribeAndRaiseCustomEvent() { var customEvent = new TestablePubSubEvent<Payload>(); Payload payload = new Payload(); var action = new ActionHelper(); customEvent.Subscribe(action.Action); customEvent.Publish(payload); Assert.AreSame(action.ActionArg<Payload>(), payload); } [TestMethod] public void CanHaveMultipleSubscribersAndRaiseCustomEvent() { var customEvent = new TestablePubSubEvent<Payload>(); Payload payload = new Payload(); var action1 = new ActionHelper(); var action2 = new ActionHelper(); customEvent.Subscribe(action1.Action); customEvent.Subscribe(action2.Action); customEvent.Publish(payload); Assert.AreSame(action1.ActionArg<Payload>(), payload); Assert.AreSame(action2.ActionArg<Payload>(), payload); } [TestMethod] public void SubscribeTakesExecuteDelegateThreadOptionAndFilter() { TestablePubSubEvent<string> pubSubEvent = new TestablePubSubEvent<string>(); var action = new ActionHelper(); pubSubEvent.Subscribe(action.Action); pubSubEvent.Publish("test"); Assert.AreEqual("test", action.ActionArg<string>()); } [TestMethod] public void FilterEnablesActionTarget() { TestablePubSubEvent<string> pubSubEvent = new TestablePubSubEvent<string>(); var goodFilter = new MockFilter { FilterReturnValue = true }; var actionGoodFilter = new ActionHelper(); var badFilter = new MockFilter { FilterReturnValue = false }; var actionBadFilter = new ActionHelper(); pubSubEvent.Subscribe(actionGoodFilter.Action, ThreadOption.PublisherThread, true, goodFilter.FilterString); pubSubEvent.Subscribe(actionBadFilter.Action, ThreadOption.PublisherThread, true, badFilter.FilterString); pubSubEvent.Publish("test"); Assert.IsTrue(actionGoodFilter.ActionCalled); Assert.IsFalse(actionBadFilter.ActionCalled); } [TestMethod] public void SubscribeDefaultsThreadOptionAndNoFilter() { TestablePubSubEvent<string> pubSubEvent = new TestablePubSubEvent<string>(); SynchronizationContext.SetSynchronizationContext(new SynchronizationContext()); SynchronizationContext calledSyncContext = null; var myAction = new ActionHelper() { ActionToExecute = () => calledSyncContext = SynchronizationContext.Current }; pubSubEvent.Subscribe(myAction.Action); pubSubEvent.Publish("test"); Assert.AreEqual(SynchronizationContext.Current, calledSyncContext); } [TestMethod] public void ShouldUnsubscribeFromPublisherThread() { var PubSubEvent = new TestablePubSubEvent<string>(); var actionEvent = new ActionHelper(); PubSubEvent.Subscribe( actionEvent.Action, ThreadOption.PublisherThread); Assert.IsTrue(PubSubEvent.Contains(actionEvent.Action)); PubSubEvent.Unsubscribe(actionEvent.Action); Assert.IsFalse(PubSubEvent.Contains(actionEvent.Action)); } [TestMethod] public void UnsubscribeShouldNotFailWithNonSubscriber() { TestablePubSubEvent<string> pubSubEvent = new TestablePubSubEvent<string>(); Action<string> subscriber = delegate { }; pubSubEvent.Unsubscribe(subscriber); } [TestMethod] public void ShouldUnsubscribeFromBackgroundThread() { var PubSubEvent = new TestablePubSubEvent<string>(); var actionEvent = new ActionHelper(); PubSubEvent.Subscribe( actionEvent.Action, ThreadOption.BackgroundThread); Assert.IsTrue(PubSubEvent.Contains(actionEvent.Action)); PubSubEvent.Unsubscribe(actionEvent.Action); Assert.IsFalse(PubSubEvent.Contains(actionEvent.Action)); } [TestMethod] public void ShouldUnsubscribeFromUIThread() { var PubSubEvent = new TestablePubSubEvent<string>(); PubSubEvent.SynchronizationContext = new SynchronizationContext(); var actionEvent = new ActionHelper(); PubSubEvent.Subscribe( actionEvent.Action, ThreadOption.UIThread); Assert.IsTrue(PubSubEvent.Contains(actionEvent.Action)); PubSubEvent.Unsubscribe(actionEvent.Action); Assert.IsFalse(PubSubEvent.Contains(actionEvent.Action)); } [TestMethod] public void ShouldUnsubscribeASingleDelegate() { var PubSubEvent = new TestablePubSubEvent<string>(); int callCount = 0; var actionEvent = new ActionHelper() { ActionToExecute = () => callCount++ }; PubSubEvent.Subscribe(actionEvent.Action); PubSubEvent.Subscribe(actionEvent.Action); PubSubEvent.Publish(null); Assert.AreEqual<int>(2, callCount); callCount = 0; PubSubEvent.Unsubscribe(actionEvent.Action); PubSubEvent.Publish(null); Assert.AreEqual<int>(1, callCount); } [TestMethod] public void ShouldNotExecuteOnGarbageCollectedDelegateReferenceWhenNotKeepAlive() { var PubSubEvent = new TestablePubSubEvent<string>(); ExternalAction externalAction = new ExternalAction(); PubSubEvent.Subscribe(externalAction.ExecuteAction); PubSubEvent.Publish("testPayload"); Assert.AreEqual("testPayload", externalAction.PassedValue); WeakReference actionEventReference = new WeakReference(externalAction); externalAction = null; GC.Collect(); Assert.IsFalse(actionEventReference.IsAlive); PubSubEvent.Publish("testPayload"); } [TestMethod] public void ShouldNotExecuteOnGarbageCollectedFilterReferenceWhenNotKeepAlive() { var PubSubEvent = new TestablePubSubEvent<string>(); bool wasCalled = false; var actionEvent = new ActionHelper() { ActionToExecute = () => wasCalled = true }; ExternalFilter filter = new ExternalFilter(); PubSubEvent.Subscribe(actionEvent.Action, ThreadOption.PublisherThread, false, filter.AlwaysTrueFilter); PubSubEvent.Publish("testPayload"); Assert.IsTrue(wasCalled); wasCalled = false; WeakReference filterReference = new WeakReference(filter); filter = null; GC.Collect(); Assert.IsFalse(filterReference.IsAlive); PubSubEvent.Publish("testPayload"); Assert.IsFalse(wasCalled); } [TestMethod] public void CanAddSubscriptionWhileEventIsFiring() { var PubSubEvent = new TestablePubSubEvent<string>(); var emptyAction = new ActionHelper(); var subscriptionAction = new ActionHelper { ActionToExecute = (() => PubSubEvent.Subscribe( emptyAction.Action)) }; PubSubEvent.Subscribe(subscriptionAction.Action); Assert.IsFalse(PubSubEvent.Contains(emptyAction.Action)); PubSubEvent.Publish(null); Assert.IsTrue((PubSubEvent.Contains(emptyAction.Action))); } [TestMethod] public void InlineDelegateDeclarationsDoesNotGetCollectedIncorrectlyWithWeakReferences() { var PubSubEvent = new TestablePubSubEvent<string>(); bool published = false; PubSubEvent.Subscribe(delegate { published = true; }, ThreadOption.PublisherThread, false, delegate { return true; }); GC.Collect(); PubSubEvent.Publish(null); Assert.IsTrue(published); } [TestMethod] public void ShouldNotGarbageCollectDelegateReferenceWhenUsingKeepAlive() { var PubSubEvent = new TestablePubSubEvent<string>(); var externalAction = new ExternalAction(); PubSubEvent.Subscribe(externalAction.ExecuteAction, ThreadOption.PublisherThread, true); WeakReference actionEventReference = new WeakReference(externalAction); externalAction = null; GC.Collect(); GC.Collect(); Assert.IsTrue(actionEventReference.IsAlive); PubSubEvent.Publish("testPayload"); Assert.AreEqual("testPayload", ((ExternalAction)actionEventReference.Target).PassedValue); } [TestMethod] public void RegisterReturnsTokenThatCanBeUsedToUnsubscribe() { var PubSubEvent = new TestablePubSubEvent<string>(); var emptyAction = new ActionHelper(); var token = PubSubEvent.Subscribe(emptyAction.Action); PubSubEvent.Unsubscribe(token); Assert.IsFalse(PubSubEvent.Contains(emptyAction.Action)); } [TestMethod] public void ContainsShouldSearchByToken() { var PubSubEvent = new TestablePubSubEvent<string>(); var emptyAction = new ActionHelper(); var token = PubSubEvent.Subscribe(emptyAction.Action); Assert.IsTrue(PubSubEvent.Contains(token)); PubSubEvent.Unsubscribe(emptyAction.Action); Assert.IsFalse(PubSubEvent.Contains(token)); } [TestMethod] public void SubscribeDefaultsToPublisherThread() { var PubSubEvent = new TestablePubSubEvent<string>(); Action<string> action = delegate { }; var token = PubSubEvent.Subscribe(action, true); Assert.AreEqual(1, PubSubEvent.BaseSubscriptions.Count); Assert.AreEqual(typeof(EventSubscription<string>), PubSubEvent.BaseSubscriptions.ElementAt(0).GetType()); } public class ExternalFilter { public bool AlwaysTrueFilter(string value) { return true; } } public class ExternalAction { public string PassedValue; public void ExecuteAction(string value) { PassedValue = value; } } class TestablePubSubEvent<TPayload> : PubSubEvent<TPayload> { public ICollection<IEventSubscription> BaseSubscriptions { get { return base.Subscriptions; } } } public class Payload { } } public class ActionHelper { public bool ActionCalled; public Action ActionToExecute = null; private object actionArg; public T ActionArg<T>() { return (T)actionArg; } public void Action(PubSubEventFixture.Payload arg) { Action((object)arg); } public void Action(string arg) { Action((object)arg); } public void Action(object arg) { actionArg = arg; ActionCalled = true; if (ActionToExecute != null) { ActionToExecute.Invoke(); } } } public class MockFilter { public bool FilterReturnValue; public bool FilterString(string arg) { return FilterReturnValue; } } }
// <copyright file="PersistedQueueBase{T}.cs" company="Adrian Mos"> // Copyright (c) Adrian Mos with all rights reserved. Part of the IX Framework. // </copyright> using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.Serialization; using System.Threading; using System.Threading.Tasks; using IX.StandardExtensions; using IX.StandardExtensions.Contracts; using IX.StandardExtensions.Threading; using IX.System.Collections.Generic; using IX.System.IO; using JetBrains.Annotations; namespace IX.Guaranteed.Collections { /// <summary> /// A base class for persisted queues. /// </summary> /// <typeparam name="T">The type of object in the queue.</typeparam> /// <seealso cref="StandardExtensions.ComponentModel.DisposableBase" /> /// <seealso cref="System.Collections.Generic.IQueue{T}" /> [PublicAPI] public abstract class PersistedQueueBase<T> : ReaderWriterSynchronizedBase, IQueue<T> { private readonly IDirectory directoryShim; private readonly IFile fileShim; private readonly IPath pathShim; /// <summary> /// The poisoned non-removable files list. /// </summary> private readonly List<string> poisonedUnremovableFiles; private readonly DataContractSerializer serializer; /// <summary> /// Initializes a new instance of the <see cref="PersistedQueueBase{T}" /> class. /// </summary> /// <param name="persistenceFolderPath"> /// The persistence folder path. /// </param> /// <param name="fileShim"> /// The file shim. /// </param> /// <param name="directoryShim"> /// The directory shim. /// </param> /// <param name="pathShim"> /// The path shim. /// </param> /// <param name="serializer"> /// The serializer. /// </param> /// <param name="timeout"> /// The timeout. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="persistenceFolderPath" /> /// or /// <paramref name="fileShim" /> /// or /// <paramref name="directoryShim" /> /// or /// <paramref name="pathShim" /> /// or /// <paramref name="serializer" /> /// is <see langword="null" /> (<see langword="Nothing" /> in Visual Basic). /// </exception> /// <exception cref="ArgumentInvalidPathException"> /// The folder at <paramref name="persistenceFolderPath" /> does not exist, or is not accessible. /// </exception> protected PersistedQueueBase( [NotNull] string persistenceFolderPath, [NotNull] IFile fileShim, [NotNull] IDirectory directoryShim, [NotNull] IPath pathShim, [NotNull] DataContractSerializer serializer, TimeSpan timeout) : base(timeout) { // Dependency validation Contract.RequiresNotNull( ref this.fileShim, fileShim, nameof(fileShim)); Contract.RequiresNotNull( ref this.pathShim, pathShim, nameof(pathShim)); Contract.RequiresNotNull( ref this.directoryShim, directoryShim, nameof(directoryShim)); Contract.RequiresNotNull( ref this.serializer, serializer, nameof(serializer)); // Parameter validation Contract.RequiresNotNullOrWhitespace( persistenceFolderPath, nameof(persistenceFolderPath)); if (!directoryShim.Exists(persistenceFolderPath)) { throw new ArgumentInvalidPathException(nameof(persistenceFolderPath)); } // Internal state this.poisonedUnremovableFiles = new List<string>(); // Persistence folder paths var dataFolderPath = pathShim.Combine( persistenceFolderPath, "Data"); this.DataFolderPath = dataFolderPath; var poisonFolderPath = pathShim.Combine( persistenceFolderPath, "Poison"); this.PoisonFolderPath = poisonFolderPath; // Initialize folder paths if (!directoryShim.Exists(dataFolderPath)) { directoryShim.CreateDirectory(dataFolderPath); } if (!directoryShim.Exists(poisonFolderPath)) { directoryShim.CreateDirectory(poisonFolderPath); } } /// <summary> /// Gets the number of elements contained in the <see cref="PersistedQueueBase{T}" />. /// </summary> /// <value>The count.</value> public abstract int Count { get; } /// <summary> /// Gets an object that can be used to synchronize access to the <see cref="PersistedQueueBase{T}" />. /// </summary> /// <value>The synchronize root.</value> object ICollection.SyncRoot { get; } = new object(); /// <summary> /// Gets a value indicating whether access to the <see cref="PersistedQueueBase{T}" /> is synchronized (thread safe). /// </summary> /// <value>The is synchronized.</value> bool ICollection.IsSynchronized => true; /// <summary> /// Gets the data folder path. /// </summary> /// <value>The data folder path.</value> protected string DataFolderPath { get; } /// <summary> /// Gets the folder shim. /// </summary> /// <value>The folder shim.</value> protected IDirectory DirectoryShim => this.directoryShim; /// <summary> /// Gets the file shim. /// </summary> /// <value>The file shim.</value> protected IFile FileShim => this.fileShim; /// <summary> /// Gets the path shim. /// </summary> /// <value>The path shim.</value> protected IPath PathShim => this.pathShim; /// <summary> /// Gets the poison folder path. /// </summary> /// <value>The poison folder path.</value> protected string PoisonFolderPath { get; } /// <summary> /// Gets the serializer. /// </summary> /// <value>The serializer.</value> protected DataContractSerializer Serializer => this.serializer; /// <summary> /// Clears the queue of all elements. /// </summary> public abstract void Clear(); /// <summary> /// Verifies whether or not an item is contained in the queue. /// </summary> /// <param name="item">The item to verify.</param> /// <returns><see langword="true" /> if the item is queued, <see langword="false" /> otherwise.</returns> public abstract bool Contains(T item); /// <summary> /// Copies the elements of the <see cref="PersistedQueueBase{T}" /> to an <see cref="T:System.Array" />, starting at a /// particular <see cref="T:System.Array" /> index. /// </summary> /// <param name="array"> /// The one-dimensional <see cref="T:System.Array" /> that is the destination of the elements copied /// from <see cref="PersistedQueueBase{T}" />. The <see cref="T:System.Array" /> must have zero-based indexing. /// </param> /// <param name="index">The zero-based index in <paramref name="array" /> at which copying begins.</param> public abstract void CopyTo( Array array, int index); /// <summary> /// De-queues an item and removes it from the queue. /// </summary> /// <returns>The item that has been de-queued.</returns> public abstract T Dequeue(); /// <summary> /// Attempts to de-queue an item and to remove it from queue. /// </summary> /// <param name="item">The item that has been de-queued, default if unsuccessful.</param> /// <returns> /// <see langword="true" /> if an item is de-queued successfully, <see langword="false" /> otherwise, or if the /// queue is empty. /// </returns> public abstract bool TryDequeue(out T item); /// <summary> /// Queues an item, adding it to the queue. /// </summary> /// <param name="item">The item to enqueue.</param> public abstract void Enqueue(T item); /// <summary> /// Returns an enumerator that iterates through the queue. /// </summary> /// <returns>An enumerator that can be used to iterate through the queue.</returns> public abstract IEnumerator<T> GetEnumerator(); /// <summary> /// Peeks at the topmost element in the queue, without removing it. /// </summary> /// <returns>The item peeked at, if any.</returns> public abstract T Peek(); /// <summary> /// Copies all elements of the queue into a new array. /// </summary> /// <returns>The created array with all element of the queue.</returns> public abstract T[] ToArray(); /// <summary> /// Trims the excess free space from within the queue, reducing the capacity to the actual number of elements. /// </summary> public virtual void TrimExcess() { } #pragma warning disable HAA0401 // Possible allocation of reference type enumerator - Yeah, we know /// <summary> /// Returns an enumerator that iterates through the queue. /// </summary> /// <returns>An <see cref="T:System.Collections.IEnumerator" /> object that can be used to iterate through the queue.</returns> IEnumerator IEnumerable.GetEnumerator() => this.GetEnumerator(); #pragma warning restore HAA0401 // Possible allocation of reference type enumerator /// <summary> /// Loads the topmost item from the folder, ensuring its deletion afterwards. /// </summary> /// <returns>An item, if one exists and can be loaded, a default value otherwise.</returns> /// <exception cref="InvalidOperationException">There are no more valid items in the folder.</exception> protected T LoadTopmostItem() { this.RequiresNotDisposed(); using (this.WriteLock()) { string[] files = this.GetPossibleDataFiles(); var i = 0; string possibleFilePath; T obj; while (true) { if (i >= files.Length) { throw new InvalidOperationException(); } possibleFilePath = files[i]; try { using (Stream stream = this.FileShim.OpenRead(possibleFilePath)) { obj = (T)this.Serializer.ReadObject(stream); } break; } catch (IOException) { this.HandleFileLoadProblem(possibleFilePath); i++; } catch (UnauthorizedAccessException) { this.HandleFileLoadProblem(possibleFilePath); i++; } catch (SerializationException) { this.HandleFileLoadProblem(possibleFilePath); i++; } } try { this.FileShim.Delete(possibleFilePath); } catch (IOException) { this.HandleFileLoadProblem(possibleFilePath); } catch (UnauthorizedAccessException) { this.HandleFileLoadProblem(possibleFilePath); } catch (SerializationException) { this.HandleFileLoadProblem(possibleFilePath); } return obj; } } /// <summary> /// Tries the load topmost item and execute an action on it, deleting the topmost object data if the operation is /// successful. /// </summary> /// <typeparam name="TState">The type of the state object to send to the action.</typeparam> /// <param name="actionToInvoke">The action to invoke.</param> /// <param name="state">The state object to pass to the invoked action.</param> /// <returns><see langword="true" /> if de-queuing and executing is successful, <see langword="false" /> otherwise.</returns> protected bool TryLoadTopmostItemWithAction<TState>( [NotNull] Action<TState, T> actionToInvoke, TState state) { Contract.RequiresNotNull( in actionToInvoke, nameof(actionToInvoke)); this.RequiresNotDisposed(); using (ReadWriteSynchronizationLocker locker = this.ReadWriteLock()) { string[] files = this.GetPossibleDataFiles(); var i = 0; T obj; string possibleFilePath; while (true) { if (i >= files.Length) { return false; } possibleFilePath = files[i]; try { using (Stream stream = this.FileShim.OpenRead(possibleFilePath)) { obj = (T)this.Serializer.ReadObject(stream); } break; } catch (IOException) { this.HandleFileLoadProblem(possibleFilePath); i++; } catch (UnauthorizedAccessException) { this.HandleFileLoadProblem(possibleFilePath); i++; } catch (SerializationException) { this.HandleFileLoadProblem(possibleFilePath); i++; } } try { actionToInvoke( state, obj); } catch (Exception) { #pragma warning disable ERP022 // Catching everything considered harmful. - We will mitigate shortly return false; #pragma warning restore ERP022 // Catching everything considered harmful. } locker.Upgrade(); try { this.FileShim.Delete(possibleFilePath); } catch (IOException) { this.HandleFileLoadProblem(possibleFilePath); } catch (UnauthorizedAccessException) { this.HandleFileLoadProblem(possibleFilePath); } catch (SerializationException) { this.HandleFileLoadProblem(possibleFilePath); } return true; } } /// <summary> /// Asynchronously tries the load topmost item and execute an action on it, deleting the topmost object data if the /// operation is successful. /// </summary> /// <typeparam name="TState">The type of the state object to send to the action.</typeparam> /// <param name="actionToInvoke">The action to invoke.</param> /// <param name="state">The state object to pass to the invoked action.</param> /// <param name="cancellationToken">The cancellation token for this operation.</param> /// <returns><see langword="true" /> if de-queuing and executing is successful, <see langword="false" /> otherwise.</returns> protected async Task<bool> TryLoadTopmostItemWithActionAsync<TState>( [NotNull] Func<TState, T, Task> actionToInvoke, TState state, CancellationToken cancellationToken = default) { Contract.RequiresNotNull( in actionToInvoke, nameof(actionToInvoke)); this.RequiresNotDisposed(); using (ReadWriteSynchronizationLocker locker = this.ReadWriteLock()) { string[] files = this.GetPossibleDataFiles(); var i = 0; T obj; string possibleFilePath; while (true) { cancellationToken.ThrowIfCancellationRequested(); if (i >= files.Length) { return false; } possibleFilePath = files[i]; try { using (Stream stream = this.FileShim.OpenRead(possibleFilePath)) { obj = (T)this.Serializer.ReadObject(stream); } break; } catch (IOException) { this.HandleFileLoadProblem(possibleFilePath); i++; } catch (UnauthorizedAccessException) { this.HandleFileLoadProblem(possibleFilePath); i++; } catch (SerializationException) { this.HandleFileLoadProblem(possibleFilePath); i++; } } try { await actionToInvoke( state, obj).ConfigureAwait(false); } catch (Exception) { #pragma warning disable ERP022 // Catching everything considered harmful. - We will mitigate shortly return false; #pragma warning restore ERP022 // Catching everything considered harmful. } locker.Upgrade(); try { this.FileShim.Delete(possibleFilePath); } catch (IOException) { this.HandleFileLoadProblem(possibleFilePath); } catch (UnauthorizedAccessException) { this.HandleFileLoadProblem(possibleFilePath); } catch (SerializationException) { this.HandleFileLoadProblem(possibleFilePath); } return true; } } /// <summary> /// Tries to load the topmost item and execute an action on it, deleting the topmost object data if the operation is /// successful. /// </summary> /// <typeparam name="TState">The type of the state object to send to the action.</typeparam> /// <param name="predicate">The predicate.</param> /// <param name="actionToInvoke">The action to invoke.</param> /// <param name="state">The state object to pass to the invoked action.</param> /// <returns>The number of items that have been de-queued.</returns> /// <remarks> /// <para> /// Warning! This method has the potential of overrunning its read/write lock timeouts. Please ensure that the /// <paramref name="predicate" /> method /// filters out items in a way that limits the amount of data passing through. /// </para> /// </remarks> protected int TryLoadWhilePredicateWithAction<TState>( [NotNull] Func<TState, T, bool> predicate, [NotNull] Action<TState, IEnumerable<T>> actionToInvoke, [CanBeNull] TState state) { Contract.RequiresNotNull( in predicate, nameof(predicate)); Contract.RequiresNotNull( in actionToInvoke, nameof(actionToInvoke)); this.RequiresNotDisposed(); using (ReadWriteSynchronizationLocker locker = this.ReadWriteLock()) { string[] files = this.GetPossibleDataFiles(); var i = 0; var accumulatedObjects = new List<T>(); var accumulatedPaths = new List<string>(); while (i < files.Length) { var possibleFilePath = files[i]; try { T obj; using (Stream stream = this.FileShim.OpenRead(possibleFilePath)) { obj = (T)this.Serializer.ReadObject(stream); } if (!predicate( state, obj)) { break; } accumulatedObjects.Add(obj); accumulatedPaths.Add(possibleFilePath); i++; } catch (IOException) { this.HandleFileLoadProblem(possibleFilePath); i++; } catch (UnauthorizedAccessException) { this.HandleFileLoadProblem(possibleFilePath); i++; } catch (SerializationException) { this.HandleFileLoadProblem(possibleFilePath); i++; } } if (accumulatedObjects.Count <= 0) { return accumulatedPaths.Count; } try { actionToInvoke( state, accumulatedObjects); } catch (Exception) { #pragma warning disable ERP022 // Catching everything considered harmful. - We will mitigate shortly return 0; #pragma warning restore ERP022 // Catching everything considered harmful. } locker.Upgrade(); foreach (var possibleFilePath in accumulatedPaths) { try { this.FileShim.Delete(possibleFilePath); } catch (IOException) { this.HandleFileLoadProblem(possibleFilePath); } catch (UnauthorizedAccessException) { this.HandleFileLoadProblem(possibleFilePath); } catch (SerializationException) { this.HandleFileLoadProblem(possibleFilePath); } } return accumulatedPaths.Count; } } /// <summary> /// Asynchronouly tries to load the topmost item and execute an action on it, deleting the topmost object data if the /// operation is successful. /// </summary> /// <typeparam name="TState">The type of the state object to send to the action.</typeparam> /// <param name="predicate">The predicate.</param> /// <param name="actionToInvoke">The action to invoke.</param> /// <param name="state">The state object to pass to the invoked action.</param> /// <param name="cancellationToken">The cancellation token for this operation.</param> /// <returns>The number of items that have been de-queued.</returns> /// <remarks> /// <para> /// Warning! This method has the potential of overrunning its read/write lock timeouts. Please ensure that the /// <paramref name="predicate" /> method /// filters out items in a way that limits the amount of data passing through. /// </para> /// </remarks> protected async Task<int> TryLoadWhilePredicateWithActionAsync<TState>( [NotNull] Func<TState, T, Task<bool>> predicate, [NotNull] Action<TState, IEnumerable<T>> actionToInvoke, [CanBeNull] TState state, CancellationToken cancellationToken = default) { Contract.RequiresNotNull( in predicate, nameof(predicate)); Contract.RequiresNotNull( in actionToInvoke, nameof(actionToInvoke)); this.RequiresNotDisposed(); using (ReadWriteSynchronizationLocker locker = this.ReadWriteLock()) { string[] files = this.GetPossibleDataFiles(); var i = 0; var accumulatedObjects = new List<T>(); var accumulatedPaths = new List<string>(); while (i < files.Length) { if (cancellationToken.IsCancellationRequested) { break; } var possibleFilePath = files[i]; try { T obj; using (Stream stream = this.FileShim.OpenRead(possibleFilePath)) { obj = (T)this.Serializer.ReadObject(stream); } if (!await predicate( state, obj).ConfigureAwait(false)) { break; } accumulatedObjects.Add(obj); accumulatedPaths.Add(possibleFilePath); i++; } catch (IOException) { this.HandleFileLoadProblem(possibleFilePath); i++; } catch (UnauthorizedAccessException) { this.HandleFileLoadProblem(possibleFilePath); i++; } catch (SerializationException) { this.HandleFileLoadProblem(possibleFilePath); i++; } } if (accumulatedObjects.Count <= 0) { cancellationToken.ThrowIfCancellationRequested(); return accumulatedPaths.Count; } try { actionToInvoke( state, accumulatedObjects); } catch (Exception) { cancellationToken.ThrowIfCancellationRequested(); #pragma warning disable ERP022 // Catching everything considered harmful. - We will mitigate shortly return 0; #pragma warning restore ERP022 // Catching everything considered harmful. } locker.Upgrade(); foreach (var possibleFilePath in accumulatedPaths) { try { this.FileShim.Delete(possibleFilePath); } catch (IOException) { this.HandleFileLoadProblem(possibleFilePath); } catch (UnauthorizedAccessException) { this.HandleFileLoadProblem(possibleFilePath); } catch (SerializationException) { this.HandleFileLoadProblem(possibleFilePath); } } cancellationToken.ThrowIfCancellationRequested(); return accumulatedPaths.Count; } } /// <summary> /// Asynchronously tries to load the topmost item and execute an action on it, deleting the topmost object data if the /// operation is successful. /// </summary> /// <typeparam name="TState">The type of the state object to send to the action.</typeparam> /// <param name="predicate">The predicate.</param> /// <param name="actionToInvoke">The action to invoke.</param> /// <param name="state">The state object to pass to the invoked action.</param> /// <param name="cancellationToken">The cancellation token for this operation.</param> /// <returns>The number of items that have been de-queued.</returns> /// <remarks> /// <para> /// Warning! This method has the potential of overrunning its read/write lock timeouts. Please ensure that the /// <paramref name="predicate" /> method /// filters out items in a way that limits the amount of data passing through. /// </para> /// </remarks> protected async Task<int> TryLoadWhilePredicateWithActionAsync<TState>( [NotNull] Func<TState, T, bool> predicate, [NotNull] Func<TState, IEnumerable<T>, Task> actionToInvoke, [CanBeNull] TState state, CancellationToken cancellationToken = default) { Contract.RequiresNotNull( in predicate, nameof(predicate)); Contract.RequiresNotNull( in actionToInvoke, nameof(actionToInvoke)); this.RequiresNotDisposed(); using (ReadWriteSynchronizationLocker locker = this.ReadWriteLock()) { string[] files = this.GetPossibleDataFiles(); var i = 0; var accumulatedObjects = new List<T>(); var accumulatedPaths = new List<string>(); while (i < files.Length) { if (cancellationToken.IsCancellationRequested) { break; } var possibleFilePath = files[i]; try { T obj; using (Stream stream = this.FileShim.OpenRead(possibleFilePath)) { obj = (T)this.Serializer.ReadObject(stream); } if (!predicate( state, obj)) { break; } accumulatedObjects.Add(obj); accumulatedPaths.Add(possibleFilePath); i++; } catch (IOException) { this.HandleFileLoadProblem(possibleFilePath); i++; } catch (UnauthorizedAccessException) { this.HandleFileLoadProblem(possibleFilePath); i++; } catch (SerializationException) { this.HandleFileLoadProblem(possibleFilePath); i++; } } if (accumulatedObjects.Count <= 0) { cancellationToken.ThrowIfCancellationRequested(); return accumulatedPaths.Count; } try { await actionToInvoke( state, accumulatedObjects).ConfigureAwait(false); } catch (Exception) { cancellationToken.ThrowIfCancellationRequested(); #pragma warning disable ERP022 // Catching everything considered harmful. - We will mitigate shortly return 0; #pragma warning restore ERP022 // Catching everything considered harmful. } locker.Upgrade(); foreach (var possibleFilePath in accumulatedPaths) { try { this.FileShim.Delete(possibleFilePath); } catch (IOException) { this.HandleFileLoadProblem(possibleFilePath); } catch (UnauthorizedAccessException) { this.HandleFileLoadProblem(possibleFilePath); } catch (SerializationException) { this.HandleFileLoadProblem(possibleFilePath); } } cancellationToken.ThrowIfCancellationRequested(); return accumulatedPaths.Count; } } /// <summary> /// Asynchronously tries to load the topmost item and execute an action on it, deleting the topmost object data if the /// operation is successful. /// </summary> /// <typeparam name="TState">The type of the state object to send to the action.</typeparam> /// <param name="predicate">The predicate.</param> /// <param name="actionToInvoke">The action to invoke.</param> /// <param name="state">The state object to pass to the invoked action.</param> /// <param name="cancellationToken">The cancellation token for this operation.</param> /// <returns>The number of items that have been de-queued.</returns> /// <remarks> /// <para> /// Warning! This method has the potential of overrunning its read/write lock timeouts. Please ensure that the /// <paramref name="predicate" /> method /// filters out items in a way that limits the amount of data passing through. /// </para> /// </remarks> protected async Task<int> TryLoadWhilePredicateWithActionAsync<TState>( [NotNull] Func<TState, T, Task<bool>> predicate, [NotNull] Func<TState, IEnumerable<T>, Task> actionToInvoke, [CanBeNull] TState state, CancellationToken cancellationToken = default) { Contract.RequiresNotNull( in predicate, nameof(predicate)); Contract.RequiresNotNull( in actionToInvoke, nameof(actionToInvoke)); this.RequiresNotDisposed(); using (ReadWriteSynchronizationLocker locker = this.ReadWriteLock()) { string[] files = this.GetPossibleDataFiles(); var i = 0; var accumulatedObjects = new List<T>(); var accumulatedPaths = new List<string>(); while (i < files.Length) { if (cancellationToken.IsCancellationRequested) { break; } var possibleFilePath = files[i]; try { T obj; using (Stream stream = this.FileShim.OpenRead(possibleFilePath)) { obj = (T)this.Serializer.ReadObject(stream); } if (!await predicate( state, obj).ConfigureAwait(false)) { break; } accumulatedObjects.Add(obj); accumulatedPaths.Add(possibleFilePath); i++; } catch (IOException) { this.HandleFileLoadProblem(possibleFilePath); i++; } catch (UnauthorizedAccessException) { this.HandleFileLoadProblem(possibleFilePath); i++; } catch (SerializationException) { this.HandleFileLoadProblem(possibleFilePath); i++; } } if (accumulatedObjects.Count <= 0) { cancellationToken.ThrowIfCancellationRequested(); return accumulatedPaths.Count; } try { await actionToInvoke( state, accumulatedObjects).ConfigureAwait(false); } catch (Exception) { cancellationToken.ThrowIfCancellationRequested(); #pragma warning disable ERP022 // Catching everything considered harmful. - We will mitigate shortly return 0; #pragma warning restore ERP022 // Catching everything considered harmful. } locker.Upgrade(); foreach (var possibleFilePath in accumulatedPaths) { try { this.FileShim.Delete(possibleFilePath); } catch (IOException) { this.HandleFileLoadProblem(possibleFilePath); } catch (UnauthorizedAccessException) { this.HandleFileLoadProblem(possibleFilePath); } catch (SerializationException) { this.HandleFileLoadProblem(possibleFilePath); } } cancellationToken.ThrowIfCancellationRequested(); return accumulatedPaths.Count; } } /// <summary> /// Peeks at the topmost item in the folder. /// </summary> /// <returns>An item, if one exists and can be loaded, or an exception otherwise.</returns> /// <exception cref="InvalidOperationException">There are no more valid items in the folder.</exception> protected T PeekTopmostItem() { this.RequiresNotDisposed(); using (this.ReadLock()) { string[] files = this.GetPossibleDataFiles(); var i = 0; while (true) { if (i >= files.Length) { throw new InvalidOperationException(); } var possibleFilePath = files[i]; try { using (Stream stream = this.FileShim.OpenRead(possibleFilePath)) { return (T)this.Serializer.ReadObject(stream); } } catch (IOException) { this.HandleFileLoadProblem(possibleFilePath); i++; } catch (UnauthorizedAccessException) { this.HandleFileLoadProblem(possibleFilePath); i++; } catch (SerializationException) { this.HandleFileLoadProblem(possibleFilePath); i++; } } } } /// <summary> /// Loads the items from the folder. /// </summary> /// <returns>An item, if one exists and can be loaded, a default value otherwise.</returns> /// <remarks> /// <para>Warning! Not synchronized.</para> /// <para> /// This method is not synchronized between threads. Please ensure that you only use this method in a guaranteed /// one-time-access manner (such as a constructor). /// </para> /// </remarks> /// <exception cref="InvalidOperationException">There are no more valid items in the folder.</exception> [NotNull] protected IEnumerable<Tuple<T, string>> LoadValidItemObjectHandles() { foreach (var possibleFilePath in this.GetPossibleDataFiles()) { T obj; try { using (Stream stream = this.FileShim.OpenRead(possibleFilePath)) { obj = (T)this.Serializer.ReadObject(stream); } } catch (IOException) { this.HandleFileLoadProblem(possibleFilePath); continue; } catch (UnauthorizedAccessException) { this.HandleFileLoadProblem(possibleFilePath); continue; } catch (SerializationException) { this.HandleFileLoadProblem(possibleFilePath); continue; } yield return new Tuple<T, string>( obj, possibleFilePath); } } /// <summary> /// Saves the new item to the disk. /// </summary> /// <param name="item">The item to save.</param> /// <returns>The path of the newly-saved file.</returns> /// <exception cref="InvalidOperationException"> /// We have reached the maximum number of items saved in the same femtosecond. /// This is theoretically not possible. /// </exception> [NotNull] protected string SaveNewItem(T item) { this.RequiresNotDisposed(); using (this.WriteLock()) { var i = 1; string filePath; DateTime now = DateTime.UtcNow; do { #pragma warning disable HAA0601 // Value type to reference type conversion causing boxing allocation - This is a false positive filePath = this.PathShim.Combine( this.DataFolderPath, $"{now:yyyy.MM.dd.HH.mm.ss.fffffff}.{i}.dat"); #pragma warning restore HAA0601 // Value type to reference type conversion causing boxing allocation i++; if (i == int.MaxValue) { throw new InvalidOperationException(); } } while (this.FileShim.Exists(filePath)); using (Stream stream = this.FileShim.Create(filePath)) { #pragma warning disable HAA0601 // Value type to reference type conversion causing boxing allocation - This is unavoidable this.Serializer.WriteObject( stream, item); #pragma warning restore HAA0601 // Value type to reference type conversion causing boxing allocation } return filePath; } } /// <summary> /// Clears the data. /// </summary> protected void ClearData() { this.RequiresNotDisposed(); using (this.WriteLock()) { foreach (var possibleFilePath in this.DirectoryShim.EnumerateFiles( this.DataFolderPath, "*.dat").ToArray()) { this.HandleImpossibleMoveToPoison(possibleFilePath); } } this.FixUnmovableReferences(); } /// <summary> /// Gets the possible data files. /// </summary> /// <returns>An array of data file names.</returns> [NotNull] protected string[] GetPossibleDataFiles() => this.DirectoryShim.EnumerateFiles( this.DataFolderPath, "*.dat").Except(this.poisonedUnremovableFiles).ToArray(); /// <summary> /// Handles the file load problem. /// </summary> /// <param name="possibleFilePath">The possible file path.</param> private void HandleFileLoadProblem(string possibleFilePath) { Contract.RequiresNotNullOrWhitespacePrivate( possibleFilePath, nameof(possibleFilePath)); var newFilePath = this.PathShim.Combine( this.PoisonFolderPath, this.PathShim.GetFileName(possibleFilePath)); // Seemingly-redundant catch code below will be replaced at a later time with an opt-in-based logging solution // and a more try/finally general approach // If an item by the same name exists in the poison queue, delete it try { if (this.FileShim.Exists(newFilePath)) { this.FileShim.Delete(newFilePath); } } catch (IOException) { this.HandleImpossibleMoveToPoison(possibleFilePath); return; } catch (UnauthorizedAccessException) { this.HandleImpossibleMoveToPoison(possibleFilePath); return; } try { // Move to poison queue this.FileShim.Move( possibleFilePath, newFilePath); } catch (IOException) { this.HandleImpossibleMoveToPoison(possibleFilePath); } catch (UnauthorizedAccessException) { this.HandleImpossibleMoveToPoison(possibleFilePath); } } /// <summary> /// Handles the situation where it is impossible to move a file to poison. /// </summary> /// <param name="possibleFilePath">The possible file path.</param> private void HandleImpossibleMoveToPoison(string possibleFilePath) { Contract.RequiresNotNullOrWhitespacePrivate( possibleFilePath, nameof(possibleFilePath)); try { // If deletion was not possible, delete the offending item this.FileShim.Delete(possibleFilePath); } catch (IOException) { this.poisonedUnremovableFiles.Add(possibleFilePath); } catch (UnauthorizedAccessException) { this.poisonedUnremovableFiles.Add(possibleFilePath); } } /// <summary> /// Fixes the unmovable references. /// </summary> private void FixUnmovableReferences() { foreach (var file in this.poisonedUnremovableFiles.ToArray()) { try { if (!this.FileShim.Exists(file)) { this.poisonedUnremovableFiles.Remove(file); } } catch (IOException) { } catch (UnauthorizedAccessException) { } } } } }
using System; using System.IO; using System.Collections.Specialized; using System.Diagnostics.CodeAnalysis; using System.Net; using System.Net.Cache; using System.Text; using System.Web; using System.Security.Cryptography; using Newtonsoft.Json; using System.Security.Cryptography.X509Certificates; using System.Net.Security; using SteamKit2; using System.Threading; namespace SteamTrade { /// <summary> /// SteamWeb class to create an API endpoint to the Steam Web. /// </summary> public class SteamWeb { /// <summary> /// Base steam community domain. /// </summary> public const string SteamCommunityDomain = "steamcommunity.com"; /// <summary> /// Token of steam. Generated after login. /// </summary> public string Token { get; private set; } /// <summary> /// Session id of Steam after Login. /// </summary> public string SessionId { get; private set; } /// <summary> /// Token secure as string. It is generated after the Login. /// </summary> public string TokenSecure { get; private set; } /// <summary> /// The Accept-Language header when sending all HTTP requests. Default value is determined according to the constructor caller thread's culture. /// </summary> public string AcceptLanguageHeader { get { return acceptLanguageHeader; } set { acceptLanguageHeader = value; } } private string acceptLanguageHeader = Thread.CurrentThread.CurrentCulture.TwoLetterISOLanguageName == "en" ? Thread.CurrentThread.CurrentCulture.ToString() + ",en;q=0.8" : Thread.CurrentThread.CurrentCulture.ToString() + "," + Thread.CurrentThread.CurrentCulture.TwoLetterISOLanguageName + ";q=0.8,en;q=0.6"; /// <summary> /// CookieContainer to save all cookies during the Login. /// </summary> private CookieContainer _cookies = new CookieContainer(); /// <summary> /// This method is using the Request method to return the full http stream from a web request as string. /// </summary> /// <param name="url">URL of the http request.</param> /// <param name="method">Gets the HTTP data transfer method (such as GET, POST, or HEAD) used by the client.</param> /// <param name="data">A NameValueCollection including Headers added to the request.</param> /// <param name="ajax">A bool to define if the http request is an ajax request.</param> /// <param name="referer">Gets information about the URL of the client's previous request that linked to the current URL.</param> /// <param name="fetchError">If true, response codes other than HTTP 200 will still be returned, rather than throwing exceptions</param> /// <returns>The string of the http return stream.</returns> /// <remarks>If you want to know how the request method works, use: <see cref="SteamWeb.Request"/></remarks> public string Fetch(string url, string method, NameValueCollection data = null, bool ajax = true, string referer = "", bool fetchError = false) { // Reading the response as stream and read it to the end. After that happened return the result as string. using (HttpWebResponse response = Request(url, method, data, ajax, referer, fetchError)) { using (Stream responseStream = response.GetResponseStream()) { // If the response stream is null it cannot be read. So return an empty string. if (responseStream == null) { return ""; } using (StreamReader reader = new StreamReader(responseStream)) { return reader.ReadToEnd(); } } } } /// <summary> /// Custom wrapper for creating a HttpWebRequest, edited for Steam. /// </summary> /// <param name="url">Gets information about the URL of the current request.</param> /// <param name="method">Gets the HTTP data transfer method (such as GET, POST, or HEAD) used by the client.</param> /// <param name="data">A NameValueCollection including Headers added to the request.</param> /// <param name="ajax">A bool to define if the http request is an ajax request.</param> /// <param name="referer">Gets information about the URL of the client's previous request that linked to the current URL.</param> /// <param name="fetchError">Return response even if its status code is not 200</param> /// <returns>An instance of a HttpWebResponse object.</returns> public HttpWebResponse Request(string url, string method, NameValueCollection data = null, bool ajax = true, string referer = "", bool fetchError = false) { // Append the data to the URL for GET-requests. bool isGetMethod = (method.ToLower() == "get"); string dataString = (data == null ? null : String.Join("&", Array.ConvertAll(data.AllKeys, key => // ReSharper disable once UseStringInterpolation string.Format("{0}={1}", HttpUtility.UrlEncode(key), HttpUtility.UrlEncode(data[key])) ))); // Example working with C# 6 // string dataString = (data == null ? null : String.Join("&", Array.ConvertAll(data.AllKeys, key => $"{HttpUtility.UrlEncode(key)}={HttpUtility.UrlEncode(data[key])}" ))); // Append the dataString to the url if it is a GET request. if (isGetMethod && !string.IsNullOrEmpty(dataString)) { url += (url.Contains("?") ? "&" : "?") + dataString; } // Setup the request. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = method; request.Accept = "application/json, text/javascript;q=0.9, */*;q=0.5"; request.Headers[HttpRequestHeader.AcceptLanguage] = AcceptLanguageHeader; request.ContentType = "application/x-www-form-urlencoded; charset=UTF-8"; // request.Host is set automatically. request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36"; request.Referer = string.IsNullOrEmpty(referer) ? "http://steamcommunity.com/trade/1" : referer; request.Timeout = 50000; // Timeout after 50 seconds. request.CachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.Revalidate); request.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip; // If the request is an ajax request we need to add various other Headers, defined below. if (ajax) { request.Headers.Add("X-Requested-With", "XMLHttpRequest"); request.Headers.Add("X-Prototype-Version", "1.7"); } // Cookies request.CookieContainer = _cookies; // If the request is a GET request return now the response. If not go on. Because then we need to apply data to the request. if (isGetMethod || string.IsNullOrEmpty(dataString)) { return request.GetResponse() as HttpWebResponse; } // Write the data to the body for POST and other methods. byte[] dataBytes = Encoding.UTF8.GetBytes(dataString); request.ContentLength = dataBytes.Length; using (Stream requestStream = request.GetRequestStream()) { requestStream.Write(dataBytes, 0, dataBytes.Length); } // Get the response and return it. try { return request.GetResponse() as HttpWebResponse; } catch (WebException ex) { //this is thrown if response code is not 200 if (fetchError) { var resp = ex.Response as HttpWebResponse; if (resp != null) { return resp; } } throw; } } /// <summary> /// Executes the login by using the Steam Website. /// This Method is not used by Steambot repository, but it could be very helpful if you want to build a own Steambot or want to login into steam services like backpack.tf/csgolounge.com. /// Updated: 10-02-2015. /// </summary> /// <param name="username">Your Steam username.</param> /// <param name="password">Your Steam password.</param> /// <returns>A bool containing a value, if the login was successful.</returns> public bool DoLogin(string username, string password) { var data = new NameValueCollection {{"username", username}}; // First get the RSA key with which we will encrypt our password. string response = Fetch("https://steamcommunity.com/login/getrsakey", "POST", data, false); GetRsaKey rsaJson = JsonConvert.DeserializeObject<GetRsaKey>(response); // Validate, if we could get the rsa key. if (!rsaJson.success) { return false; } // RSA Encryption. RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); RSAParameters rsaParameters = new RSAParameters { Exponent = HexToByte(rsaJson.publickey_exp), Modulus = HexToByte(rsaJson.publickey_mod) }; rsa.ImportParameters(rsaParameters); // Encrypt the password and convert it. byte[] bytePassword = Encoding.ASCII.GetBytes(password); byte[] encodedPassword = rsa.Encrypt(bytePassword, false); string encryptedBase64Password = Convert.ToBase64String(encodedPassword); SteamResult loginJson = null; CookieCollection cookieCollection; string steamGuardText = ""; string steamGuardId = ""; // Do this while we need a captcha or need email authentification. Probably you have misstyped the captcha or the SteamGaurd code if this comes multiple times. do { Console.WriteLine("SteamWeb: Logging In..."); bool captcha = loginJson != null && loginJson.captcha_needed; bool steamGuard = loginJson != null && loginJson.emailauth_needed; string time = Uri.EscapeDataString(rsaJson.timestamp); string capGid = string.Empty; // Response does not need to send if captcha is needed or not. // ReSharper disable once MergeSequentialChecks if (loginJson != null && loginJson.captcha_gid != null) { capGid = Uri.EscapeDataString(loginJson.captcha_gid); } data = new NameValueCollection {{"password", encryptedBase64Password}, {"username", username}}; // Captcha Check. string capText = ""; if (captcha) { Console.WriteLine("SteamWeb: Captcha is needed."); System.Diagnostics.Process.Start("https://steamcommunity.com/public/captcha.php?gid=" + loginJson.captcha_gid); Console.WriteLine("SteamWeb: Type the captcha:"); string consoleText = Console.ReadLine(); if (!string.IsNullOrEmpty(consoleText)) { capText = Uri.EscapeDataString(consoleText); } } data.Add("captchagid", captcha ? capGid : ""); data.Add("captcha_text", captcha ? capText : ""); // Captcha end. // Added Header for two factor code. data.Add("twofactorcode", ""); // Added Header for remember login. It can also set to true. data.Add("remember_login", "false"); // SteamGuard check. If SteamGuard is enabled you need to enter it. Care probably you need to wait 7 days to trade. // For further information about SteamGuard see: https://support.steampowered.com/kb_article.php?ref=4020-ALZM-5519&l=english. if (steamGuard) { Console.WriteLine("SteamWeb: SteamGuard is needed."); Console.WriteLine("SteamWeb: Type the code:"); string consoleText = Console.ReadLine(); if (!string.IsNullOrEmpty(consoleText)) { steamGuardText = Uri.EscapeDataString(consoleText); } steamGuardId = loginJson.emailsteamid; // Adding the machine name to the NameValueCollection, because it is requested by steam. Console.WriteLine("SteamWeb: Type your machine name:"); consoleText = Console.ReadLine(); var machineName = string.IsNullOrEmpty(consoleText) ? "" : Uri.EscapeDataString(consoleText); data.Add("loginfriendlyname", machineName != "" ? machineName : "defaultSteamBotMachine"); } data.Add("emailauth", steamGuardText); data.Add("emailsteamid", steamGuardId); // SteamGuard end. // Added unixTimestamp. It is included in the request normally. var unixTimestamp = (int)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds; // Added three "0"'s because Steam has a weird unix timestamp interpretation. data.Add("donotcache", unixTimestamp + "000"); data.Add("rsatimestamp", time); // Sending the actual login. using(HttpWebResponse webResponse = Request("https://steamcommunity.com/login/dologin/", "POST", data, false)) { var stream = webResponse.GetResponseStream(); if (stream == null) { return false; } using (StreamReader reader = new StreamReader(stream)) { string json = reader.ReadToEnd(); loginJson = JsonConvert.DeserializeObject<SteamResult>(json); cookieCollection = webResponse.Cookies; } } } while (loginJson.captcha_needed || loginJson.emailauth_needed); // If the login was successful, we need to enter the cookies to steam. if (loginJson.success) { _cookies = new CookieContainer(); foreach (Cookie cookie in cookieCollection) { _cookies.Add(cookie); } SubmitCookies(_cookies); return true; } else { Console.WriteLine("SteamWeb Error: " + loginJson.message); return false; } } ///<summary> /// Authenticate using SteamKit2 and ISteamUserAuth. /// This does the same as SteamWeb.DoLogin(), but without contacting the Steam Website. /// </summary> /// <remarks>Should this one doesnt work anymore, use <see cref="SteamWeb.DoLogin"/></remarks> /// <param name="myUniqueId">Id what you get to login.</param> /// <param name="client">An instance of a SteamClient.</param> /// <param name="myLoginKey">Login Key of your account.</param> /// <returns>A bool, which is true if the login was successful.</returns> public bool Authenticate(string myUniqueId, SteamClient client, string myLoginKey) { Token = TokenSecure = ""; SessionId = Convert.ToBase64String(Encoding.UTF8.GetBytes(myUniqueId)); _cookies = new CookieContainer(); using (dynamic userAuth = WebAPI.GetInterface("ISteamUserAuth")) { // Generate an AES session key. var sessionKey = CryptoHelper.GenerateRandomBlock(32); // rsa encrypt it with the public key for the universe we're on byte[] cryptedSessionKey; using (RSACrypto rsa = new RSACrypto(KeyDictionary.GetPublicKey(client.ConnectedUniverse))) { cryptedSessionKey = rsa.Encrypt(sessionKey); } byte[] loginKey = new byte[20]; Array.Copy(Encoding.ASCII.GetBytes(myLoginKey), loginKey, myLoginKey.Length); // AES encrypt the loginkey with our session key. byte[] cryptedLoginKey = CryptoHelper.SymmetricEncrypt(loginKey, sessionKey); KeyValue authResult; // Get the Authentification Result. try { authResult = userAuth.AuthenticateUser( steamid: client.SteamID.ConvertToUInt64(), sessionkey: HttpUtility.UrlEncode(cryptedSessionKey), encrypted_loginkey: HttpUtility.UrlEncode(cryptedLoginKey), method: "POST", secure: true ); } catch (Exception) { Token = TokenSecure = null; return false; } Token = authResult["token"].AsString(); TokenSecure = authResult["tokensecure"].AsString(); // Adding cookies to the cookie container. _cookies.Add(new Cookie("sessionid", SessionId, string.Empty, SteamCommunityDomain)); _cookies.Add(new Cookie("steamLogin", Token, string.Empty, SteamCommunityDomain)); _cookies.Add(new Cookie("steamLoginSecure", TokenSecure, string.Empty, SteamCommunityDomain)); return true; } } /// <summary> /// Authenticate using an array of cookies from a browser or whatever source, without contacting the server. /// It is recommended that you call <see cref="VerifyCookies"/> after calling this method to ensure that the cookies are valid. /// </summary> /// <param name="cookies">An array of cookies from a browser or whatever source. Must contain sessionid, steamLogin, steamLoginSecure</param> /// <exception cref="ArgumentException">One of the required cookies(steamLogin, steamLoginSecure, sessionid) is missing.</exception> public void Authenticate(System.Collections.Generic.IEnumerable<Cookie> cookies) { var cookieContainer = new CookieContainer(); string token = null; string tokenSecure = null; string sessionId = null; foreach (var cookie in cookies) { if (cookie.Name == "sessionid") sessionId = cookie.Value; else if (cookie.Name == "steamLogin") token = cookie.Value; else if (cookie.Name == "steamLoginSecure") tokenSecure = cookie.Value; cookieContainer.Add(cookie); } if (token == null) throw new ArgumentException("Cookie with name \"steamLogin\" is not found."); if (tokenSecure == null) throw new ArgumentException("Cookie with name \"steamLoginSecure\" is not found."); if (sessionId == null) throw new ArgumentException("Cookie with name \"sessionid\" is not found."); Token = token; TokenSecure = tokenSecure; SessionId = sessionId; _cookies = cookieContainer; } /// <summary> /// Helper method to verify our precious cookies. /// </summary> /// <returns>true if cookies are correct; false otherwise</returns> public bool VerifyCookies() { using (HttpWebResponse response = Request("http://steamcommunity.com/", "HEAD")) { return response.Cookies["steamLogin"] == null || !response.Cookies["steamLogin"].Value.Equals("deleted"); } } /// <summary> /// Method to submit cookies to Steam after Login. /// </summary> /// <param name="cookies">Cookiecontainer which contains cookies after the login to Steam.</param> static void SubmitCookies (CookieContainer cookies) { HttpWebRequest w = WebRequest.Create("https://steamcommunity.com/") as HttpWebRequest; // Check, if the request is null. if (w == null) { return; } w.Method = "POST"; w.ContentType = "application/x-www-form-urlencoded"; w.CookieContainer = cookies; // Added content-length because it is required. w.ContentLength = 0; w.GetResponse().Close(); } /// <summary> /// Method to convert a Hex to a byte. /// </summary> /// <param name="hex">Input parameter as string.</param> /// <returns>The byte value.</returns> private byte[] HexToByte(string hex) { if (hex.Length % 2 == 1) { throw new Exception("The binary key cannot have an odd number of digits"); } byte[] arr = new byte[hex.Length >> 1]; int l = hex.Length; for (int i = 0; i < (l >> 1); ++i) { arr[i] = (byte)((GetHexVal(hex[i << 1]) << 4) + (GetHexVal(hex[(i << 1) + 1]))); } return arr; } /// <summary> /// Get the Hex value as int out of an char. /// </summary> /// <param name="hex">Input parameter.</param> /// <returns>A Hex Value as int.</returns> private int GetHexVal(char hex) { int val = hex; return val - (val < 58 ? 48 : 55); } /// <summary> /// Method to allow all certificates. /// </summary> /// <param name="sender">An object that contains state information for this validation.</param> /// <param name="certificate">The certificate used to authenticate the remote party.</param> /// <param name="chain">The chain of certificate authorities associated with the remote certificate.</param> /// <param name="policyErrors">One or more errors associated with the remote certificate.</param> /// <returns>Always true to accept all certificates.</returns> public bool ValidateRemoteCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors policyErrors) { return true; } } // JSON Classes // These classes are used to deserialize response strings from the login: // Example of a return string: {"success":true,"publickey_mod":"XXXX87144BF5B2CABFEC24E35655FDC5E438D6064E47D33A3531F3AAB195813E316A5D8AAB1D8A71CB7F031F801200377E8399C475C99CBAFAEFF5B24AE3CF64BXXXXB2FDBA3BC3974D6DCF1E760F8030AB5AB40FA8B9D193A8BEB43AA7260482EAD5CE429F718ED06B0C1F7E063FE81D4234188657DB40EEA4FAF8615111CD3E14CAF536CXXXX3C104BE060A342BF0C9F53BAAA2A4747E43349FF0518F8920664F6E6F09FE41D8D79C884F8FD037276DED0D1D1D540A2C2B6639CF97FF5180E3E75224EXXXX56AAA864EEBF9E8B35B80E25B405597219BFD90F3AD9765D81D148B9500F12519F1F96828C12AEF77D948D0DC9FDAF8C7CC73527ADE7C7F0FF33","publickey_exp":"010001","timestamp":"241590850000","steamid":"7656119824534XXXX","token_gid":"c35434c0c07XXXX"} /// <summary> /// Class to Deserialize the json response strings of the getResKey request. See: <see cref="SteamWeb.DoLogin"/> /// </summary> [SuppressMessage("ReSharper", "InconsistentNaming")] public class GetRsaKey { public bool success { get; set; } public string publickey_mod { get; set; } public string publickey_exp { get; set; } public string timestamp { get; set; } } // Examples: // For not accepted SteamResult: // {"success":false,"requires_twofactor":false,"message":"","emailauth_needed":true,"emaildomain":"gmail.com","emailsteamid":"7656119824534XXXX"} // For accepted SteamResult: // {"success":true,"requires_twofactor":false,"login_complete":true,"transfer_url":"https:\/\/store.steampowered.com\/login\/transfer","transfer_parameters":{"steamid":"7656119824534XXXX","token":"XXXXC39589A9XXXXCB60D651EFXXXX85578AXXXX","auth":"XXXXf1d9683eXXXXc76bdc1888XXXX29","remember_login":false,"webcookie":"XXXX4C33779A4265EXXXXC039D3512DA6B889D2F","token_secure":"XXXX63F43AA2CXXXXC703441A312E1B14AC2XXXX"}} /// <summary> /// Class to Deserialize the json response strings after the login. See: <see cref="SteamWeb.DoLogin"/> /// </summary> [SuppressMessage("ReSharper", "InconsistentNaming")] public class SteamResult { public bool success { get; set; } public string message { get; set; } public bool captcha_needed { get; set; } public string captcha_gid { get; set; } public bool emailauth_needed { get; set; } public string emailsteamid { get; set; } } }
// 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 Microsoft.Build.Framework; using Microsoft.Build.BuildEngine.Shared; using System.Threading; namespace Microsoft.Build.BuildEngine { /// <summary> /// This class is resposible for managing the node providers - starting, stopping and sharing them. /// Although child nodes have a NodeManager, theirs do nothing as they never has any NodeProviders registered with them. /// </summary> internal class NodeManager { #region Constructors /// <summary> /// Default constructor. /// </summary> internal NodeManager(int cpuCount, bool childMode, Engine parentEngine) { nodeList = new List<ProvidersNodeInformation>(); nodeProviders = new List<INodeProvider>(); this.parentEngine = parentEngine; this.statusMessageReceived = new ManualResetEvent(false); // Create the inproc node, this means that there will always be one node, node 0 if (taskExecutionModule == null) { taskExecutionModule = new TaskExecutionModule(parentEngine.EngineCallback, (cpuCount == 1 && !childMode ? TaskExecutionModule.TaskExecutionModuleMode.SingleProcMode : TaskExecutionModule.TaskExecutionModuleMode.MultiProcFullNodeMode), parentEngine.ProfileBuild); } } #endregion #region Methods /// <summary> /// Register an instantiated INodeProvider with the node manager. The node manager will query the nodeprovider /// for a list of its node descriptions, and add these nodes to a master list of nodes which can be used /// by the scheduler. QUESTION: Do we allow duplicate Node Providers? /// </summary> /// <param name="providerToRegister"></param> /// <returns></returns> internal bool RegisterNodeProvider(INodeProvider nodeProviderToRegister) { ErrorUtilities.VerifyThrowArgumentNull(nodeProviderToRegister,"nodeProviderToRegister"); INodeDescription[] nodeDescriptions = nodeProviderToRegister.QueryNodeDescriptions(); int[] nodeIds = new int[nodeDescriptions.Length]; for (int i = 0; i < nodeIds.Length; i++) { nodeIds[i] = parentEngine.GetNextNodeId(); } nodeProviderToRegister.AssignNodeIdentifiers(nodeIds); // Go through all of the nodes as described by nodeDescriptions and add them to out list of nodes for(int i=0; i < nodeDescriptions.Length;i++) { ProvidersNodeInformation nodeToAddFromProvider = new ProvidersNodeInformation(i, nodeIds[i], nodeDescriptions[i], nodeProviderToRegister); nodeList.Add(nodeToAddFromProvider); } nodeProviders.Add(nodeProviderToRegister); return true; } /// <summary> /// Provide an array of INodeDescriptionsof the node provided by the node provider for the node. The index of the description /// is the node index to which the description matches /// </summary> /// <returns></returns> internal INodeDescription[] GetNodeDescriptions() { // The number of node descriptions is the number of nodes from all of the node providers, plus one for the default "0" node INodeDescription[] nodeDescription = new INodeDescription[nodeList.Count+1]; nodeDescription[0] = null; for (int nodeListIndex = 0; nodeListIndex < nodeList.Count; nodeListIndex++) { ProvidersNodeInformation nodeInfo = nodeList[nodeListIndex]; // +1 because the node description already has the 0 element set to null nodeDescription[nodeListIndex + 1] = nodeInfo.Description; } return nodeDescription; } /// <summary> /// Register node logger with all currently available providers /// </summary> /// <param name="loggerDescription"></param> internal void RegisterNodeLogger(LoggerDescription loggerDescription) { foreach (INodeProvider nodeProvider in nodeProviders) { nodeProvider.RegisterNodeLogger(loggerDescription); } } /// <summary> /// Request status from all nodes in the system /// </summary> /// <param name="responseTimeout"></param> /// <returns></returns> internal NodeStatus[] RequestStatusForNodes(int responseTimeout) { int requestId = 0; statusForNodes = new NodeStatus[nodeList.Count]; statusReplyCount = 0; statusMessageReceived.Reset(); // Request status from all registered nodes for (int i = 0; i < nodeList.Count; i++) { nodeList[i].NodeProvider.RequestNodeStatus(nodeList[i].NodeIndex, requestId); } long startTime = DateTime.Now.Ticks; while (statusReplyCount < nodeList.Count) { if (statusMessageReceived.WaitOne(responseTimeout, false)) { // We received another reply statusMessageReceived.Reset(); // Calculate the time remaining and only continue if there is time left TimeSpan timeSpent = new TimeSpan(DateTime.Now.Ticks - startTime); startTime = DateTime.Now.Ticks; responseTimeout = responseTimeout - (int)timeSpent.TotalMilliseconds; if (responseTimeout <= 0) { Console.WriteLine("Response time out out exceeded :" + DateTime.Now.Ticks); break; } } else { // Timed out waiting for the response from the node Console.WriteLine("Response time out out exceeded:" + DateTime.Now.Ticks); break; } } return statusForNodes; } internal void PostNodeStatus(int nodeId, NodeStatus nodeStatus) { ErrorUtilities.VerifyThrow( nodeStatus.RequestId != NodeStatus.UnrequestedStatus, "Node manager should not receive unrequested status"); NodeStatus[] currentStatus = statusForNodes; for (int i = 0; i < nodeList.Count; i++) { if (nodeList[i].NodeId == nodeId) { currentStatus[i] = nodeStatus; break; } } statusReplyCount++; statusMessageReceived.Set(); } internal void PostCycleNotification ( int nodeId, TargetInProgessState child, TargetInProgessState parent) { if (nodeId == 0) { parentEngine.Introspector.BreakCycle(child, parent); } for (int i = 0; i < nodeList.Count; i++) { if (nodeList[i].NodeId == nodeId) { nodeList[i].NodeProvider.PostIntrospectorCommand(nodeList[i].NodeIndex, child, parent); break; } } } /// <summary> /// Shut down each of the nodes for all providers registered to the node manager. /// Shuts down the TEM. /// </summary> internal void ShutdownNodes(Node.NodeShutdownLevel nodeShutdownLevel) { foreach (INodeProvider nodeProvider in nodeProviders) { nodeProvider.ShutdownNodes(nodeShutdownLevel); } // Don't shutdown the TEM if the engine maybe reused for another build if (nodeShutdownLevel != Node.NodeShutdownLevel.BuildCompleteFailure && nodeShutdownLevel != Node.NodeShutdownLevel.BuildCompleteSuccess) { if (taskExecutionModule != null) { taskExecutionModule.Shutdown(); taskExecutionModule = null; // At this point we have nulled out the task execution module and have told our task worker threads to exit // we do not want the engine build loop to continue to do any work becasue the operations of the build loop // require the task execution module in many cases. Before this fix, when the engine build loop was allowed // to do work after the task execution module we would get random null reference excetpions depending on // what was the first line to use the TEM after it was nulled out. parentEngine.SetEngineAbortTo(true); } } } /// <summary> /// Post a build result to a node, the node index is an index into the list of nodes provided by all node providers /// registered to the node manager, the 0 in index is a local call to taskexecutionmodule /// </summary> /// <param name="nodeIndex"></param> /// <param name="buildResult"></param> internal void PostBuildResultToNode(int nodeIndex, BuildResult buildResult) { ErrorUtilities.VerifyThrow(nodeIndex <= nodeList.Count, "Should not pass a node index higher then the number of nodes in nodeManager"); if (nodeIndex != 0) { nodeList[nodeIndex-1].NodeProvider.PostBuildResultToNode(nodeList[nodeIndex-1].NodeIndex, buildResult); } else { taskExecutionModule.PostBuildResults(buildResult); } } /// <summary> /// Post a build request to a node, the node index is an index into the list of nodes provided by all node providers /// registered to the node manager, the 0 in index is a local call to taskexecutionmodule /// </summary> /// <param name="nodeIndex"></param> /// <param name="buildRequest"></param> internal void PostBuildRequestToNode(int nodeIndex, BuildRequest buildRequest) { ErrorUtilities.VerifyThrow(nodeIndex != 0, "Should not use NodeManager to post to local TEM"); nodeList[nodeIndex - 1].NodeProvider.PostBuildRequestToNode(nodeList[nodeIndex - 1].NodeIndex, buildRequest); } /// <summary> /// Execute a task on the local node /// </summary> /// <param name="taskState"></param> internal void ExecuteTask(TaskExecutionState taskState) { taskExecutionModule.ExecuteTask(taskState); } /// <summary> /// TEMPORARY /// </summary> internal void UpdateSettings ( bool enableOutofProcLogging, bool enableOnlyLogCriticalEvents, bool useBreadthFirstTraversal ) { foreach (INodeProvider nodeProvider in nodeProviders) { nodeProvider.UpdateSettings(enableOutofProcLogging, enableOnlyLogCriticalEvents, useBreadthFirstTraversal); } } internal void ChangeNodeTraversalType(bool breadthFirstTraversal) { UpdateSettings(parentEngine.EnabledCentralLogging, parentEngine.OnlyLogCriticalEvents, breadthFirstTraversal); } #endregion #region Properties /// <summary> /// Getter access to the local node /// </summary> internal TaskExecutionModule TaskExecutionModule { get { return taskExecutionModule; } set { taskExecutionModule = value; } } /// <summary> /// Number of Nodes being managed by NodeManager /// </summary> internal int MaxNodeCount { get { // add 1 for the local node (taskExecutionModule) return nodeList.Count+1; } } #endregion #region Data /// <summary> /// Pointer to the parent engine /// </summary> private Engine parentEngine; /// <summary> /// List of node information of nodes provided by registered node providers /// </summary> private List<ProvidersNodeInformation> nodeList; /// <summary> /// List of registered node providers /// </summary> private List<INodeProvider> nodeProviders; /// <summary> /// Array of status summaries from the node /// </summary> private NodeStatus[] statusForNodes; /// <summary> /// Count of status replies recieved /// </summary> private int statusReplyCount; /// <summary> /// An event activated when status message arrives /// </summary> private ManualResetEvent statusMessageReceived; /// <summary> /// Local TEM used for executing tasks within the current process /// </summary> private TaskExecutionModule taskExecutionModule; #endregion } /// <summary> /// Class which contains, information about each of the nodes provided by each of the node providers registered to node manager /// </summary> internal class ProvidersNodeInformation { #region Constructors internal ProvidersNodeInformation ( int nodeProviderNodeIndex, int nodeId, INodeDescription nodeProviderDescription, INodeProvider nodeProviderReference ) { this.nodeIndex = nodeProviderNodeIndex; this.nodeId = nodeId; this.description = nodeProviderDescription; this.nodeProvider = nodeProviderReference; } #endregion #region Properties /// <summary> /// Node provider for node /// </summary> internal INodeProvider NodeProvider { get { return nodeProvider; } } /// <summary> /// Node description for node /// </summary> internal INodeDescription Description { get { return description; } } /// <summary> /// Node index relative to the node provider to which it is attached /// </summary> internal int NodeIndex { get { return nodeIndex; } } /// <summary> /// The nodeId issued by the engine to this node /// </summary> internal int NodeId { get { return nodeId; } } #endregion #region Data // Index from nodeProvider of a node which it manages private int nodeIndex; // Node description of node in nodeProvider referenced by nodeIndex; private INodeDescription description; // Reference to the nodeProvider which manages the node referenced by nodeIndex private INodeProvider nodeProvider; // The nodeId issued by the engine to this node private int nodeId; #endregion } }
// (c) Copyright Microsoft Corporation. // This source is subject to the Microsoft Permissive License. // See http://www.microsoft.com/opensource/licenses.mspx#Ms-PL. // All other rights reserved. using System; using System.Diagnostics; using System.Reflection; using System.Collections; using System.Collections.Generic; using System.IO; using System.Text; using System.Windows.Automation; using System.Xml; using System.Xml.Serialization; #if NATIVE_UIA using QueryStringWrapper; #endif namespace Microsoft.Test.UIAutomation.Logging { using Microsoft.Test.UIAutomation.Logging.XmlSerializableObjects; using Microsoft.Test.UIAutomation.TestManager; using Microsoft.Test.UIAutomation.Logging.InfoObjects; using Microsoft.Test.UIAutomation.Core; /// ----------------------------------------------------------------------- /// <summary> /// Loggin object for InternalHelper /// </summary> /// ----------------------------------------------------------------------- sealed public class UIVerifyLogger { public class UILogger { public List<ILogger> uivLogger = new List<ILogger>(); public void Log(object Object) { foreach (ILogger currentLogger in uivLogger) { currentLogger.Log(Object); } } } /// ------------------------------------------------------------------- /// <summary></summary> /// ------------------------------------------------------------------- static int _incorrectConfigurations = 0; /// <summary> /// this holds Logger to use /// </summary> static UILogger _currentLogger = new UILogger(); /// ------------------------------------------------------------------- /// <summary></summary> /// ------------------------------------------------------------------- static string _uivLogFile = String.Empty; /// ------------------------------------------------------------------- /// <summary> /// Report that the test had an error /// </summary> /// ------------------------------------------------------------------- public static void LogError(Exception exception) { // Our test framework calls using Invoke, and throw is returned if (exception is TargetInvocationException) exception = exception.InnerException; // If a test catches the exception, and then rethrows the excpeption later, it uses "RETHROW" // to allow this global exception handler to peel this rethrow and analyze the actual exception. if (exception.Message == "RETHROW") exception = exception.InnerException; if (exception.GetType() == typeof(InternalHelper.Tests.IncorrectElementConfigurationForTestException)) { _incorrectConfigurations++; _currentLogger.Log(new CommentInfo(exception.Message)); LogPass(); } else if (exception.GetType() == typeof(InternalHelper.Tests.TestErrorException)) { _currentLogger.Log(new ExceptionInfo(exception)); _currentLogger.Log(new TestResultInfo(TestResultInfo.TestResults.Failed)); } else { LogUnexpectedError(exception); } } /// ------------------------------------------------------------------- /// <summary> /// Report an excepetion that was not expected /// </summary> /// ------------------------------------------------------------------- public static void LogUnexpectedError(Exception exception) { _currentLogger.Log(new ExceptionInfo(exception, true, false, false)); _currentLogger.Log(new TestResultInfo(TestResultInfo.TestResults.UnexpectedError)); } /// ------------------------------------------------------------------- /// <summary> /// Loads a logger DLL binary that impements WUIALogging interface. /// </summary> /// <param name="filename">Filename with path</param> /// ------------------------------------------------------------------- public static void SetLogger(string filename) { SetLogger(GenericLogger.GetLogger(filename)); } /// ------------------------------------------------------------------- /// <summary> /// Loads a logger DLL binary that impements WUIALogging interface /// </summary> /// <param name="filename">Filename with path</param> /// ------------------------------------------------------------------- static public void SetLogger(ILogger logger) { // Clear the _currentLogger if it is set by old runs _currentLogger.uivLogger.Clear(); if (logger == null) throw new ArgumentNullException(); List<ILogger> loggerList = new List<ILogger>(); if (logger is XmlLogger) { loggerList.Add(logger); } else { loggerList.Add(logger); loggerList.Add(new XmlLogger()); } SetLogger(loggerList); } /// ------------------------------------------------------------------- /// <summary> /// Loads a logger DLL binary that impements WUIALogging interface /// </summary> /// <param name="filename">Filename with path</param> /// ------------------------------------------------------------------- static public void SetLogger(List<ILogger> logger) { for (int i=0; i<logger.Count; i++) { if (logger[i] == null) throw new ArgumentNullException(); _currentLogger.uivLogger.Add(logger[i]); } } /// ------------------------------------------------------------------- /// <summary></summary> /// ------------------------------------------------------------------- public static void LogComment(object comment) { LogComment(comment.ToString()); } /// ------------------------------------------------------------------- /// <summary> /// Log comment to the output /// </summary> /// <param name="format">The format string</param> /// <param name="args">An array of objects to write using format</param> /// ------------------------------------------------------------------- public static void LogComment(string format, params object[] args) { // format may have formating characters '{' & '}', only call // String.Format if there is a valid args arrray. Calling it // without and arg will throw an exception if you have formating // chars and no args array. string comment = format; if (args.Length > 0) { comment = String.Format(format, args); } _currentLogger.Log(new CommentInfo(comment)); } /// ------------------------------------------------------------------- /// <summary></summary> /// ------------------------------------------------------------------- public static void StartTest(XmlNode xmlElementIdentifier, TestCaseAttribute testAttribute, MethodInfo methodInfo) { _currentLogger.Log(new StartTestInfo(xmlElementIdentifier, testAttribute, methodInfo)); } /// ------------------------------------------------------------------- /// <summary></summary> /// ------------------------------------------------------------------- public static void LogPass() { _currentLogger.Log(new TestResultInfo(TestResultInfo.TestResults.Passed)); } /// ------------------------------------------------------------------- /// <summary></summary> /// ------------------------------------------------------------------- public static void EndTest() { _currentLogger.Log(new TestEndInfo()); } /// --------------------------------------------------------------- /// <summary></summary> /// --------------------------------------------------------------- public static void MonitorProcess(Process process) { _currentLogger.Log(new MonitorProcessInfo(process)); } /// --------------------------------------------------------------- /// <summary>Last call to close the channel down to the logger. /// No tests should be ran after this call</summary> /// --------------------------------------------------------------- public static void CloseLog() { if (_currentLogger is IDisposable) { ((IDisposable)_currentLogger).Dispose(); } } /// --------------------------------------------------------------- /// <summary></summary> /// --------------------------------------------------------------- public static void ReportResults() { _currentLogger.Log(new ReportResultsInfo()); } /// --------------------------------------------------------------- /// <summary>The call will generate the XML log if the logger is /// XML </summary> /// --------------------------------------------------------------- public static void GenerateXMLLog(string filePath) { String logSaveLocation; if (filePath == string.Empty) { String newLog1 = Path.Combine(Directory.GetCurrentDirectory(), "UIAVerifyLogs"); //Default UIAVerifyLogs Log directory = %Desktop%\UIAVerifyLogs String logTimeStamp = String.Format("[{0:yyyy}.{0:mm}.{0:dd}]_({0:HH}.{0:mm}.{0:ss})", DateTime.Now); if (!Directory.Exists(newLog1)) Directory.CreateDirectory(newLog1); //Save file format: UserName_OSVersion_[Year.Month.Day]_(Hour.Minute.Second).xml String newLog2 = String.Format("{0}_{1}_{2}.xml", Environment.UserName, Environment.OSVersion.VersionString, logTimeStamp); logSaveLocation = Path.Combine(newLog1, newLog2); } else { if (Path.GetExtension(filePath).ToLower() == ".xml") { logSaveLocation = filePath; } else { logSaveLocation = Path.ChangeExtension(filePath, "xml"); } } XmlWriterSettings writerSettings = new XmlWriterSettings(); writerSettings.Indent = true; #if NATIVE_UIA // Add the machine configuration details as another test Microsoft.Test.UIAutomation.TestManager.TestCaseAttribute tca = new Microsoft.Test.UIAutomation.TestManager.TestCaseAttribute("Configuration", TestPriorities.Pri0, Microsoft.Test.UIAutomation.TestManager.TestStatus.Works, "Microsoft Corp.", new string[] { "This test logs Machine Configuration" }); StringBuilder pathXmlString = new StringBuilder(); using (XmlWriter xmlConfigLog = XmlTextWriter.Create(pathXmlString)) { XmlSerializer xmlSerializer = new XmlSerializer(QueryString.LogSystemInformationObject.GetType()); xmlSerializer.Serialize(xmlConfigLog, QueryString.LogSystemInformationObject); } // Now return only the InnerDocument XmlDocument doc = new XmlDocument(); doc.LoadXml(pathXmlString.ToString()); StartTest(doc.DocumentElement.FirstChild.Clone(), tca, null); LogPass(); EndTest(); #endif //lets save log file _uivLogFile = logSaveLocation; using (XmlWriter xmlLogFile = XmlTextWriter.Create(logSaveLocation, writerSettings)) { XmlLog.GetTestRunXml(xmlLogFile); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Runtime.CompilerServices; using Microsoft.Scripting; using Microsoft.Scripting.Actions; using Microsoft.Scripting.Runtime; using IronPython.Runtime.Binding; using MSAst = System.Linq.Expressions; using AstUtils = Microsoft.Scripting.Ast.Utils; namespace IronPython.Compiler.Ast { using Ast = MSAst.Expression; public class WithStatement : Statement { private int _headerIndex; private readonly Expression _contextManager; private readonly Expression _var; private Statement _body; public WithStatement(Expression contextManager, Expression var, Statement body) { _contextManager = contextManager; _var = var; _body = body; } public int HeaderIndex { set { _headerIndex = value; } } public new Expression Variable { get { return _var; } } public Expression ContextManager { get { return _contextManager; } } public Statement Body { get { return _body; } } /// <summary> /// WithStatement is translated to the DLR AST equivalent to /// the following Python code snippet (from with statement spec): /// /// mgr = (EXPR) /// exit = mgr.__exit__ # Not calling it yet /// value = mgr.__enter__() /// exc = True /// try: /// VAR = value # Only if "as VAR" is present /// BLOCK /// except: /// # The exceptional case is handled here /// exc = False /// if not exit(*sys.exc_info()): /// raise /// # The exception is swallowed if exit() returns true /// finally: /// # The normal and non-local-goto cases are handled here /// if exc: /// exit(None, None, None) /// /// </summary> public override MSAst.Expression Reduce() { // Five statements in the result... ReadOnlyCollectionBuilder<MSAst.Expression> statements = new ReadOnlyCollectionBuilder<MSAst.Expression>(6); ReadOnlyCollectionBuilder<MSAst.ParameterExpression> variables = new ReadOnlyCollectionBuilder<MSAst.ParameterExpression>(6); MSAst.ParameterExpression lineUpdated = Ast.Variable(typeof(bool), "$lineUpdated_with"); variables.Add(lineUpdated); //****************************************************************** // 1. mgr = (EXPR) //****************************************************************** MSAst.ParameterExpression manager = Ast.Variable(typeof(object), "with_manager"); variables.Add(manager); statements.Add( GlobalParent.AddDebugInfo( Ast.Assign( manager, _contextManager ), new SourceSpan(GlobalParent.IndexToLocation(StartIndex), GlobalParent.IndexToLocation(_headerIndex)) ) ); //****************************************************************** // 2. exit = mgr.__exit__ # Not calling it yet //****************************************************************** MSAst.ParameterExpression exit = Ast.Variable(typeof(object), "with_exit"); variables.Add(exit); statements.Add( MakeAssignment( exit, GlobalParent.Get( "__exit__", manager ) ) ); //****************************************************************** // 3. value = mgr.__enter__() //****************************************************************** MSAst.ParameterExpression value = Ast.Variable(typeof(object), "with_value"); variables.Add(value); statements.Add( GlobalParent.AddDebugInfoAndVoid( MakeAssignment( value, Parent.Invoke( new CallSignature(0), Parent.LocalContext, GlobalParent.Get( "__enter__", manager ) ) ), new SourceSpan(GlobalParent.IndexToLocation(StartIndex), GlobalParent.IndexToLocation(_headerIndex)) ) ); //****************************************************************** // 4. exc = True //****************************************************************** MSAst.ParameterExpression exc = Ast.Variable(typeof(bool), "with_exc"); variables.Add(exc); statements.Add( MakeAssignment( exc, AstUtils.Constant(true) ) ); //****************************************************************** // 5. The final try statement: // // try: // VAR = value # Only if "as VAR" is present // BLOCK // except: // # The exceptional case is handled here // exc = False // if not exit(*sys.exc_info()): // raise // # The exception is swallowed if exit() returns true // finally: // # The normal and non-local-goto cases are handled here // if exc: // exit(None, None, None) //****************************************************************** var previousException = Ast.Variable(typeof(Exception), "$previousException"); variables.Add(previousException); MSAst.ParameterExpression exception; statements.Add( // try: AstUtils.Try( AstUtils.Try(// try statement body PushLineUpdated(false, lineUpdated), Ast.Assign(previousException, Ast.Call(AstMethods.SaveCurrentException)), _var != null ? (MSAst.Expression)Ast.Block( // VAR = value _var.TransformSet(SourceSpan.None, value, PythonOperationKind.None), // BLOCK _body, AstUtils.Empty() ) : // BLOCK (MSAst.Expression)_body // except:, // try statement location ).Catch(exception = Ast.Variable(typeof(Exception), "exception"), // Python specific exception handling code TryStatement.GetTracebackHeader( this, exception, GlobalParent.AddDebugInfoAndVoid( Ast.Block( Ast.Call(AstMethods.SetCurrentException, Parent.LocalContext, exception), // exc = False MakeAssignment( exc, AstUtils.Constant(false) ), // if not exit(*sys.exc_info()): // raise AstUtils.IfThen( GlobalParent.Convert( typeof(bool), ConversionResultKind.ExplicitCast, GlobalParent.Operation( typeof(bool), PythonOperationKind.IsFalse, MakeExitCall(exit, exception) ) ), UpdateLineUpdated(true), Ast.Throw( Ast.Call( AstMethods.MakeRethrowExceptionWorker, exception ) ) ) ), _body.Span ) ), PopLineUpdated(lineUpdated), Ast.Empty() ) // finally: ).Finally( Ast.Call(AstMethods.RestoreCurrentException, previousException), // if exc: // exit(None, None, None) AstUtils.IfThen( exc, GlobalParent.AddDebugInfoAndVoid( Ast.Block( MSAst.DynamicExpression.Dynamic( GlobalParent.PyContext.Invoke( new CallSignature(3) // signature doesn't include function ), typeof(object), new MSAst.Expression[] { Parent.LocalContext, exit, AstUtils.Constant(null), AstUtils.Constant(null), AstUtils.Constant(null) } ), Ast.Empty() ), _contextManager.Span ) ) ) ); statements.Add(AstUtils.Empty()); return Ast.Block(variables.ToReadOnlyCollection(), statements.ToReadOnlyCollection()); } private MSAst.Expression MakeExitCall(MSAst.ParameterExpression exit, MSAst.Expression exception) { // The 'with' statement's exceptional clause explicitly does not set the thread's current exception information. // So while the pseudo code says: // exit(*sys.exc_info()) // we'll actually do: // exit(*PythonOps.GetExceptionInfoLocal($exception)) return GlobalParent.Convert( typeof(bool), ConversionResultKind.ExplicitCast, Parent.Invoke( new CallSignature(ArgumentType.List), Parent.LocalContext, exit, Ast.Call( AstMethods.GetExceptionInfoLocal, Parent.LocalContext, exception ) ) ); } public override void Walk(PythonWalker walker) { if (walker.Walk(this)) { _contextManager?.Walk(walker); _var?.Walk(walker); _body?.Walk(walker); } walker.PostWalk(this); } } }
/* * Copyright (c) InWorldz Halcyon Developers * Copyright (c) Contributors, http://opensimulator.org/ * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSim Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Reflection; using System.Text.RegularExpressions; using DotNetOpenMail; using DotNetOpenMail.SmtpAuth; using log4net; using Nini.Config; using OpenMetaverse; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Data.SimpleDB; namespace OpenSim.Region.CoreModules.Scripting.EmailModules { public class GetEmailModule : IGetEmailModule { // // Log // private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); // // Module vars // private IConfigSource m_Config; private int m_MaxQueueSize = 50; // maximum size of an object mail queue private Dictionary<UUID, List<Email>> m_MailQueues = new Dictionary<UUID, List<Email>>(); private Dictionary<UUID, DateTime> m_LastGetEmailCall = new Dictionary<UUID, DateTime>(); private TimeSpan m_QueueTimeout = new TimeSpan(2, 0, 0); // 2 hours without llGetNextEmail drops the queue // Database support private ConnectionFactory _connectionFactory; private string _connectString = String.Empty; private static long mTicksToEpoch = new DateTime(1970, 1, 1).Ticks; // Scenes by Region Handle private Dictionary<ulong, Scene> m_Scenes = new Dictionary<ulong, Scene>(); private bool m_Enabled = false; public void InsertEmail(UUID to, Email email) { // It's tempting to create the queue here. Don't; objects which have // not yet called GetNextEmail should have no queue, and emails to them // should be silently dropped. lock (m_MailQueues) { if (m_MailQueues.ContainsKey(to)) { if (m_MailQueues[to].Count >= m_MaxQueueSize) { // fail silently return; } lock (m_MailQueues[to]) { m_MailQueues[to].Add(email); } } } } public void Initialize(Scene scene, IConfigSource config) { m_Config = config; IConfig SMTPConfig; //FIXME: RegionName is correct?? //m_RegionName = scene.RegionInfo.RegionName; IConfig startupConfig = m_Config.Configs["Startup"]; m_Enabled = (startupConfig.GetString("getemailmodule", "DefaultGetEmailModule") == "DefaultGetEmailModule"); //Load SMTP SERVER config try { if ((SMTPConfig = m_Config.Configs["SMTP"]) == null) { m_log.ErrorFormat("[InboundEmail]: SMTP not configured"); m_Enabled = false; return; } if (!SMTPConfig.GetBoolean("inbound", true)) { m_log.WarnFormat("[InboundEmail]: Inbound email module disabled in configuration"); m_Enabled = false; return; } // Database support _connectString = SMTPConfig.GetString("inbound_storage_connection", String.Empty); if (String.IsNullOrEmpty(_connectString)) { m_log.ErrorFormat("[InboundEmail]: Could not find SMTP inbound_storage_connection."); m_Enabled = false; return; } _connectionFactory = new ConnectionFactory("MySQL", _connectString); if (_connectionFactory == null) { m_log.ErrorFormat("[InboundEmail]: Inbound email module could not create MySQL connection."); m_Enabled = false; return; } } catch (Exception e) { m_log.Error("[InboundEmail]: Inbound email not configured: " + e.Message); m_log.Error(e.StackTrace); m_Enabled = false; return; } // It's a go! if (m_Enabled) { lock (m_Scenes) { // Claim the interface slot scene.RegisterModuleInterface<IGetEmailModule>(this); // Add to scene list if (m_Scenes.ContainsKey(scene.RegionInfo.RegionHandle)) { m_Scenes[scene.RegionInfo.RegionHandle] = scene; } else { m_Scenes.Add(scene.RegionInfo.RegionHandle, scene); } } m_log.Info("[InboundEmail]: Activated inbound email."); } } public void PostInitialize() { } public void Close() { } public string Name { get { return "DefaultGetEmailModule"; } } public bool IsSharedModule { get { return true; } } /// <summary> /// Delay function using thread in seconds /// </summary> /// <param name="seconds"></param> private void DelayInSeconds(int delay) { delay = (int)((float)delay * 1000); if (delay == 0) return; System.Threading.Thread.Sleep(delay); } public static uint DateTime2UnixTime(DateTime when) { long elapsed = DateTime.Now.Ticks - mTicksToEpoch; return Convert.ToUInt32(elapsed / 10000000); } public static DateTime UnixTime2DateTime(uint when) { return new DateTime(mTicksToEpoch + when); } private bool IsLocal(UUID objectID) { UUID unused; return (null != findPrim(objectID, out unused)); } private SceneObjectPart findPrim(UUID objectID, out UUID regionUUID) { lock (m_Scenes) { foreach (Scene s in m_Scenes.Values) { SceneObjectPart part = s.GetSceneObjectPart(objectID); if (part != null) { regionUUID = s.RegionInfo.RegionID; return part; } } } regionUUID = UUID.Zero; return null; } private void UpdateRegistration(ISimpleDB db, UUID uuid, UUID regionUUID) { string sql = "INSERT INTO emailregistrations (`uuid`, `time`, `region`) VALUES (?uuid, ?time, ?region)"; sql += " ON DUPLICATE KEY UPDATE `time`=?time"; Dictionary<string, object> parameters = new Dictionary<string, object>(); parameters["?uuid"] = uuid.ToString(); parameters["?region"] = regionUUID.ToString(); parameters["?time"] = DateTime2UnixTime(DateTime.UtcNow); // All storage dates are UTC try { db.QueryNoResults(sql, parameters); } catch (Exception e) { m_log.Error("[InboundEmail]: Exception during database call to store message: "+e.Message); m_log.Error(e.StackTrace); } } private void DeleteMessage(ISimpleDB db, uint ID) { string sql = "DELETE FROM emailmessages WHERE `ID`=?id"; Dictionary<string, object> parameters = new Dictionary<string, object>(); parameters["?ID"] = ID.ToString(); try { db.QueryNoResults(sql, parameters); } catch (Exception e) { m_log.Error("[InboundEmail]: Exception during database call to delete delivered message: " + e.Message); m_log.Error(e.StackTrace); } } private uint QueryEmailCount(ISimpleDB db, UUID uuid) { try { string query = "SELECT COUNT(*) FROM emailmessages WHERE uuid = ?uuid"; Dictionary<string, object> parms = new Dictionary<string, object>(); parms.Add("?uuid", uuid); List<Dictionary<string, string>> results = db.QueryWithResults(query, parms); if (results.Count != 1) return 0; return Convert.ToUInt32(results[0]["COUNT(*)"]); } catch (Exception e) { m_log.Error("[InboundEmail]: Exception during database call to count messages: " + e.Message); m_log.Error(e.StackTrace); return 0; } } private Email QueryNextEmail(ISimpleDB db, UUID uuid, string sender, string subject) { Email msg = new Email(); try { Dictionary<string, object> parms = new Dictionary<string, object>(); string query = "SELECT * FROM emailmessages WHERE uuid = ?uuid"; parms.Add("?uuid", uuid); if (!String.IsNullOrEmpty(sender)) { query += " AND from = ?from"; parms.Add("?from", sender); } if (!String.IsNullOrEmpty(subject)) { query += " AND subject = ?subject"; parms.Add("?subject", subject); } query += " ORDER BY sent LIMIT 1"; List<Dictionary<string, string>> results = db.QueryWithResults(query, parms); if (results.Count != 1) return null; uint ID = Convert.ToUInt32(results[0]["ID"]); uint unixtime = Convert.ToUInt32(results[0]["sent"]); msg.time = unixtime.ToString(); // Note: email event is documented as string form of *UTC* unix time msg.sender = results[0]["from"]; msg.subject = results[0]["subject"]; msg.message = results[0]["body"]; // This one has been handled, remove it from those queued in the DB. DeleteMessage(db, ID); } catch (Exception e) { m_log.Error("[InboundEmail]: Exception during database call to store message: " + e.Message); m_log.Error(e.StackTrace); return null; } msg.numLeft = (int)QueryEmailCount(db, uuid); return msg; } /// <summary> /// /// </summary> /// <param name="objectID"></param> /// <param name="sender"></param> /// <param name="subject"></param> /// <returns></returns> public Email GetNextEmail(UUID objectID, string sender, string subject) { try { using (ISimpleDB db = _connectionFactory.GetConnection()) { UUID regionUUID; SceneObjectPart part = findPrim(objectID, out regionUUID); if (part != null) { UpdateRegistration(db, objectID, regionUUID); return QueryNextEmail(db, objectID, sender, subject); } } } catch (Exception e) { m_log.Error("[InboundEmail]: Exception during database call to check messages: " + e.Message); m_log.Error(e.StackTrace); } m_log.Error("[InboundEmail]: Next email not available. Part " + objectID.ToString() + " not found."); return null; } } }
// // MonoTests.System.Xml.XsdValidatingReaderTests.cs // // Author: // Atsushi Enomoto <[email protected]> // // (C)2003 Atsushi Enomoto // (C)2005-2007 Novell, Inc. // using System; using System.IO; using System.Net; using System.Xml; using System.Xml.Schema; using NUnit.Framework; namespace MonoTests.System.Xml { [TestFixture] public class XsdValidatingReaderTests { public XsdValidatingReaderTests () { } XmlReader xtr; XmlValidatingReader xvr; private XmlValidatingReader PrepareXmlReader (string xml) { XmlReader reader = new XmlTextReader (xml, XmlNodeType.Document, null); // XmlDocument doc = new XmlDocument (); // doc.LoadXml (xml); // XmlReader reader = new XmlNodeReader (doc); return new XmlValidatingReader (reader); } [Test] public void TestEmptySchema () { string xml = "<root/>"; xvr = PrepareXmlReader (xml); xvr.ValidationType = ValidationType.Schema; xvr.Read (); // Is is missing schema component. } [Test] public void TestSimpleValidation () { string xml = "<root/>"; xvr = PrepareXmlReader (xml); Assert.AreEqual (ValidationType.Auto, xvr.ValidationType); XmlSchema schema = new XmlSchema (); XmlSchemaElement elem = new XmlSchemaElement (); elem.Name = "root"; schema.Items.Add (elem); xvr.Schemas.Add (schema); xvr.Read (); // root Assert.AreEqual (ValidationType.Auto, xvr.ValidationType); xvr.Read (); // EOF xml = "<hoge/>"; xvr = PrepareXmlReader (xml); xvr.Schemas.Add (schema); try { xvr.Read (); Assert.Fail ("element mismatch is incorrectly allowed"); } catch (XmlSchemaException) { } xml = "<hoge xmlns='urn:foo' />"; xvr = PrepareXmlReader (xml); xvr.Schemas.Add (schema); try { xvr.Read (); Assert.Fail ("Element in different namespace is incorrectly allowed."); } catch (XmlSchemaException) { } } [Test] public void TestReadTypedValueSimple () { string xml = "<root>12</root>"; XmlSchema schema = new XmlSchema (); XmlSchemaElement elem = new XmlSchemaElement (); elem.Name = "root"; elem.SchemaTypeName = new XmlQualifiedName ("integer", XmlSchema.Namespace); schema.Items.Add (elem); // Lap 1: xvr = PrepareXmlReader (xml); xvr.Schemas.Add (schema); // Read directly from root. object o = xvr.ReadTypedValue (); Assert.AreEqual (ReadState.Initial, xvr.ReadState); Assert.IsNull (o); xvr.Read (); // element root Assert.AreEqual (XmlNodeType.Element, xvr.NodeType); Assert.IsNotNull (xvr.SchemaType); Assert.IsTrue (xvr.SchemaType is XmlSchemaDatatype); o = xvr.ReadTypedValue (); // read "12" Assert.AreEqual (XmlNodeType.EndElement, xvr.NodeType); Assert.IsNotNull (o); Assert.AreEqual (typeof (decimal), o.GetType ()); decimal n = (decimal) o; Assert.AreEqual (12, n); Assert.IsTrue (!xvr.EOF); Assert.AreEqual ("root", xvr.Name); Assert.IsNull (xvr.SchemaType); // EndElement's type // Lap 2: xvr = PrepareXmlReader (xml); xvr.Schemas.Add (schema); xvr.Read (); // root XmlSchemaDatatype dt = xvr.SchemaType as XmlSchemaDatatype; Assert.IsNotNull (dt); Assert.AreEqual (typeof (decimal), dt.ValueType); Assert.AreEqual (XmlTokenizedType.None, dt.TokenizedType); xvr.Read (); // text "12" Assert.IsNull (xvr.SchemaType); o = xvr.ReadTypedValue (); // ReadTypedValue is different from ReadString(). Assert.IsNull (o); } [Test] [Ignore ("XML Schema validator should not be available for validating non namespace-aware XmlReader that handled colon as a name character")] public void TestNamespacesFalse () { // This tests if Namespaces=false is specified, then // the reader's NamespaceURI should be always string.Empty and // validation should be done against such schema that has target ns as "". string xml = "<x:root xmlns:x='urn:foo' />"; xvr = PrepareXmlReader (xml); xvr.Namespaces = false; Assert.AreEqual (ValidationType.Auto, xvr.ValidationType); XmlSchema schema = new XmlSchema (); schema.TargetNamespace = "urn:foo"; XmlSchemaElement elem = new XmlSchemaElement (); elem.Name = "root"; schema.Items.Add (elem); xvr.Schemas.Add (schema); xvr.Read (); // root Assert.IsTrue (!xvr.Namespaces); Assert.AreEqual ("x:root", xvr.Name); // LocalName may contain colons. Assert.AreEqual ("x:root", xvr.LocalName); // NamespaceURI is not supplied. Assert.AreEqual ("", xvr.NamespaceURI); } [Test] public void TestReadTypedAttributeValue () { string xml = "<root attr='12'></root>"; XmlSchema schema = new XmlSchema (); XmlSchemaElement elem = new XmlSchemaElement (); elem.Name = "root"; XmlSchemaComplexType ct = new XmlSchemaComplexType (); XmlSchemaAttribute attr = new XmlSchemaAttribute (); attr.Name = "attr"; attr.SchemaTypeName = new XmlQualifiedName ("int", XmlSchema.Namespace); ct.Attributes.Add (attr); elem.SchemaType = ct; schema.Items.Add (elem); xvr = PrepareXmlReader (xml); xvr.Schemas.Add (schema); xvr.Read (); Assert.AreEqual ("root", xvr.Name); Assert.IsTrue (xvr.MoveToNextAttribute ()); // attr Assert.AreEqual ("attr", xvr.Name); XmlSchemaDatatype dt = xvr.SchemaType as XmlSchemaDatatype; Assert.IsNotNull (dt); Assert.AreEqual (typeof (int), dt.ValueType); Assert.AreEqual (XmlTokenizedType.None, dt.TokenizedType); object o = xvr.ReadTypedValue (); Assert.AreEqual (XmlNodeType.Attribute, xvr.NodeType); Assert.AreEqual (typeof (int), o.GetType ()); int n = (int) o; Assert.AreEqual (12, n); Assert.IsTrue (xvr.ReadAttributeValue ()); // can read = seems not proceed. } [Test] public void DuplicateSchemaAssignment () { string xml = @"<data xmlns='http://www.test.com/schemas/' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xsi:schemaLocation='http://www.test.com/schemas/ /home/user/schema.xsd' />"; string xsd = @"<xs:schema targetNamespace='http://www.test.com/schemas/' xmlns:xs='http://www.w3.org/2001/XMLSchema' xmlns='http://www.test.com/schemas/' > <xs:element name='data' /></xs:schema>"; string xmlns = "http://www.test.com/schemas/"; XmlValidatingReader xvr = new XmlValidatingReader ( xml, XmlNodeType.Document, null); XmlSchemaCollection schemas = new XmlSchemaCollection (); schemas.Add (XmlSchema.Read (new XmlTextReader ( xsd, XmlNodeType.Document, null), null)); xvr.Schemas.Add (schemas); while (!xvr.EOF) xvr.Read (); } [Test] // bug #76234 public void DTDValidatorNamespaceHandling () { string xml = "<xml xmlns='urn:a'> <foo> <a:bar xmlns='urn:b' xmlns:a='urn:a' /> <bug /> </foo> </xml>"; XmlValidatingReader vr = new XmlValidatingReader ( xml, XmlNodeType.Document, null); vr.Read (); vr.Read (); // whitespace Assert.AreEqual (String.Empty, vr.NamespaceURI, "#1"); vr.Read (); // foo Assert.AreEqual ("urn:a", vr.NamespaceURI, "#2"); vr.Read (); // whitespace vr.Read (); // a:bar Assert.AreEqual ("urn:a", vr.NamespaceURI, "#3"); vr.Read (); // whitespace vr.Read (); // bug Assert.AreEqual ("urn:a", vr.NamespaceURI, "#4"); } [Test] public void MultipleSchemaInSchemaLocation () { XmlTextReader xtr = new XmlTextReader ("Test/XmlFiles/xsd/multi-schemaLocation.xml"); XmlValidatingReader vr = new XmlValidatingReader (xtr); while (!vr.EOF) vr.Read (); } [Test] public void ReadTypedValueSimpleTypeRestriction () { string xml = "<root>xx</root><!-- after -->"; string xsd = @" <xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema'> <xs:element name='root'> <xs:simpleType> <xs:restriction base='xs:string'> <xs:minLength value='2' /> </xs:restriction> </xs:simpleType> </xs:element> </xs:schema>"; XmlTextReader xir = new XmlTextReader (xml, XmlNodeType.Document, null); XmlTextReader xsr = new XmlTextReader (xsd, XmlNodeType.Document, null); XmlValidatingReader vr = new XmlValidatingReader (xir); vr.Schemas.Add (XmlSchema.Read (xsr, null)); vr.Read (); // root Assert.AreEqual ("xx", vr.ReadTypedValue ()); Assert.AreEqual (XmlNodeType.EndElement, vr.NodeType); } // If we normalize string before validating with facets, // this test will fail. It will also fail if ReadTypedValue() // ignores whitespace nodes. [Test] public void ReadTypedValueWhitespaces () { string xml = "<root> </root><!-- after -->"; string xsd = @" <xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema'> <xs:element name='root'> <xs:simpleType> <xs:restriction base='xs:string'> <xs:minLength value='2' /> </xs:restriction> </xs:simpleType> </xs:element> </xs:schema>"; XmlTextReader xir = new XmlTextReader (xml, XmlNodeType.Document, null); XmlTextReader xsr = new XmlTextReader (xsd, XmlNodeType.Document, null); XmlValidatingReader vr = new XmlValidatingReader (xir); vr.Schemas.Add (XmlSchema.Read (xsr, null)); vr.Read (); // root Assert.AreEqual (" ", vr.ReadTypedValue ()); Assert.AreEqual (XmlNodeType.EndElement, vr.NodeType); } [Test] // bug #77241 public void EmptyContentAllowWhitespace () { string doc = @" <root> <!-- some comment --> <child/> </root> "; string schema = @" <xsd:schema xmlns:xsd=""http://www.w3.org/2001/XMLSchema""> <xsd:element name=""root""> <xsd:complexType> <xsd:sequence> <xsd:element name=""child"" type=""xsd:string"" /> </xsd:sequence> </xsd:complexType> </xsd:element> </xsd:schema> "; XmlValidatingReader reader = new XmlValidatingReader ( new XmlTextReader (new StringReader (doc))); reader.Schemas.Add (null, new XmlTextReader (new StringReader (schema))); while (reader.Read ()) ; } [Test] // bug #79650 #if NET_2_0 // annoyance [ExpectedException (typeof (XmlSchemaValidationException))] #else [ExpectedException (typeof (XmlSchemaException))] #endif public void EnumerationFacetOnAttribute () { string xml = "<test mode='NOT A ENUMERATION VALUE' />"; XmlSchema schema = XmlSchema.Read (new XmlTextReader ("Test/XmlFiles/xsd/79650.xsd"), null); XmlValidatingReader xvr = new XmlValidatingReader (xml, XmlNodeType.Document, null); xvr.ValidationType = ValidationType.Schema; xvr.Schemas.Add (schema); while (!xvr.EOF) xvr.Read (); } class XmlErrorResolver : XmlResolver { public override ICredentials Credentials { set { } } public override object GetEntity (Uri uri, string role, Type type) { throw new Exception (); } } [Test] // bug #79924 public void ValidationTypeNoneIgnoreSchemaLocations () { string xml = "<project xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xsi:noNamespaceSchemaLocation='nosuchschema.xsd'/>"; XmlValidatingReader vr = new XmlValidatingReader ( new XmlTextReader (new StringReader (xml))); vr.ValidationType = ValidationType.None; vr.XmlResolver = new XmlErrorResolver (); while (!vr.EOF) vr.Read (); } [Test] // bug #336625 public void ValidationTypeNoneIgnoreLocatedSchemaErrors () { string xml = "<test xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xsi:noNamespaceSchemaLocation='Test/XmlFiles/xsd/336625.xsd'/>"; XmlValidatingReader vr = new XmlValidatingReader ( new XmlTextReader (new StringReader (xml))); vr.ValidationType = ValidationType.None; while (!vr.EOF) vr.Read (); } [Test] public void Bug81360 () { string schemaFile = "Test/XmlFiles/xsd/81360.xsd"; XmlTextReader treader = new XmlTextReader (schemaFile); XmlSchema sc = XmlSchema.Read (treader, null); sc.Compile (null); string xml = @"<body xmlns='" + sc.TargetNamespace + "'><div></div></body>"; XmlTextReader reader = new XmlTextReader (new StringReader (xml)); XmlValidatingReader validator = new XmlValidatingReader (reader); validator.Schemas.Add (sc); validator.ValidationType = ValidationType.Schema; while (!validator.EOF) validator.Read (); } #if NET_2_0 [Test] public void Bug81460 () { string xsd = "<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema'><xs:element name='foo'><xs:complexType><xs:attribute name='a' default='x' /></xs:complexType></xs:element></xs:schema>"; string xml = "<foo/>"; XmlReaderSettings s = new XmlReaderSettings (); s.ValidationType = ValidationType.Schema; s.Schemas.Add (XmlSchema.Read (new StringReader (xsd), null)); XmlReader r = XmlReader.Create (new StringReader (xml), s); r.Read (); r.MoveToFirstAttribute (); // default attribute Assert.AreEqual (String.Empty, r.Prefix); } #endif [Test] #if NET_2_0 // annoyance [ExpectedException (typeof (XmlSchemaValidationException))] #else [ExpectedException (typeof (XmlSchemaException))] #endif public void Bug82099 () { string xsd = @" <xsd:schema xmlns:xsd='http://www.w3.org/2001/XMLSchema'> <xsd:element name='Customer' type='CustomerType' /> <xsd:complexType name='CustomerType'> <xsd:attribute name='name' type='xsd:string' /> </xsd:complexType> </xsd:schema>"; XmlSchema schema = XmlSchema.Read (new StringReader (xsd), null); string xml = "<Customer name='Bob'> </Customer>"; #if NET_2_0 XmlReaderSettings settings = new XmlReaderSettings (); settings.Schemas.Add (schema); settings.ValidationType = ValidationType.Schema; XmlReader reader = XmlReader.Create (new StringReader (xml), settings); #else XmlValidatingReader reader = new XmlValidatingReader (xml, XmlNodeType.Document, null); reader.Schemas.Add (schema); reader.ValidationType = ValidationType.Schema; #endif reader.Read (); reader.Read (); reader.Read (); } [Test] public void Bug82010 () { string xmlfile = "Test/XmlFiles/xsd/82010.xml"; string xsdfile = "Test/XmlFiles/xsd/82010.xsd"; XmlTextReader xr = null, xr2 = null; try { xr = new XmlTextReader (xsdfile); xr2 = new XmlTextReader (xmlfile); XmlValidatingReader xvr = new XmlValidatingReader (xr2); xvr.Schemas.Add (XmlSchema.Read (xr, null)); while (!xvr.EOF) xvr.Read (); } finally { if (xr2 != null) xr2.Close (); if (xr != null) xr.Close (); } } [Test] public void Bug376395 () { string xmlfile = "Test/XmlFiles/xsd/376395.xml"; string xsdfile = "Test/XmlFiles/xsd/376395.xsd"; XmlTextReader xr = null, xr2 = null; try { xr = new XmlTextReader (xsdfile); xr2 = new XmlTextReader (xmlfile); XmlValidatingReader xvr = new XmlValidatingReader (xr2); xvr.Schemas.Add (XmlSchema.Read (xr, null)); while (!xvr.EOF) xvr.Read (); } finally { if (xr2 != null) xr2.Close (); if (xr != null) xr.Close (); } } [Test] public void ValidateMixedInsideXsdAny () { string xml = @"<root xmlns='urn:foo'> <X><Z>text</Z></X> <Y><X><Z>text</Z></X></Y> </root>"; string xsd = @" <xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema' targetNamespace='urn:foo' xmlns='urn:foo'> <xs:complexType name='root-type'> <xs:sequence><xs:element ref='X' /><xs:element ref='Y' /></xs:sequence> </xs:complexType> <xs:complexType name='X-type'> <xs:choice minOccurs='1' maxOccurs='unbounded'> <xs:any processContents='skip'/> </xs:choice> </xs:complexType> <xs:complexType name='Y-type'> <xs:sequence><xs:element ref='X' /></xs:sequence> </xs:complexType> <xs:element name='root' type='root-type' /> <xs:element name='X' type='X-type' /> <xs:element name='Y' type='Y-type' /> </xs:schema>"; XmlTextReader xtr = new XmlTextReader (new StringReader (xml)); XmlValidatingReader xvr = new XmlValidatingReader (xtr); XmlReader xsr = new XmlTextReader (new StringReader (xsd)); xvr.Schemas.Add (XmlSchema.Read (xsr, null)); while (!xvr.EOF) xvr.Read (); #if NET_2_0 xtr = new XmlTextReader (new StringReader (xml)); xsr = new XmlTextReader (new StringReader (xsd)); var s = new XmlReaderSettings (); s.Schemas.Add (XmlSchema.Read (xsr, null)); s.ValidationType = ValidationType.Schema; XmlReader xvr2 = XmlReader.Create (xtr, s); while (!xvr2.EOF) xvr2.Read (); #endif } #if NET_2_0 [Test] public void WhitespaceAndElementOnly () { string xsd = @"<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema'> <xs:element name='element_list'> <xs:complexType> <xs:sequence> <xs:element name='element' maxOccurs='unbounded' /> </xs:sequence> </xs:complexType> </xs:element> </xs:schema>"; string xml = @"<element_list> <!-- blah blah blah --> <element /> <!-- blah blah --> <element /> </element_list>"; RunValidation (xml, xsd); } [Test] [ExpectedException (typeof (XmlSchemaValidationException))] public void EnumerationFacet () { // bug #339934 string xsd = @"<xs:schema id='schema' xmlns:xs='http://www.w3.org/2001/XMLSchema'> <xs:simpleType name='ModeType'> <xs:restriction base='xs:string'> <xs:enumeration value='on' /> <xs:enumeration value='off' /> </xs:restriction> </xs:simpleType> <xs:element name='test'> <xs:complexType> <xs:sequence/> <xs:attribute name='mode' type='ModeType' use='required' /> </xs:complexType> </xs:element> </xs:schema>"; string xml = @"<test mode='out of scope'></test>"; RunValidation (xml, xsd); } [Test] public void Bug501763 () { string xsd1 = @" <xs:schema id='foo1' targetNamespace='foo1' elementFormDefault='qualified' xmlns='foo1' xmlns:xs='http://www.w3.org/2001/XMLSchema' xmlns:f2='foo2'> <xs:import namespace='foo2' /> <xs:element name='Foo1Element' type='f2:Foo2ExtendedType'/> </xs:schema>"; string xsd2 = @" <xs:schema id='foo2' targetNamespace='foo2' elementFormDefault='qualified' xmlns='foo2' xmlns:xs='http://www.w3.org/2001/XMLSchema' > <xs:element name='Foo2Element' type='Foo2Type' /> <xs:complexType name='Foo2Type'> <xs:attribute name='foo2Attr' type='xs:string' use='required'/> </xs:complexType> <xs:complexType name='Foo2ExtendedType'> <xs:complexContent> <xs:extension base='Foo2Type'> <xs:attribute name='foo2ExtAttr' type='xs:string' use='required'/> </xs:extension> </xs:complexContent> </xs:complexType> </xs:schema>"; XmlDocument doc = new XmlDocument (); XmlSchema schema1 = XmlSchema.Read (XmlReader.Create (new StringReader (xsd1)), null); XmlSchema schema2 = XmlSchema.Read (XmlReader.Create (new StringReader (xsd2)), null); doc.LoadXml (@" <Foo2Element foo2Attr='dummyvalue1' xmlns='foo2' />"); doc.Schemas.Add (schema2); doc.Validate (null); doc = new XmlDocument(); doc.LoadXml(@" <Foo1Element foo2Attr='dummyvalue1' foo2ExtAttr='dummyvalue2' xmlns='foo1' />"); doc.Schemas.Add (schema2); doc.Schemas.Add (schema1); doc.Validate (null); } void RunValidation (string xml, string xsd) { XmlReaderSettings s = new XmlReaderSettings (); s.ValidationType = ValidationType.Schema; s.Schemas.Add (XmlSchema.Read (XmlReader.Create (new StringReader (xsd)), null)); XmlReader r = XmlReader.Create (new StringReader (xml), s); while (!r.EOF) r.Read (); } #endif } }
using System; using System.Collections.Generic; using System.Data; using System.Data.Common; using System.Linq; namespace LinqToDB.DataProvider.DB2 { using Common; using Data; using SchemaProvider; class DB2LUWSchemaProvider : SchemaProviderBase { protected override List<DataTypeInfo> GetDataTypes(DataConnection dataConnection) { DataTypesSchema = ((DbConnection)dataConnection.Connection).GetSchema("DataTypes"); return DataTypesSchema.AsEnumerable() .Select(t => new DataTypeInfo { TypeName = t.Field<string>("SQL_TYPE_NAME"), DataType = t.Field<string>("FRAMEWORK_TYPE"), CreateParameters = t.Field<string>("CREATE_PARAMS"), }) .Union( new[] { new DataTypeInfo { TypeName = "CHARACTER", CreateParameters = "LENGTH", DataType = "System.String" } }) .ToList(); } protected string CurrenSchema; protected override List<TableInfo> GetTables(DataConnection dataConnection) { CurrenSchema = dataConnection.Execute<string>("select current_schema from sysibm.sysdummy1"); var tables = ((DbConnection)dataConnection.Connection).GetSchema("Tables"); return ( from t in tables.AsEnumerable() where new[] { "TABLE", "VIEW" }.Contains(t.Field<string>("TABLE_TYPE")) let catalog = dataConnection.Connection.Database let schema = t.Field<string>("TABLE_SCHEMA") let name = t.Field<string>("TABLE_NAME") where IncludedSchemas.Length != 0 || ExcludedSchemas.Length != 0 || schema == CurrenSchema select new TableInfo { TableID = catalog + '.' + schema + '.' + name, CatalogName = catalog, SchemaName = schema, TableName = name, IsDefaultSchema = schema.IsNullOrEmpty(), IsView = t.Field<string>("TABLE_TYPE") == "VIEW", Description = t.Field<string>("REMARKS"), } ).ToList(); } protected override List<PrimaryKeyInfo> GetPrimaryKeys(DataConnection dataConnection) { return ( from pk in dataConnection.Query( rd => new { id = dataConnection.Connection.Database + "." + rd.ToString(0) + "." + rd.ToString(1), name = rd.ToString(2), cols = rd.ToString(3).Split('+').Skip(1).ToArray(), },@" SELECT TABSCHEMA, TABNAME, INDNAME, COLNAMES FROM SYSCAT.INDEXES WHERE UNIQUERULE = 'P' AND " + GetSchemaFilter("TABSCHEMA")) from col in pk.cols.Select((c,i) => new { c, i }) select new PrimaryKeyInfo { TableID = pk.id, PrimaryKeyName = pk.name, ColumnName = col.c, Ordinal = col.i } ).ToList(); } List<ColumnInfo> _columns; protected override List<ColumnInfo> GetColumns(DataConnection dataConnection) { var sql = @" SELECT TABSCHEMA, TABNAME, COLNAME, LENGTH, SCALE, NULLS, IDENTITY, COLNO, TYPENAME, REMARKS, CODEPAGE FROM SYSCAT.COLUMNS WHERE " + GetSchemaFilter("TABSCHEMA"); return _columns = dataConnection.Query(rd => { var typeName = rd.ToString(8); var cp = Converter.ChangeTypeTo<int>(rd[10]); if (typeName == "CHARACTER" && cp == 0) typeName = "CHAR () FOR BIT DATA"; else if (typeName == "VARCHAR" && cp == 0) typeName = "VARCHAR () FOR BIT DATA"; var ci = new ColumnInfo { TableID = dataConnection.Connection.Database + "." + rd.GetString(0) + "." + rd.GetString(1), Name = rd.ToString(2), IsNullable = rd.ToString(5) == "Y", IsIdentity = rd.ToString(6) == "Y", Ordinal = Converter.ChangeTypeTo<int>(rd[7]), DataType = typeName, Description = rd.ToString(9), }; SetColumnParameters(ci, Converter.ChangeTypeTo<long?>(rd[3]), Converter.ChangeTypeTo<int?> (rd[4])); return ci; }, sql).ToList(); } static void SetColumnParameters(ColumnInfo ci, long? size, int? scale) { switch (ci.DataType) { case "DECIMAL" : case "DECFLOAT" : if ((size ?? 0) > 0) ci.Precision = (int?)size.Value; if ((scale ?? 0) > 0) ci.Scale = scale; break; case "DBCLOB" : case "CLOB" : case "BLOB" : case "LONG VARGRAPHIC" : case "VARGRAPHIC" : case "GRAPHIC" : case "LONG VARCHAR FOR BIT DATA" : case "VARCHAR () FOR BIT DATA" : case "VARBIN" : case "BINARY" : case "CHAR () FOR BIT DATA" : case "LONG VARCHAR" : case "CHARACTER" : case "CHAR" : case "VARCHAR" : ci.Length = size; break; } } protected override List<ForeingKeyInfo> GetForeignKeys(DataConnection dataConnection) { return dataConnection .Query(rd => new { name = rd.ToString(0), thisTable = dataConnection.Connection.Database + "." + rd.ToString(1) + "." + rd.ToString(2), thisColumns = rd.ToString(3), otherTable = dataConnection.Connection.Database + "." + rd.ToString(4) + "." + rd.ToString(5), otherColumns = rd.ToString(6), },@" SELECT CONSTNAME, TABSCHEMA, TABNAME, FK_COLNAMES, REFTABSCHEMA, REFTABNAME, PK_COLNAMES FROM SYSCAT.REFERENCES WHERE " + GetSchemaFilter("TABSCHEMA")) .SelectMany(fk => { var thisTable = _columns.Where(c => c.TableID == fk.thisTable). OrderByDescending(c => c.Length).ToList(); var otherTable = _columns.Where(c => c.TableID == fk.otherTable).OrderByDescending(c => c.Length).ToList(); var thisColumns = fk.thisColumns. Trim(); var otherColumns = fk.otherColumns.Trim(); var list = new List<ForeingKeyInfo>(); for (var i = 0; thisColumns.Length > 0; i++) { var thisColumn = thisTable. First(c => thisColumns. StartsWith(c.Name)); var otherColumn = otherTable.First(c => otherColumns.StartsWith(c.Name)); list.Add(new ForeingKeyInfo { Name = fk.name, ThisTableID = fk.thisTable, OtherTableID = fk.otherTable, Ordinal = i, ThisColumn = thisColumn. Name, OtherColumn = otherColumn.Name, }); thisColumns = thisColumns. Substring(thisColumn. Name.Length).Trim(); otherColumns = otherColumns.Substring(otherColumn.Name.Length).Trim(); } return list; }) .ToList(); } protected override string GetDbType(string columnType, DataTypeInfo dataType, long? length, int? prec, int? scale) { var type = DataTypes.FirstOrDefault(dt => dt.TypeName == columnType); if (type != null) { if (type.CreateParameters == null) length = prec = scale = 0; else { if (type.CreateParameters == "LENGTH") prec = scale = 0; else length = 0; if (type.CreateFormat == null) { if (type.TypeName.IndexOf("()") >= 0) { type.CreateFormat = type.TypeName.Replace("()", "({0})"); } else { var format = string.Join(",", type.CreateParameters .Split(',') .Select((p,i) => "{" + i + "}") .ToArray()); type.CreateFormat = type.TypeName + "(" + format + ")"; } } } } return base.GetDbType(columnType, dataType, length, prec, scale); } protected override DataType GetDataType(string dataType, string columnType, long? length, int? prec, int? scale) { switch (dataType) { case "XML" : return DataType.Xml; // Xml System.String case "DECFLOAT" : return DataType.Decimal; // DecimalFloat System.Decimal case "DBCLOB" : return DataType.Text; // DbClob System.String case "CLOB" : return DataType.Text; // Clob System.String case "BLOB" : return DataType.Blob; // Blob System.Byte[] case "LONG VARGRAPHIC" : return DataType.Text; // LongVarGraphic System.String case "VARGRAPHIC" : return DataType.Text; // VarGraphic System.String case "GRAPHIC" : return DataType.Text; // Graphic System.String case "BIGINT" : return DataType.Int64; // BigInt System.Int64 case "LONG VARCHAR FOR BIT DATA" : return DataType.VarBinary; // LongVarBinary System.Byte[] case "VARCHAR () FOR BIT DATA" : return DataType.VarBinary; // VarBinary System.Byte[] case "VARBIN" : return DataType.VarBinary; // VarBinary System.Byte[] case "BINARY" : return DataType.Binary; // Binary System.Byte[] case "CHAR () FOR BIT DATA" : return DataType.Binary; // Binary System.Byte[] case "LONG VARCHAR" : return DataType.VarChar; // LongVarChar System.String case "CHARACTER" : return DataType.Char; // Char System.String case "CHAR" : return DataType.Char; // Char System.String case "DECIMAL" : return DataType.Decimal; // Decimal System.Decimal case "INTEGER" : return DataType.Int32; // Integer System.Int32 case "SMALLINT" : return DataType.Int16; // SmallInt System.Int16 case "REAL" : return DataType.Single; // Real System.Single case "DOUBLE" : return DataType.Double; // Double System.Double case "VARCHAR" : return DataType.VarChar; // VarChar System.String case "DATE" : return DataType.Date; // Date System.DateTime case "TIME" : return DataType.Time; // Time System.TimeSpan case "TIMESTAMP" : return DataType.Timestamp; // Timestamp System.DateTime case "TIMESTMP" : return DataType.Timestamp; // Timestamp System.DateTime case "ROWID" : return DataType.Undefined; // RowID System.Byte[] } return DataType.Undefined; } protected override string GetProviderSpecificTypeNamespace() { return "IBM.Data.DB2Types"; } protected override string GetProviderSpecificType(string dataType) { switch (dataType) { case "XML" : return "DB2Xml"; case "DECFLOAT" : return "DB2DecimalFloat"; case "DBCLOB" : case "CLOB" : return "DB2Clob"; case "BLOB" : return "DB2Blob"; case "BIGINT" : return "DB2Int64"; case "LONG VARCHAR FOR BIT DATA" : case "VARCHAR () FOR BIT DATA" : case "VARBIN" : case "BINARY" : case "CHAR () FOR BIT DATA" : return "DB2Binary"; case "LONG VARGRAPHIC" : case "VARGRAPHIC" : case "GRAPHIC" : case "LONG VARCHAR" : case "CHARACTER" : case "VARCHAR" : case "CHAR" : return "DB2String"; case "DECIMAL" : return "DB2Decimal"; case "INTEGER" : return "DB2Int32"; case "SMALLINT" : return "DB2Int16"; case "REAL" : return "DB2Real"; case "DOUBLE" : return "DB2Double"; case "DATE" : return "DB2Date"; case "TIME" : return "DB2Time"; case "TIMESTMP" : case "TIMESTAMP" : return "DB2TimeStamp"; case "ROWID" : return "DB2RowId"; } return base.GetProviderSpecificType(dataType); } protected override string GetDataSourceName(DbConnection dbConnection) { var str = dbConnection.ConnectionString; if (str != null) { var host = str.Split(';') .Select(s => { var ss = s.Split('='); return new { key = ss.Length == 2 ? ss[0] : "", value = ss.Length == 2 ? ss[1] : "" }; }) .Where (s => s.key.ToUpper() == "SERVER") .Select(s => s.value) .FirstOrDefault(); if (host != null) return host; } return base.GetDataSourceName(dbConnection); } protected override List<ProcedureInfo> GetProcedures(DataConnection dataConnection) { return dataConnection .Query(rd => { var schema = rd.ToString(0); var name = rd.ToString(1); return new ProcedureInfo { ProcedureID = dataConnection.Connection.Database + "." + schema + "." + name, CatalogName = dataConnection.Connection.Database, SchemaName = schema, ProcedureName = name, }; },@" SELECT PROCSCHEMA, PROCNAME FROM SYSCAT.PROCEDURES WHERE " + GetSchemaFilter("PROCSCHEMA")) .Where(p => IncludedSchemas.Length != 0 || ExcludedSchemas.Length != 0 || p.SchemaName == CurrenSchema) .ToList(); } protected override List<ProcedureParameterInfo> GetProcedureParameters(DataConnection dataConnection) { return dataConnection .Query(rd => { var schema = rd.ToString(0); var procname = rd.ToString(1); var length = ConvertTo<long?>.From(rd["LENGTH"]); var scale = ConvertTo<int?>. From(rd["SCALE"]); var mode = ConvertTo<string>.From(rd[4]); var ppi = new ProcedureParameterInfo { ProcedureID = dataConnection.Connection.Database + "." + schema + "." + procname, ParameterName = rd.ToString(2), DataType = rd.ToString(3), Ordinal = ConvertTo<int>.From(rd["ORDINAL"]), IsIn = mode.Contains("IN"), IsOut = mode.Contains("OUT"), IsResult = false }; var ci = new ColumnInfo { DataType = ppi.DataType }; SetColumnParameters(ci, length, scale); ppi.Length = ci.Length; ppi.Precision = ci.Precision; ppi.Scale = ci.Scale; return ppi; },@" SELECT PROCSCHEMA, PROCNAME, PARMNAME, TYPENAME, PARM_MODE, ORDINAL, LENGTH, SCALE FROM SYSCAT.PROCPARMS WHERE " + GetSchemaFilter("PROCSCHEMA")) .ToList(); } protected string GetSchemaFilter(string schemaNameField) { if (IncludedSchemas.Length != 0 || ExcludedSchemas.Length != 0) { var sql = schemaNameField; if (IncludedSchemas.Length != 0) { sql += string.Format(" IN ({0})", IncludedSchemas.Select(n => '\'' + n + '\'') .Aggregate((s1,s2) => s1 + ',' + s2)); if (ExcludedSchemas.Length != 0) sql += " AND " + schemaNameField; } if (ExcludedSchemas.Length != 0) sql += string.Format(" NOT IN ({0})", ExcludedSchemas.Select(n => '\'' + n + '\'') .Aggregate((s1,s2) => s1 + ',' + s2)); return sql; } return string.Format("{0} = '{1}'", schemaNameField, CurrenSchema); } } static class DB2Extensions { public static string ToString(this IDataReader reader, int i) { var value = Converter.ChangeTypeTo<string>(reader[i]); return value == null ? null : value.TrimEnd(); } } }
/* * 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; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Reflection; using log4net; using OpenMetaverse; using OpenSim.Framework; namespace OpenSim.Data.MSSQL { /// <summary> /// A database interface class to a user profile storage system /// </summary> public class MSSQLUserData : UserDataBase { private const string _migrationStore = "UserStore"; private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); /// <summary> /// Database manager for MSSQL /// </summary> public MSSQLManager database; private const string m_agentsTableName = "agents"; private const string m_usersTableName = "users"; private const string m_userFriendsTableName = "userfriends"; // [Obsolete("Cannot be default-initialized!")] override public void Initialise() { m_log.Info("[MSSQLUserData]: " + Name + " cannot be default-initialized!"); throw new PluginNotInitialisedException(Name); } /// <summary> /// Loads and initialises the MSSQL storage plugin /// </summary> /// <param name="connect">connectionstring</param> /// <remarks>use mssql_connection.ini</remarks> override public void Initialise(string connect) { if (!string.IsNullOrEmpty(connect)) { database = new MSSQLManager(connect); } else { IniFile iniFile = new IniFile("mssql_connection.ini"); string settingDataSource = iniFile.ParseFileReadValue("data_source"); string settingInitialCatalog = iniFile.ParseFileReadValue("initial_catalog"); string settingPersistSecurityInfo = iniFile.ParseFileReadValue("persist_security_info"); string settingUserId = iniFile.ParseFileReadValue("user_id"); string settingPassword = iniFile.ParseFileReadValue("password"); database = new MSSQLManager(settingDataSource, settingInitialCatalog, settingPersistSecurityInfo, settingUserId, settingPassword); } //Check migration on DB database.CheckMigration(_migrationStore); } /// <summary> /// Releases unmanaged and - optionally - managed resources /// </summary> override public void Dispose() { } #region User table methods /// <summary> /// Searches the database for a specified user profile by name components /// </summary> /// <param name="user">The first part of the account name</param> /// <param name="last">The second part of the account name</param> /// <returns>A user profile</returns> override public UserProfileData GetUserByName(string user, string last) { string sql = string.Format(@"SELECT * FROM {0} WHERE username = @first AND lastname = @second", m_usersTableName); using (AutoClosingSqlCommand command = database.Query(sql)) { command.Parameters.Add(database.CreateParameter("first", user)); command.Parameters.Add(database.CreateParameter("second", last)); try { using (SqlDataReader reader = command.ExecuteReader()) { return ReadUserRow(reader); } } catch (Exception e) { m_log.ErrorFormat("[USER DB] Error getting user profile for {0} {1}: {2}", user, last, e.Message); return null; } } } /// <summary> /// See IUserDataPlugin /// </summary> /// <param name="uuid"></param> /// <returns></returns> override public UserProfileData GetUserByUUID(UUID uuid) { string sql = string.Format("SELECT * FROM {0} WHERE UUID = @uuid", m_usersTableName); using (AutoClosingSqlCommand command = database.Query(sql)) { command.Parameters.Add(database.CreateParameter("uuid", uuid)); try { using (SqlDataReader reader = command.ExecuteReader()) { return ReadUserRow(reader); } } catch (Exception e) { m_log.ErrorFormat("[USER DB] Error getting user profile by UUID {0}, error: {1}", uuid, e.Message); return null; } } } /// <summary> /// Creates a new users profile /// </summary> /// <param name="user">The user profile to create</param> override public void AddNewUserProfile(UserProfileData user) { try { InsertUserRow(user.ID, user.FirstName, user.SurName, user.Email, user.PasswordHash, user.PasswordSalt, user.HomeRegion, user.HomeLocation.X, user.HomeLocation.Y, user.HomeLocation.Z, user.HomeLookAt.X, user.HomeLookAt.Y, user.HomeLookAt.Z, user.Created, user.LastLogin, user.UserInventoryURI, user.UserAssetURI, user.CanDoMask, user.WantDoMask, user.AboutText, user.FirstLifeAboutText, user.Image, user.FirstLifeImage, user.WebLoginKey, user.HomeRegionID, user.GodLevel, user.UserFlags, user.CustomType, user.Partner); } catch (Exception e) { m_log.ErrorFormat("[USER DB] Error adding new profile, error: {0}", e.Message); } } /// <summary> /// update a user profile /// </summary> /// <param name="user">the profile to update</param> /// <returns></returns> override public bool UpdateUserProfile(UserProfileData user) { string sql = string.Format(@"UPDATE {0} SET UUID = @uuid, username = @username, lastname = @lastname, email = @email, passwordHash = @passwordHash, passwordSalt = @passwordSalt, homeRegion = @homeRegion, homeLocationX = @homeLocationX, homeLocationY = @homeLocationY, homeLocationZ = @homeLocationZ, homeLookAtX = @homeLookAtX, homeLookAtY = @homeLookAtY, homeLookAtZ = @homeLookAtZ, created = @created, lastLogin = @lastLogin, userInventoryURI = @userInventoryURI, userAssetURI = @userAssetURI, profileCanDoMask = @profileCanDoMask, profileWantDoMask = @profileWantDoMask, profileAboutText = @profileAboutText, profileFirstText = @profileFirstText, profileImage = @profileImage, profileFirstImage = @profileFirstImage, webLoginKey = @webLoginKey, homeRegionID = @homeRegionID, userFlags = @userFlags, godLevel = @godLevel, customType = @customType, partner = @partner WHERE UUID = @keyUUUID;",m_usersTableName); using (AutoClosingSqlCommand command = database.Query(sql)) { command.Parameters.Add(database.CreateParameter("uuid", user.ID)); command.Parameters.Add(database.CreateParameter("username", user.FirstName)); command.Parameters.Add(database.CreateParameter("lastname", user.SurName)); command.Parameters.Add(database.CreateParameter("email", user.Email)); command.Parameters.Add(database.CreateParameter("passwordHash", user.PasswordHash)); command.Parameters.Add(database.CreateParameter("passwordSalt", user.PasswordSalt)); command.Parameters.Add(database.CreateParameter("homeRegion", user.HomeRegion)); command.Parameters.Add(database.CreateParameter("homeLocationX", user.HomeLocation.X)); command.Parameters.Add(database.CreateParameter("homeLocationY", user.HomeLocation.Y)); command.Parameters.Add(database.CreateParameter("homeLocationZ", user.HomeLocation.Z)); command.Parameters.Add(database.CreateParameter("homeLookAtX", user.HomeLookAt.X)); command.Parameters.Add(database.CreateParameter("homeLookAtY", user.HomeLookAt.Y)); command.Parameters.Add(database.CreateParameter("homeLookAtZ", user.HomeLookAt.Z)); command.Parameters.Add(database.CreateParameter("created", user.Created)); command.Parameters.Add(database.CreateParameter("lastLogin", user.LastLogin)); command.Parameters.Add(database.CreateParameter("userInventoryURI", user.UserInventoryURI)); command.Parameters.Add(database.CreateParameter("userAssetURI", user.UserAssetURI)); command.Parameters.Add(database.CreateParameter("profileCanDoMask", user.CanDoMask)); command.Parameters.Add(database.CreateParameter("profileWantDoMask", user.WantDoMask)); command.Parameters.Add(database.CreateParameter("profileAboutText", user.AboutText)); command.Parameters.Add(database.CreateParameter("profileFirstText", user.FirstLifeAboutText)); command.Parameters.Add(database.CreateParameter("profileImage", user.Image)); command.Parameters.Add(database.CreateParameter("profileFirstImage", user.FirstLifeImage)); command.Parameters.Add(database.CreateParameter("webLoginKey", user.WebLoginKey)); command.Parameters.Add(database.CreateParameter("homeRegionID", user.HomeRegionID)); command.Parameters.Add(database.CreateParameter("userFlags", user.UserFlags)); command.Parameters.Add(database.CreateParameter("godLevel", user.GodLevel)); command.Parameters.Add(database.CreateParameter("customType", user.CustomType)); command.Parameters.Add(database.CreateParameter("partner", user.Partner)); command.Parameters.Add(database.CreateParameter("keyUUUID", user.ID)); try { int affected = command.ExecuteNonQuery(); return (affected != 0); } catch (Exception e) { m_log.ErrorFormat("[USER DB] Error updating profile, error: {0}", e.Message); } } return false; } #endregion #region Agent table methods /// <summary> /// Returns a user session searching by name /// </summary> /// <param name="name">The account name</param> /// <returns>The users session</returns> override public UserAgentData GetAgentByName(string name) { return GetAgentByName(name.Split(' ')[0], name.Split(' ')[1]); } /// <summary> /// Returns a user session by account name /// </summary> /// <param name="user">First part of the users account name</param> /// <param name="last">Second part of the users account name</param> /// <returns>The users session</returns> override public UserAgentData GetAgentByName(string user, string last) { UserProfileData profile = GetUserByName(user, last); return GetAgentByUUID(profile.ID); } /// <summary> /// Returns an agent session by account UUID /// </summary> /// <param name="uuid">The accounts UUID</param> /// <returns>The users session</returns> override public UserAgentData GetAgentByUUID(UUID uuid) { string sql = string.Format("SELECT * FROM {0} WHERE UUID = @uuid", m_agentsTableName); using (AutoClosingSqlCommand command = database.Query(sql)) { command.Parameters.Add(database.CreateParameter("uuid", uuid)); try { using (SqlDataReader reader = command.ExecuteReader()) { return readAgentRow(reader); } } catch (Exception e) { m_log.ErrorFormat("[USER DB] Error updating agentdata by UUID, error: {0}", e.Message); return null; } } } /// <summary> /// Creates a new agent /// </summary> /// <param name="agent">The agent to create</param> override public void AddNewUserAgent(UserAgentData agent) { try { InsertUpdateAgentRow(agent); } catch (Exception e) { m_log.ErrorFormat("[USER DB] Error adding new agentdata, error: {0}", e.Message); } } #endregion #region User Friends List Data /// <summary> /// Add a new friend in the friendlist /// </summary> /// <param name="friendlistowner">UUID of the friendlist owner</param> /// <param name="friend">Friend's UUID</param> /// <param name="perms">Permission flag</param> override public void AddNewUserFriend(UUID friendlistowner, UUID friend, uint perms) { int dtvalue = Util.UnixTimeSinceEpoch(); string sql = string.Format(@"INSERT INTO {0} (ownerID,friendID,friendPerms,datetimestamp) VALUES (@ownerID,@friendID,@friendPerms,@datetimestamp)", m_userFriendsTableName); using (AutoClosingSqlCommand command = database.Query(sql)) { command.Parameters.Add(database.CreateParameter("ownerID", friendlistowner)); command.Parameters.Add(database.CreateParameter("friendID", friend)); command.Parameters.Add(database.CreateParameter("friendPerms", perms)); command.Parameters.Add(database.CreateParameter("datetimestamp", dtvalue)); command.ExecuteNonQuery(); try { sql = string.Format(@"INSERT INTO {0} (ownerID,friendID,friendPerms,datetimestamp) VALUES (@friendID,@ownerID,@friendPerms,@datetimestamp)", m_userFriendsTableName); command.CommandText = sql; command.ExecuteNonQuery(); } catch (Exception e) { m_log.ErrorFormat("[USER DB] Error adding new userfriend, error: {0}", e.Message); return; } } } /// <summary> /// Remove an friend from the friendlist /// </summary> /// <param name="friendlistowner">UUID of the friendlist owner</param> /// <param name="friend">UUID of the not-so-friendly user to remove from the list</param> override public void RemoveUserFriend(UUID friendlistowner, UUID friend) { string sql = string.Format(@"DELETE from {0} WHERE ownerID = @ownerID AND friendID = @friendID", m_userFriendsTableName); using (AutoClosingSqlCommand command = database.Query(sql)) { command.Parameters.Add(database.CreateParameter("@ownerID", friendlistowner)); command.Parameters.Add(database.CreateParameter("@friendID", friend)); command.ExecuteNonQuery(); sql = string.Format(@"DELETE from {0} WHERE ownerID = @friendID AND friendID = @ownerID", m_userFriendsTableName); command.CommandText = sql; try { command.ExecuteNonQuery(); } catch (Exception e) { m_log.ErrorFormat("[USER DB] Error removing userfriend, error: {0}", e.Message); } } } /// <summary> /// Update friendlist permission flag for a friend /// </summary> /// <param name="friendlistowner">UUID of the friendlist owner</param> /// <param name="friend">UUID of the friend</param> /// <param name="perms">new permission flag</param> override public void UpdateUserFriendPerms(UUID friendlistowner, UUID friend, uint perms) { string sql = string.Format(@"UPDATE {0} SET friendPerms = @friendPerms WHERE ownerID = @ownerID AND friendID = @friendID", m_userFriendsTableName); using (AutoClosingSqlCommand command = database.Query(sql)) { command.Parameters.Add(database.CreateParameter("@ownerID", friendlistowner)); command.Parameters.Add(database.CreateParameter("@friendID", friend)); command.Parameters.Add(database.CreateParameter("@friendPerms", perms)); try { command.ExecuteNonQuery(); } catch (Exception e) { m_log.ErrorFormat("[USER DB] Error updating userfriend, error: {0}", e.Message); } } } /// <summary> /// Get (fetch?) the user's friendlist /// </summary> /// <param name="friendlistowner">UUID of the friendlist owner</param> /// <returns>Friendlist list</returns> override public List<FriendListItem> GetUserFriendList(UUID friendlistowner) { List<FriendListItem> friendList = new List<FriendListItem>(); //Left Join userfriends to itself string sql = string.Format(@"SELECT a.ownerID, a.friendID, a.friendPerms, b.friendPerms AS ownerperms FROM {0} as a, {0} as b WHERE a.ownerID = @ownerID AND b.ownerID = a.friendID AND b.friendID = a.ownerID", m_userFriendsTableName); using (AutoClosingSqlCommand command = database.Query(sql)) { command.Parameters.Add(database.CreateParameter("@ownerID", friendlistowner)); try { using (SqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) { FriendListItem fli = new FriendListItem(); fli.FriendListOwner = new UUID((Guid)reader["ownerID"]); fli.Friend = new UUID((Guid)reader["friendID"]); fli.FriendPerms = (uint)Convert.ToInt32(reader["friendPerms"]); // This is not a real column in the database table, it's a joined column from the opposite record fli.FriendListOwnerPerms = (uint)Convert.ToInt32(reader["ownerperms"]); friendList.Add(fli); } } } catch (Exception e) { m_log.ErrorFormat("[USER DB] Error updating userfriend, error: {0}", e.Message); } } return friendList; } override public Dictionary<UUID, FriendRegionInfo> GetFriendRegionInfos (List<UUID> uuids) { Dictionary<UUID, FriendRegionInfo> infos = new Dictionary<UUID,FriendRegionInfo>(); try { foreach (UUID uuid in uuids) { string sql = string.Format(@"SELECT agentOnline,currentHandle FROM {0} WHERE UUID = @uuid", m_agentsTableName); using (AutoClosingSqlCommand command = database.Query(sql)) { command.Parameters.Add(database.CreateParameter("@uuid", uuid)); using (SqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) { FriendRegionInfo fri = new FriendRegionInfo(); fri.isOnline = (byte)reader["agentOnline"] != 0; fri.regionHandle = Convert.ToUInt64(reader["currentHandle"].ToString()); infos[uuid] = fri; } } } } } catch (Exception e) { m_log.Warn("[MSSQL]: Got exception on trying to find friends regions:", e); } return infos; } #endregion #region Money functions (not used) /// <summary> /// Performs a money transfer request between two accounts /// </summary> /// <param name="from">The senders account ID</param> /// <param name="to">The receivers account ID</param> /// <param name="amount">The amount to transfer</param> /// <returns>false</returns> override public bool MoneyTransferRequest(UUID from, UUID to, uint amount) { return false; } /// <summary> /// Performs an inventory transfer request between two accounts /// </summary> /// <remarks>TODO: Move to inventory server</remarks> /// <param name="from">The senders account ID</param> /// <param name="to">The receivers account ID</param> /// <param name="item">The item to transfer</param> /// <returns>false</returns> override public bool InventoryTransferRequest(UUID from, UUID to, UUID item) { return false; } #endregion #region Appearance methods /// <summary> /// Gets the user appearance. /// </summary> /// <param name="user">The user.</param> /// <returns></returns> override public AvatarAppearance GetUserAppearance(UUID user) { try { AvatarAppearance appearance = new AvatarAppearance(); string sql = "SELECT * FROM avatarappearance WHERE owner = @UUID"; using (AutoClosingSqlCommand command = database.Query(sql)) { command.Parameters.Add(database.CreateParameter("@UUID", user)); using (SqlDataReader reader = command.ExecuteReader()) { if (reader.Read()) appearance = readUserAppearance(reader); else { m_log.WarnFormat("[USER DB] No appearance found for user {0}", user.ToString()); return null; } } } appearance.SetAttachments(GetUserAttachments(user)); return appearance; } catch (Exception e) { m_log.ErrorFormat("[USER DB] Error updating userfriend, error: {0}", e.Message); } return null; } /// <summary> /// Update a user appearence into database /// </summary> /// <param name="user">the used UUID</param> /// <param name="appearance">the appearence</param> override public void UpdateUserAppearance(UUID user, AvatarAppearance appearance) { string sql = @"DELETE FROM avatarappearance WHERE owner=@owner"; using (AutoClosingSqlCommand cmd = database.Query(sql)) { cmd.Parameters.Add(database.CreateParameter("@owner", appearance.Owner)); try { cmd.ExecuteNonQuery(); } catch (Exception e) { m_log.ErrorFormat("[USER DB] Error deleting old user appearance, error: {0}", e.Message); } } sql=@"INSERT INTO avatarappearance (owner, serial, visual_params, texture, avatar_height, body_item, body_asset, skin_item, skin_asset, hair_item, hair_asset, eyes_item, eyes_asset, shirt_item, shirt_asset, pants_item, pants_asset, shoes_item, shoes_asset, socks_item, socks_asset, jacket_item, jacket_asset, gloves_item, gloves_asset, undershirt_item, undershirt_asset, underpants_item, underpants_asset, skirt_item, skirt_asset) VALUES (@owner, @serial, @visual_params, @texture, @avatar_height, @body_item, @body_asset, @skin_item, @skin_asset, @hair_item, @hair_asset, @eyes_item, @eyes_asset, @shirt_item, @shirt_asset, @pants_item, @pants_asset, @shoes_item, @shoes_asset, @socks_item, @socks_asset, @jacket_item, @jacket_asset, @gloves_item, @gloves_asset, @undershirt_item, @undershirt_asset, @underpants_item, @underpants_asset, @skirt_item, @skirt_asset)"; using (AutoClosingSqlCommand cmd = database.Query(sql)) { cmd.Parameters.Add(database.CreateParameter("@owner", appearance.Owner)); cmd.Parameters.Add(database.CreateParameter("@serial", appearance.Serial)); cmd.Parameters.Add(database.CreateParameter("@visual_params", appearance.VisualParams)); cmd.Parameters.Add(database.CreateParameter("@texture", appearance.Texture.GetBytes())); cmd.Parameters.Add(database.CreateParameter("@avatar_height", appearance.AvatarHeight)); cmd.Parameters.Add(database.CreateParameter("@body_item", appearance.BodyItem)); cmd.Parameters.Add(database.CreateParameter("@body_asset", appearance.BodyAsset)); cmd.Parameters.Add(database.CreateParameter("@skin_item", appearance.SkinItem)); cmd.Parameters.Add(database.CreateParameter("@skin_asset", appearance.SkinAsset)); cmd.Parameters.Add(database.CreateParameter("@hair_item", appearance.HairItem)); cmd.Parameters.Add(database.CreateParameter("@hair_asset", appearance.HairAsset)); cmd.Parameters.Add(database.CreateParameter("@eyes_item", appearance.EyesItem)); cmd.Parameters.Add(database.CreateParameter("@eyes_asset", appearance.EyesAsset)); cmd.Parameters.Add(database.CreateParameter("@shirt_item", appearance.ShirtItem)); cmd.Parameters.Add(database.CreateParameter("@shirt_asset", appearance.ShirtAsset)); cmd.Parameters.Add(database.CreateParameter("@pants_item", appearance.PantsItem)); cmd.Parameters.Add(database.CreateParameter("@pants_asset", appearance.PantsAsset)); cmd.Parameters.Add(database.CreateParameter("@shoes_item", appearance.ShoesItem)); cmd.Parameters.Add(database.CreateParameter("@shoes_asset", appearance.ShoesAsset)); cmd.Parameters.Add(database.CreateParameter("@socks_item", appearance.SocksItem)); cmd.Parameters.Add(database.CreateParameter("@socks_asset", appearance.SocksAsset)); cmd.Parameters.Add(database.CreateParameter("@jacket_item", appearance.JacketItem)); cmd.Parameters.Add(database.CreateParameter("@jacket_asset", appearance.JacketAsset)); cmd.Parameters.Add(database.CreateParameter("@gloves_item", appearance.GlovesItem)); cmd.Parameters.Add(database.CreateParameter("@gloves_asset", appearance.GlovesAsset)); cmd.Parameters.Add(database.CreateParameter("@undershirt_item", appearance.UnderShirtItem)); cmd.Parameters.Add(database.CreateParameter("@undershirt_asset", appearance.UnderShirtAsset)); cmd.Parameters.Add(database.CreateParameter("@underpants_item", appearance.UnderPantsItem)); cmd.Parameters.Add(database.CreateParameter("@underpants_asset", appearance.UnderPantsAsset)); cmd.Parameters.Add(database.CreateParameter("@skirt_item", appearance.SkirtItem)); cmd.Parameters.Add(database.CreateParameter("@skirt_asset", appearance.SkirtAsset)); try { cmd.ExecuteNonQuery(); } catch (Exception e) { m_log.ErrorFormat("[USER DB] Error updating user appearance, error: {0}", e.Message); } } UpdateUserAttachments(user, appearance.GetAttachments()); } #endregion #region Attachment methods /// <summary> /// Gets all attachment of a agent. /// </summary> /// <param name="agentID">agent ID.</param> /// <returns></returns> public Hashtable GetUserAttachments(UUID agentID) { Hashtable returnTable = new Hashtable(); string sql = "select attachpoint, item, asset from avatarattachments where UUID = @uuid"; using (AutoClosingSqlCommand command = database.Query(sql, database.CreateParameter("@uuid", agentID))) { using (SqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) { int attachpoint = Convert.ToInt32(reader["attachpoint"]); if (returnTable.ContainsKey(attachpoint)) continue; Hashtable item = new Hashtable(); item.Add("item", reader["item"].ToString()); item.Add("asset", reader["asset"].ToString()); returnTable.Add(attachpoint, item); } } } return returnTable; } /// <summary> /// Updates all attachments of the agent. /// </summary> /// <param name="agentID">agentID.</param> /// <param name="data">data with all items on attachmentpoints</param> public void UpdateUserAttachments(UUID agentID, Hashtable data) { string sql = "DELETE FROM avatarattachments WHERE UUID = @uuid"; using (AutoClosingSqlCommand command = database.Query(sql)) { command.Parameters.Add(database.CreateParameter("uuid", agentID)); command.ExecuteNonQuery(); } if (data == null) return; sql = @"INSERT INTO avatarattachments (UUID, attachpoint, item, asset) VALUES (@uuid, @attachpoint, @item, @asset)"; using (AutoClosingSqlCommand command = database.Query(sql)) { bool firstTime = true; foreach (DictionaryEntry e in data) { int attachpoint = Convert.ToInt32(e.Key); Hashtable item = (Hashtable)e.Value; if (firstTime) { command.Parameters.Add(database.CreateParameter("@uuid", agentID)); command.Parameters.Add(database.CreateParameter("@attachpoint", attachpoint)); command.Parameters.Add(database.CreateParameter("@item", new UUID(item["item"].ToString()))); command.Parameters.Add(database.CreateParameter("@asset", new UUID(item["asset"].ToString()))); firstTime = false; } command.Parameters["@uuid"].Value = agentID.Guid; //.ToString(); command.Parameters["@attachpoint"].Value = attachpoint; command.Parameters["@item"].Value = new Guid(item["item"].ToString()); command.Parameters["@asset"].Value = new Guid(item["asset"].ToString()); try { command.ExecuteNonQuery(); } catch (Exception ex) { m_log.DebugFormat("[USER DB] : Error adding user attachment. {0}", ex.Message); } } } } /// <summary> /// Resets all attachments of a agent in the database. /// </summary> /// <param name="agentID">agentID.</param> override public void ResetAttachments(UUID agentID) { string sql = "UPDATE avatarattachments SET asset = '00000000-0000-0000-0000-000000000000' WHERE UUID = @uuid"; using (AutoClosingSqlCommand command = database.Query(sql)) { command.Parameters.Add(database.CreateParameter("uuid", agentID)); command.ExecuteNonQuery(); } } override public void LogoutUsers(UUID regionID) { } #endregion #region Other public methods /// <summary> /// /// </summary> /// <param name="queryID"></param> /// <param name="query"></param> /// <returns></returns> override public List<AvatarPickerAvatar> GeneratePickerResults(UUID queryID, string query) { List<AvatarPickerAvatar> returnlist = new List<AvatarPickerAvatar>(); string[] querysplit = query.Split(' '); if (querysplit.Length == 2) { try { string sql = string.Format(@"SELECT UUID,username,lastname FROM {0} WHERE username LIKE @first AND lastname LIKE @second", m_usersTableName); using (AutoClosingSqlCommand command = database.Query(sql)) { //Add wildcard to the search command.Parameters.Add(database.CreateParameter("first", querysplit[0] + "%")); command.Parameters.Add(database.CreateParameter("second", querysplit[1] + "%")); using (SqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) { AvatarPickerAvatar user = new AvatarPickerAvatar(); user.AvatarID = new UUID((Guid)reader["UUID"]); user.firstName = (string)reader["username"]; user.lastName = (string)reader["lastname"]; returnlist.Add(user); } } } } catch (Exception e) { m_log.Error(e.ToString()); } } else if (querysplit.Length == 1) { try { string sql = string.Format(@"SELECT UUID,username,lastname FROM {0} WHERE username LIKE @first OR lastname LIKE @first", m_usersTableName); using (AutoClosingSqlCommand command = database.Query(sql)) { command.Parameters.Add(database.CreateParameter("first", querysplit[0] + "%")); using (SqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) { AvatarPickerAvatar user = new AvatarPickerAvatar(); user.AvatarID = new UUID((Guid)reader["UUID"]); user.firstName = (string)reader["username"]; user.lastName = (string)reader["lastname"]; returnlist.Add(user); } } } } catch (Exception e) { m_log.Error(e.ToString()); } } return returnlist; } /// <summary> /// Store a weblogin key /// </summary> /// <param name="AgentID">The agent UUID</param> /// <param name="WebLoginKey">the WebLogin Key</param> /// <remarks>unused ?</remarks> override public void StoreWebLoginKey(UUID AgentID, UUID WebLoginKey) { UserProfileData user = GetUserByUUID(AgentID); user.WebLoginKey = WebLoginKey; UpdateUserProfile(user); } /// <summary> /// Database provider name /// </summary> /// <returns>Provider name</returns> override public string Name { get { return "MSSQL Userdata Interface"; } } /// <summary> /// Database provider version /// </summary> /// <returns>provider version</returns> override public string Version { get { return database.getVersion(); } } #endregion #region Private functions /// <summary> /// Reads a one item from an SQL result /// </summary> /// <param name="reader">The SQL Result</param> /// <returns>the item read</returns> private static AvatarAppearance readUserAppearance(SqlDataReader reader) { try { AvatarAppearance appearance = new AvatarAppearance(); appearance.Owner = new UUID((Guid)reader["owner"]); appearance.Serial = Convert.ToInt32(reader["serial"]); appearance.VisualParams = (byte[])reader["visual_params"]; appearance.Texture = new Primitive.TextureEntry((byte[])reader["texture"], 0, ((byte[])reader["texture"]).Length); appearance.AvatarHeight = (float)Convert.ToDouble(reader["avatar_height"]); appearance.BodyItem = new UUID((Guid)reader["body_item"]); appearance.BodyAsset = new UUID((Guid)reader["body_asset"]); appearance.SkinItem = new UUID((Guid)reader["skin_item"]); appearance.SkinAsset = new UUID((Guid)reader["skin_asset"]); appearance.HairItem = new UUID((Guid)reader["hair_item"]); appearance.HairAsset = new UUID((Guid)reader["hair_asset"]); appearance.EyesItem = new UUID((Guid)reader["eyes_item"]); appearance.EyesAsset = new UUID((Guid)reader["eyes_asset"]); appearance.ShirtItem = new UUID((Guid)reader["shirt_item"]); appearance.ShirtAsset = new UUID((Guid)reader["shirt_asset"]); appearance.PantsItem = new UUID((Guid)reader["pants_item"]); appearance.PantsAsset = new UUID((Guid)reader["pants_asset"]); appearance.ShoesItem = new UUID((Guid)reader["shoes_item"]); appearance.ShoesAsset = new UUID((Guid)reader["shoes_asset"]); appearance.SocksItem = new UUID((Guid)reader["socks_item"]); appearance.SocksAsset = new UUID((Guid)reader["socks_asset"]); appearance.JacketItem = new UUID((Guid)reader["jacket_item"]); appearance.JacketAsset = new UUID((Guid)reader["jacket_asset"]); appearance.GlovesItem = new UUID((Guid)reader["gloves_item"]); appearance.GlovesAsset = new UUID((Guid)reader["gloves_asset"]); appearance.UnderShirtItem = new UUID((Guid)reader["undershirt_item"]); appearance.UnderShirtAsset = new UUID((Guid)reader["undershirt_asset"]); appearance.UnderPantsItem = new UUID((Guid)reader["underpants_item"]); appearance.UnderPantsAsset = new UUID((Guid)reader["underpants_asset"]); appearance.SkirtItem = new UUID((Guid)reader["skirt_item"]); appearance.SkirtAsset = new UUID((Guid)reader["skirt_asset"]); return appearance; } catch (SqlException e) { m_log.Error(e.ToString()); } return null; } /// <summary> /// Insert/Update a agent row in the DB. /// </summary> /// <param name="agentdata">agentdata.</param> private void InsertUpdateAgentRow(UserAgentData agentdata) { string sql = @" IF EXISTS (SELECT * FROM agents WHERE UUID = @UUID) BEGIN UPDATE agents SET UUID = @UUID, sessionID = @sessionID, secureSessionID = @secureSessionID, agentIP = @agentIP, agentPort = @agentPort, agentOnline = @agentOnline, loginTime = @loginTime, logoutTime = @logoutTime, currentRegion = @currentRegion, currentHandle = @currentHandle, currentPos = @currentPos WHERE UUID = @UUID END ELSE BEGIN INSERT INTO agents (UUID, sessionID, secureSessionID, agentIP, agentPort, agentOnline, loginTime, logoutTime, currentRegion, currentHandle, currentPos) VALUES (@UUID, @sessionID, @secureSessionID, @agentIP, @agentPort, @agentOnline, @loginTime, @logoutTime, @currentRegion, @currentHandle, @currentPos) END "; using (AutoClosingSqlCommand command = database.Query(sql)) { command.Parameters.Add(database.CreateParameter("@UUID", agentdata.ProfileID)); command.Parameters.Add(database.CreateParameter("@sessionID", agentdata.SessionID)); command.Parameters.Add(database.CreateParameter("@secureSessionID", agentdata.SecureSessionID)); command.Parameters.Add(database.CreateParameter("@agentIP", agentdata.AgentIP)); command.Parameters.Add(database.CreateParameter("@agentPort", agentdata.AgentPort)); command.Parameters.Add(database.CreateParameter("@agentOnline", agentdata.AgentOnline)); command.Parameters.Add(database.CreateParameter("@loginTime", agentdata.LoginTime)); command.Parameters.Add(database.CreateParameter("@logoutTime", agentdata.LogoutTime)); command.Parameters.Add(database.CreateParameter("@currentRegion", agentdata.Region)); command.Parameters.Add(database.CreateParameter("@currentHandle", agentdata.Handle)); command.Parameters.Add(database.CreateParameter("@currentPos", "<" + ((int)agentdata.Position.X) + "," + ((int)agentdata.Position.Y) + "," + ((int)agentdata.Position.Z) + ">")); command.Transaction = command.Connection.BeginTransaction(IsolationLevel.Serializable); try { if (command.ExecuteNonQuery() > 0) { command.Transaction.Commit(); return; } command.Transaction.Rollback(); return; } catch (Exception e) { command.Transaction.Rollback(); m_log.Error(e.ToString()); return; } } } /// <summary> /// Reads an agent row from a database reader /// </summary> /// <param name="reader">An active database reader</param> /// <returns>A user session agent</returns> private UserAgentData readAgentRow(SqlDataReader reader) { UserAgentData retval = new UserAgentData(); if (reader.Read()) { // Agent IDs retval.ProfileID = new UUID((Guid)reader["UUID"]); retval.SessionID = new UUID((Guid)reader["sessionID"]); retval.SecureSessionID = new UUID((Guid)reader["secureSessionID"]); // Agent Who? retval.AgentIP = (string)reader["agentIP"]; retval.AgentPort = Convert.ToUInt32(reader["agentPort"].ToString()); retval.AgentOnline = Convert.ToInt32(reader["agentOnline"].ToString()) != 0; // Login/Logout times (UNIX Epoch) retval.LoginTime = Convert.ToInt32(reader["loginTime"].ToString()); retval.LogoutTime = Convert.ToInt32(reader["logoutTime"].ToString()); // Current position retval.Region = new UUID((Guid)reader["currentRegion"]); retval.Handle = Convert.ToUInt64(reader["currentHandle"].ToString()); Vector3 tmp_v; Vector3.TryParse((string)reader["currentPos"], out tmp_v); retval.Position = tmp_v; } else { return null; } return retval; } /// <summary> /// Creates a new user and inserts it into the database /// </summary> /// <param name="uuid">User ID</param> /// <param name="username">First part of the login</param> /// <param name="lastname">Second part of the login</param> /// <param name="email">Email of person</param> /// <param name="passwordHash">A salted hash of the users password</param> /// <param name="passwordSalt">The salt used for the password hash</param> /// <param name="homeRegion">A regionHandle of the users home region</param> /// <param name="homeLocX">Home region position vector</param> /// <param name="homeLocY">Home region position vector</param> /// <param name="homeLocZ">Home region position vector</param> /// <param name="homeLookAtX">Home region 'look at' vector</param> /// <param name="homeLookAtY">Home region 'look at' vector</param> /// <param name="homeLookAtZ">Home region 'look at' vector</param> /// <param name="created">Account created (unix timestamp)</param> /// <param name="lastlogin">Last login (unix timestamp)</param> /// <param name="inventoryURI">Users inventory URI</param> /// <param name="assetURI">Users asset URI</param> /// <param name="canDoMask">I can do mask</param> /// <param name="wantDoMask">I want to do mask</param> /// <param name="aboutText">Profile text</param> /// <param name="firstText">Firstlife text</param> /// <param name="profileImage">UUID for profile image</param> /// <param name="firstImage">UUID for firstlife image</param> /// <param name="webLoginKey">web login key</param> /// <param name="homeRegionID">homeregion UUID</param> /// <param name="godLevel">has the user godlevel</param> /// <param name="userFlags">unknown</param> /// <param name="customType">unknown</param> /// <param name="partnerID">UUID of partner</param> /// <returns>Success?</returns> private void InsertUserRow(UUID uuid, string username, string lastname, string email, string passwordHash, string passwordSalt, UInt64 homeRegion, float homeLocX, float homeLocY, float homeLocZ, float homeLookAtX, float homeLookAtY, float homeLookAtZ, int created, int lastlogin, string inventoryURI, string assetURI, uint canDoMask, uint wantDoMask, string aboutText, string firstText, UUID profileImage, UUID firstImage, UUID webLoginKey, UUID homeRegionID, int godLevel, int userFlags, string customType, UUID partnerID) { string sql = string.Format(@"INSERT INTO {0} ([UUID], [username], [lastname], [email], [passwordHash], [passwordSalt], [homeRegion], [homeLocationX], [homeLocationY], [homeLocationZ], [homeLookAtX], [homeLookAtY], [homeLookAtZ], [created], [lastLogin], [userInventoryURI], [userAssetURI], [profileCanDoMask], [profileWantDoMask], [profileAboutText], [profileFirstText], [profileImage], [profileFirstImage], [webLoginKey], [homeRegionID], [userFlags], [godLevel], [customType], [partner]) VALUES (@UUID, @username, @lastname, @email, @passwordHash, @passwordSalt, @homeRegion, @homeLocationX, @homeLocationY, @homeLocationZ, @homeLookAtX, @homeLookAtY, @homeLookAtZ, @created, @lastLogin, @userInventoryURI, @userAssetURI, @profileCanDoMask, @profileWantDoMask, @profileAboutText, @profileFirstText, @profileImage, @profileFirstImage, @webLoginKey, @homeRegionID, @userFlags, @godLevel, @customType, @partner)", m_usersTableName); try { using (AutoClosingSqlCommand command = database.Query(sql)) { command.Parameters.Add(database.CreateParameter("UUID", uuid)); command.Parameters.Add(database.CreateParameter("username", username)); command.Parameters.Add(database.CreateParameter("lastname", lastname)); command.Parameters.Add(database.CreateParameter("email", email)); command.Parameters.Add(database.CreateParameter("passwordHash", passwordHash)); command.Parameters.Add(database.CreateParameter("passwordSalt", passwordSalt)); command.Parameters.Add(database.CreateParameter("homeRegion", homeRegion)); command.Parameters.Add(database.CreateParameter("homeLocationX", homeLocX)); command.Parameters.Add(database.CreateParameter("homeLocationY", homeLocY)); command.Parameters.Add(database.CreateParameter("homeLocationZ", homeLocZ)); command.Parameters.Add(database.CreateParameter("homeLookAtX", homeLookAtX)); command.Parameters.Add(database.CreateParameter("homeLookAtY", homeLookAtY)); command.Parameters.Add(database.CreateParameter("homeLookAtZ", homeLookAtZ)); command.Parameters.Add(database.CreateParameter("created", created)); command.Parameters.Add(database.CreateParameter("lastLogin", lastlogin)); command.Parameters.Add(database.CreateParameter("userInventoryURI", inventoryURI)); command.Parameters.Add(database.CreateParameter("userAssetURI", assetURI)); command.Parameters.Add(database.CreateParameter("profileCanDoMask", canDoMask)); command.Parameters.Add(database.CreateParameter("profileWantDoMask", wantDoMask)); command.Parameters.Add(database.CreateParameter("profileAboutText", aboutText)); command.Parameters.Add(database.CreateParameter("profileFirstText", firstText)); command.Parameters.Add(database.CreateParameter("profileImage", profileImage)); command.Parameters.Add(database.CreateParameter("profileFirstImage", firstImage)); command.Parameters.Add(database.CreateParameter("webLoginKey", webLoginKey)); command.Parameters.Add(database.CreateParameter("homeRegionID", homeRegionID)); command.Parameters.Add(database.CreateParameter("userFlags", userFlags)); command.Parameters.Add(database.CreateParameter("godLevel", godLevel)); command.Parameters.Add(database.CreateParameter("customType", customType)); command.Parameters.Add(database.CreateParameter("partner", partnerID)); command.ExecuteNonQuery(); return; } } catch (Exception e) { m_log.Error(e.ToString()); return; } } /// <summary> /// Reads a user profile from an active data reader /// </summary> /// <param name="reader">An active database reader</param> /// <returns>A user profile</returns> private static UserProfileData ReadUserRow(SqlDataReader reader) { UserProfileData retval = new UserProfileData(); if (reader.Read()) { retval.ID = new UUID((Guid)reader["UUID"]); retval.FirstName = (string)reader["username"]; retval.SurName = (string)reader["lastname"]; if (reader.IsDBNull(reader.GetOrdinal("email"))) retval.Email = ""; else retval.Email = (string)reader["email"]; retval.PasswordHash = (string)reader["passwordHash"]; retval.PasswordSalt = (string)reader["passwordSalt"]; retval.HomeRegion = Convert.ToUInt64(reader["homeRegion"].ToString()); retval.HomeLocation = new Vector3( Convert.ToSingle(reader["homeLocationX"].ToString()), Convert.ToSingle(reader["homeLocationY"].ToString()), Convert.ToSingle(reader["homeLocationZ"].ToString())); retval.HomeLookAt = new Vector3( Convert.ToSingle(reader["homeLookAtX"].ToString()), Convert.ToSingle(reader["homeLookAtY"].ToString()), Convert.ToSingle(reader["homeLookAtZ"].ToString())); if (reader.IsDBNull(reader.GetOrdinal("homeRegionID"))) retval.HomeRegionID = UUID.Zero; else retval.HomeRegionID = new UUID((Guid)reader["homeRegionID"]); retval.Created = Convert.ToInt32(reader["created"].ToString()); retval.LastLogin = Convert.ToInt32(reader["lastLogin"].ToString()); if (reader.IsDBNull(reader.GetOrdinal("userInventoryURI"))) retval.UserInventoryURI = ""; else retval.UserInventoryURI = (string)reader["userInventoryURI"]; if (reader.IsDBNull(reader.GetOrdinal("userAssetURI"))) retval.UserAssetURI = ""; else retval.UserAssetURI = (string)reader["userAssetURI"]; retval.CanDoMask = Convert.ToUInt32(reader["profileCanDoMask"].ToString()); retval.WantDoMask = Convert.ToUInt32(reader["profileWantDoMask"].ToString()); if (reader.IsDBNull(reader.GetOrdinal("profileAboutText"))) retval.AboutText = ""; else retval.AboutText = (string)reader["profileAboutText"]; if (reader.IsDBNull(reader.GetOrdinal("profileFirstText"))) retval.FirstLifeAboutText = ""; else retval.FirstLifeAboutText = (string)reader["profileFirstText"]; if (reader.IsDBNull(reader.GetOrdinal("profileImage"))) retval.Image = UUID.Zero; else retval.Image = new UUID((Guid)reader["profileImage"]); if (reader.IsDBNull(reader.GetOrdinal("profileFirstImage"))) retval.Image = UUID.Zero; else retval.FirstLifeImage = new UUID((Guid)reader["profileFirstImage"]); if (reader.IsDBNull(reader.GetOrdinal("webLoginKey"))) retval.WebLoginKey = UUID.Zero; else retval.WebLoginKey = new UUID((Guid)reader["webLoginKey"]); retval.UserFlags = Convert.ToInt32(reader["userFlags"].ToString()); retval.GodLevel = Convert.ToInt32(reader["godLevel"].ToString()); if (reader.IsDBNull(reader.GetOrdinal("customType"))) retval.CustomType = ""; else retval.CustomType = reader["customType"].ToString(); if (reader.IsDBNull(reader.GetOrdinal("partner"))) retval.Partner = UUID.Zero; else retval.Partner = new UUID((Guid)reader["partner"]); } else { return null; } return retval; } #endregion } }
/// This code was generated by /// \ / _ _ _| _ _ /// | (_)\/(_)(_|\/| |(/_ v1.0.0 /// / / using System; using System.Collections.Generic; using Twilio.Base; using Twilio.Converters; namespace Twilio.Rest.Taskrouter.V1.Workspace { /// <summary> /// FetchTaskChannelOptions /// </summary> public class FetchTaskChannelOptions : IOptions<TaskChannelResource> { /// <summary> /// The SID of the Workspace with the Task Channel to fetch /// </summary> public string PathWorkspaceSid { get; } /// <summary> /// The SID of the Task Channel resource to fetch /// </summary> public string PathSid { get; } /// <summary> /// Construct a new FetchTaskChannelOptions /// </summary> /// <param name="pathWorkspaceSid"> The SID of the Workspace with the Task Channel to fetch </param> /// <param name="pathSid"> The SID of the Task Channel resource to fetch </param> public FetchTaskChannelOptions(string pathWorkspaceSid, string pathSid) { PathWorkspaceSid = pathWorkspaceSid; PathSid = pathSid; } /// <summary> /// Generate the necessary parameters /// </summary> public List<KeyValuePair<string, string>> GetParams() { var p = new List<KeyValuePair<string, string>>(); return p; } } /// <summary> /// ReadTaskChannelOptions /// </summary> public class ReadTaskChannelOptions : ReadOptions<TaskChannelResource> { /// <summary> /// The SID of the Workspace with the Task Channel to read /// </summary> public string PathWorkspaceSid { get; } /// <summary> /// Construct a new ReadTaskChannelOptions /// </summary> /// <param name="pathWorkspaceSid"> The SID of the Workspace with the Task Channel to read </param> public ReadTaskChannelOptions(string pathWorkspaceSid) { PathWorkspaceSid = pathWorkspaceSid; } /// <summary> /// Generate the necessary parameters /// </summary> public override List<KeyValuePair<string, string>> GetParams() { var p = new List<KeyValuePair<string, string>>(); if (PageSize != null) { p.Add(new KeyValuePair<string, string>("PageSize", PageSize.ToString())); } return p; } } /// <summary> /// UpdateTaskChannelOptions /// </summary> public class UpdateTaskChannelOptions : IOptions<TaskChannelResource> { /// <summary> /// The SID of the Workspace with the Task Channel to update /// </summary> public string PathWorkspaceSid { get; } /// <summary> /// The SID of the Task Channel resource to update /// </summary> public string PathSid { get; } /// <summary> /// A string to describe the Task Channel resource /// </summary> public string FriendlyName { get; set; } /// <summary> /// Whether the TaskChannel should prioritize Workers that have been idle /// </summary> public bool? ChannelOptimizedRouting { get; set; } /// <summary> /// Construct a new UpdateTaskChannelOptions /// </summary> /// <param name="pathWorkspaceSid"> The SID of the Workspace with the Task Channel to update </param> /// <param name="pathSid"> The SID of the Task Channel resource to update </param> public UpdateTaskChannelOptions(string pathWorkspaceSid, string pathSid) { PathWorkspaceSid = pathWorkspaceSid; PathSid = pathSid; } /// <summary> /// Generate the necessary parameters /// </summary> public List<KeyValuePair<string, string>> GetParams() { var p = new List<KeyValuePair<string, string>>(); if (FriendlyName != null) { p.Add(new KeyValuePair<string, string>("FriendlyName", FriendlyName)); } if (ChannelOptimizedRouting != null) { p.Add(new KeyValuePair<string, string>("ChannelOptimizedRouting", ChannelOptimizedRouting.Value.ToString().ToLower())); } return p; } } /// <summary> /// DeleteTaskChannelOptions /// </summary> public class DeleteTaskChannelOptions : IOptions<TaskChannelResource> { /// <summary> /// The SID of the Workspace with the Task Channel to delete /// </summary> public string PathWorkspaceSid { get; } /// <summary> /// The SID of the Task Channel resource to delete /// </summary> public string PathSid { get; } /// <summary> /// Construct a new DeleteTaskChannelOptions /// </summary> /// <param name="pathWorkspaceSid"> The SID of the Workspace with the Task Channel to delete </param> /// <param name="pathSid"> The SID of the Task Channel resource to delete </param> public DeleteTaskChannelOptions(string pathWorkspaceSid, string pathSid) { PathWorkspaceSid = pathWorkspaceSid; PathSid = pathSid; } /// <summary> /// Generate the necessary parameters /// </summary> public List<KeyValuePair<string, string>> GetParams() { var p = new List<KeyValuePair<string, string>>(); return p; } } /// <summary> /// CreateTaskChannelOptions /// </summary> public class CreateTaskChannelOptions : IOptions<TaskChannelResource> { /// <summary> /// The SID of the Workspace that the new Task Channel belongs to /// </summary> public string PathWorkspaceSid { get; } /// <summary> /// A string to describe the Task Channel resource /// </summary> public string FriendlyName { get; } /// <summary> /// An application-defined string that uniquely identifies the Task Channel /// </summary> public string UniqueName { get; } /// <summary> /// Whether the Task Channel should prioritize Workers that have been idle /// </summary> public bool? ChannelOptimizedRouting { get; set; } /// <summary> /// Construct a new CreateTaskChannelOptions /// </summary> /// <param name="pathWorkspaceSid"> The SID of the Workspace that the new Task Channel belongs to </param> /// <param name="friendlyName"> A string to describe the Task Channel resource </param> /// <param name="uniqueName"> An application-defined string that uniquely identifies the Task Channel </param> public CreateTaskChannelOptions(string pathWorkspaceSid, string friendlyName, string uniqueName) { PathWorkspaceSid = pathWorkspaceSid; FriendlyName = friendlyName; UniqueName = uniqueName; } /// <summary> /// Generate the necessary parameters /// </summary> public List<KeyValuePair<string, string>> GetParams() { var p = new List<KeyValuePair<string, string>>(); if (FriendlyName != null) { p.Add(new KeyValuePair<string, string>("FriendlyName", FriendlyName)); } if (UniqueName != null) { p.Add(new KeyValuePair<string, string>("UniqueName", UniqueName)); } if (ChannelOptimizedRouting != null) { p.Add(new KeyValuePair<string, string>("ChannelOptimizedRouting", ChannelOptimizedRouting.Value.ToString().ToLower())); } return p; } } }
using System.Diagnostics; using System; using System.Management; using System.Collections; using Microsoft.VisualBasic; using System.Data.SqlClient; using System.Web.UI.Design; using System.Data; using System.Collections.Generic; using System.Linq; namespace ACSGhana.Web.Framework { public sealed class SafeConverters { public const DateTime DEFAULT_DATE = DateTime.Parse("1/1/1753"); public static System.Nullable<DateTime> SafeDate(string Expression) { if (Expression == DBNull.Value) { return null; } else { if (Expression != Constants.vbNullString) { return DateTime.Parse(Expression); } else { return null; } } } public static DateTime SafeDateEx(string Expression) { if (Expression == DBNull.Value || Expression == string.Empty) { return System.Data.SqlTypes.SqlDateTime.Null.Value; } else { DateTime oldDate = DateTime.Parse(Expression); System.Data.SqlTypes.SqlDateTime newDate; if (oldDate < System.Data.SqlTypes.SqlDateTime.MinValue.Value) { newDate = System.Data.SqlTypes.SqlDateTime.MinValue.Value.AddTicks(oldDate.Ticks); } else { newDate = oldDate; } return newDate; } } public static System.Nullable<DateTime> SafeDate2(string Expression) { if (Expression == DBNull.Value) { return null; } else { if (Expression != Constants.vbNullString) { return DateTime.Parse(Expression); } else { return new DateTime(0); } } } public static System.Nullable<short> SafeShort(object Expression) { if (Expression != null) { if (Expression == DBNull.Value) { return - 1; } if (Expression.GetType() == typeof(string)) { if (! string.IsNullOrEmpty(Expression)) { if (Expression is string&& Expression == "Nothing") { return 0; } return System.Convert.ToInt16(Expression); } else { return 0; } } else { return System.Convert.ToInt16(Expression); } } else { return 0; } } public static System.Nullable<int> SafeInteger(object Expression) { if (Expression != null) { if (Expression == DBNull.Value) { return 0; } if (Expression.GetType() == typeof(string)) { if (! string.IsNullOrEmpty(Expression)) { if (Expression is string&& Expression == "Nothing") { return 0; } return System.Convert.ToInt32(Expression); } else { return 0; } } else { return System.Convert.ToInt32(Expression); } } else { return 0; } } public static System.Nullable<long> SafeLong(object Expression) { if (Expression != null) { if (Expression == DBNull.Value) { return 0; } if (Expression.GetType() == typeof(string)) { if (! string.IsNullOrEmpty(Expression)) { if (Expression is string&& Expression == "Nothing") { return 0; } return System.Convert.ToInt32(Expression); } else { return 0; } } else { return System.Convert.ToInt32(Expression); } } else { return 0; } } public static System.Nullable<decimal> SafeDecimal(object Expression) { if (Expression != null) { if (Expression == DBNull.Value) { return 0M; } if (Expression.GetType() == typeof(string)) { if (! string.IsNullOrEmpty(Expression)) { if (Expression is string&& Expression == "Nothing") { return 0M; } return System.Convert.ToDecimal(Expression); } else { return 0M; } } else { return System.Convert.ToDecimal(Expression); } } else { return 0M; } } public static System.Nullable<double> SafeDouble(object Expression) { if (Expression != null) { if (Expression == DBNull.Value) { return 0.0F; } if (Expression.GetType() == typeof(string)) { if (! string.IsNullOrEmpty(Expression)) { if (Expression is string&& Expression == "Nothing") { return 0.0F; } return System.Convert.ToDouble(Expression); } else { return 0.0F; } } else { return System.Convert.ToDouble(Expression); } } else { return 0.0F; } } public static System.Nullable<DateTime> SafeTime(string Expression) { if (Expression != Constants.vbNullString) { DateTime NewTime = DateAndTime.TimeValue(Expression); return DEFAULT_DATE.AddTicks(NewTime.Ticks); } else { return null; } } public static double SafeHours(string Expression) { //On Error Resume Next VBConversions Warning: On Error Resume Next not supported in C# if (Expression != Constants.vbNullString) { if (Expression.Contains(":")) { double timeTotal = 0M; string[] timeSections = Expression.Split(":"); double hours; double minutes; double seconds; if (timeSections.Length > 2) { hours = timeSections[0]; minutes = timeSections[1]; seconds = timeSections[2]; } else { hours = timeSections[0]; minutes = timeSections[1]; } timeTotal = hours + (minutes / 60) + (seconds / 3600); return timeTotal; } else { return double.Parse(Expression); } } else { return null; } } public static double SafeDuration(object Expression) { if (Expression != null) { double DurHrs = Conversion.Fix(Expression); double DurMins = (Expression - Conversion.Fix(Expression)) * 100; if (DurMins > 60) { DurHrs += 1 + ((DurMins - 60) / 100); return DurHrs; } return System.Convert.ToDouble(Expression); } else { return 0M; } } public Function CDBValue<t struct })<t> where t ;: Structure { if (Expression.GetType() == typeof(t)) { return Expression; } else { return ((t) null); } } public string SafeString(object Expression) { if (Expression != null) { if (Expression == System.DBNull.Value) { return Constants.vbNullString; } else { if (Expression is string&& Expression == "Nothing") { return null; } return Expression.ToString(); } } else { return Constants.vbNullString; } } public System.Nullable<bool> SafeBoolean(object Expression) { if (Expression != null) { if (Expression == System.DBNull.Value) { return false; } else { if (Expression is string&& string.IsNullOrEmpty(Expression)) { return false; } if (Expression is string&& Expression == "Nothing") { return false; } return System.Convert.ToBoolean(Expression); } } else { return false; } } } }
#region License /*---------------------------------------------------------------------------------*\ Distributed under the terms of an MIT-style license: The MIT License Copyright (c) 2006-2010 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; namespace JsonFx.Utils { /// <summary> /// Character Utility /// </summary> /// <remarks> /// These are either simpler definitions of character classes (e.g. letter is [a-zA-Z]), /// or they implement platform-agnositic checks (read: "Silverlight workarounds"). /// </remarks> public static class CharUtility { #region Char Methods /// <summary> /// Checks if string is null, empty or entirely made up of whitespace /// </summary> /// <param name="value"></param> /// <returns></returns> /// <remarks> /// Essentially the same as String.IsNullOrWhiteSpace from .NET 4.0 /// with a simplfied view of whitespace. /// </remarks> public static bool IsNullOrWhiteSpace(string value) { if (value != null) { for (int i=0, length=value.Length; i<length; i++) { if (!CharUtility.IsWhiteSpace(value[i])) { return false; } } } return true; } /// <summary> /// Checks if character is line ending, tab or space /// </summary> /// <param name="ch"></param> /// <returns></returns> public static bool IsWhiteSpace(char ch) { return (ch == ' ') || (ch == '\n') || (ch == '\r') || (ch == '\t'); } /// <summary> /// /// </summary> /// <param name="ch"></param> /// <returns></returns> public static bool IsControl(char ch) { return (ch <= '\u001F'); } /// <summary> /// Checks if character matches [A-Za-z] /// </summary> /// <param name="ch"></param> /// <returns></returns> public static bool IsLetter(char ch) { return ((ch >= 'a') && (ch <= 'z')) || ((ch >= 'A') && (ch <= 'Z')); } /// <summary> /// Checks if character matches [0-9] /// </summary> /// <param name="ch"></param> /// <returns></returns> public static bool IsDigit(char ch) { return (ch >= '0') && (ch <= '9'); } /// <summary> /// Checks if character matches [0-9A-Fa-f] /// </summary> /// <param name="ch"></param> /// <returns></returns> public static bool IsHexDigit(char ch) { return (ch >= '0' && ch <= '9') || (ch >= 'A' && ch <= 'F') || (ch >= 'a' && ch <= 'f'); } /// <summary> /// Gets a 4-bit number as a hex digit /// </summary> /// <param name="i">0-15</param> /// <returns></returns> public static char GetHexDigit(int i) { if (i < 10) { return (char)(i + '0'); } return (char)((i - 10) + 'a'); } /// <summary> /// Formats a number as a hex digit /// </summary> /// <param name="i"></param> /// <returns></returns> public static string GetHexString(ulong i) { string hex = ""; while (i > 0) { hex = String.Concat(CharUtility.GetHexDigit((int)(i % 0x10)), hex); i >>= 4; } return hex; } /// <summary> /// Converts the value of a UTF-16 encoded character or surrogate pair at a specified /// position in a string into a Unicode code point. /// </summary> /// <param name="value"></param> /// <param name="i"></param> /// <returns></returns> public static int ConvertToUtf32(string value, int index) { #if SILVERLIGHT return (int)value[index]; #else if (char.IsSurrogate(value, index)) { return ((int)value[index]); } else { return Char.ConvertToUtf32(value, index); } #endif } /// <summary> /// Converts the specified Unicode code point into a UTF-16 encoded string. /// </summary> /// <param name="utf32"></param> /// <returns></returns> public static string ConvertFromUtf32(int utf32) { #if SILVERLIGHT if (utf32 <= 0xFFFF) { return new string((char)utf32, 1); } utf32 -= 0x10000; return new string( new char[] { (char)((utf32 / 0x400) + 0xD800), (char)((utf32 % 0x400) + 0xDC00) }); #else return Char.ConvertFromUtf32(utf32); #endif } #endregion Char Methods } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq.Expressions; using ALinq.Mapping; using ALinq.SqlClient; namespace ALinq.Firebird { class FirebirdSqlFactory : SqlFactory { internal FirebirdSqlFactory(ITypeSystemProvider typeProvider, MetaModel model) : base(typeProvider, model) { } internal override SqlExpression Math_Truncate(SqlMethodCall mc) { return FunctionCall(mc.Method.ReturnType, "TRUNC", mc.Arguments, mc.SourceExpression); } internal override SqlExpression DateTime_Add(SqlMethodCall mc) { SqlExpression arg; if (mc.Arguments[0].NodeType == SqlNodeType.Value) arg = ValueFromObject(((TimeSpan)((SqlValue)mc.Arguments[0]).Value).Ticks / 10000000, true, mc.SourceExpression); else arg = Binary(SqlNodeType.Div, mc.Arguments[0], ValueFromObject(10000000, mc.SourceExpression)); //var arg1 = new FbFunctionArgument(mc.SourceExpression, arg, "SECOND", "TO", mc.Object); var expr = mc.SourceExpression; var args = new[] { arg, VariableFromName("SECOND", expr), VariableFromName("TO", expr), mc.Object }; return FbFunctionCall(mc.ClrType, "DATEADD", args, mc.SourceExpression); } internal override SqlExpression DateTime_Subtract(SqlMethodCall mc) { SqlExpression arg; if (mc.Arguments[0].NodeType == SqlNodeType.Value) arg = ValueFromObject(((TimeSpan)((SqlValue)mc.Arguments[0]).Value).Ticks / 10000000, true, mc.SourceExpression); else arg = Binary(SqlNodeType.Div, mc.Arguments[0], ValueFromObject(10000000, mc.SourceExpression)); arg = Binary(SqlNodeType.Sub, ValueFromObject(0, mc.SourceExpression), arg); var expr = mc.SourceExpression; var args = new[] { arg, VariableFromName("SECOND", expr), VariableFromName("TO", expr), mc.Object }; return FbFunctionCall(mc.ClrType, "DATEADD", args, mc.SourceExpression); } internal SqlFunctionCall FbFunctionCall(Type clrType, string name, IEnumerable<SqlExpression> args, Expression source) { return new SqlFunctionCall(clrType, Default(clrType), name, args, source) { Comma = false }; } //internal static SqlFunctionCall FbFunctionCall(Type clrType, ProviderType sqlType, string name, IEnumerable<SqlExpression> args, Expression source) //{ // return new SqlFunctionCall(clrType, sqlType, name, args, source); //} internal override SqlExpression DateTime_AddDays(SqlMethodCall mc) { //var arg = new FbFunctionArgument(mc.SourceExpression, mc.Arguments[0], "DAY", "TO", mc.Object); //return FunctionCall(mc.ClrType, "DATEADD", new[] { arg }, mc.SourceExpression); var expr = mc.SourceExpression; var args = new[] { mc.Arguments[0], VariableFromName("DAY", expr), VariableFromName("TO", expr), mc.Object }; return FbFunctionCall(mc.ClrType, "DATEADD", args, mc.SourceExpression); } internal override SqlExpression DateTime_AddHours(SqlMethodCall mc) { //var arg = new FbFunctionArgument(mc.SourceExpression, mc.Arguments[0], "HOUR", "TO", mc.Object); var expr = mc.SourceExpression; var args = new[]{ mc.Arguments[0], VariableFromName("HOUR",expr), VariableFromName("TO",expr), mc.Object}; return FbFunctionCall(mc.ClrType, "DATEADD", args, mc.SourceExpression); } internal override SqlExpression DateTime_AddMinutes(SqlMethodCall mc) { var expr = mc.SourceExpression; var args = new[]{ mc.Arguments[0], VariableFromName("MINUTE",expr), VariableFromName("TO",expr), mc.Object}; return FbFunctionCall(mc.ClrType, "DATEADD", args, mc.SourceExpression); } internal override SqlExpression DateTime_AddMonths(SqlMethodCall mc) { var expr = mc.SourceExpression; var args = new[]{ mc.Arguments[0], VariableFromName("MONTH",expr), VariableFromName("TO",expr), mc.Object}; return FbFunctionCall(mc.ClrType, "DATEADD", args, mc.SourceExpression); } internal override SqlExpression DateTime_AddSeconds(SqlMethodCall mc) { var expr = mc.SourceExpression; var args = new[]{ mc.Arguments[0], VariableFromName("SECOND",expr), VariableFromName("TO",expr), mc.Object}; return FbFunctionCall(mc.ClrType, "DATEADD", args, mc.SourceExpression); } internal override SqlExpression DateTime_AddYears(SqlMethodCall mc) { var expr = mc.SourceExpression; var args = new[]{ mc.Arguments[0], VariableFromName("YEAR",expr), VariableFromName("TO",expr), mc.Object}; return FbFunctionCall(mc.ClrType, "DATEADD", args, mc.SourceExpression); } internal override SqlExpression String_Substring(SqlMethodCall mc) { SqlExpression[] args; if (mc.Arguments.Count != 1) { if (mc.Arguments.Count == 2) { var value1 = (int)((SqlValue)mc.Arguments[0]).Value + 1; var value2 = (int)((SqlValue)mc.Arguments[1]).Value; args = new[] { mc.Object, ValueFromObject(value1,mc.SourceExpression), ValueFromObject(value2, mc.SourceExpression) }; //args = new[] { mc.Object, sql.Add(mc.Arguments[0], 1), mc.Arguments[1] }; return FunctionCall(typeof(string), "SUBSTRING", args, mc.SourceExpression); } throw SqlClient.Error.MethodHasNoSupportConversionToSql(mc);//GetMethodSupportException(mc); } var arg = (SqlValue)mc.Arguments[0]; args = new[] { mc.Object, Add(ValueFromObject(arg.Value, arg.SourceExpression), 1), CLRLENGTH(mc.Object) }; return FunctionCall(typeof(string), "SUBSTRING", args, mc.SourceExpression); } internal override SqlExpression String_Insert(SqlMethodCall mc) { var clrType = mc.Method.ReturnType; var startIndex = (int)((SqlValue)mc.Arguments[0]).Value;//(int)((ConstantExpression)mc.Arguments[0]).Value; var insertString = (string)((SqlValue)mc.Arguments[1]).Value;//(string)((ConstantExpression)mc.Arguments[1]).Value; Debug.Assert(clrType == typeof(string)); Debug.Assert(startIndex >= 0); var arg1 = mc.Object;//VisitExpression(mc.Object); var arg2 = ValueFromObject(startIndex, mc.SourceExpression);//VisitExpression(Expression.Constant(startIndex)); var left = new SqlFunctionCall(clrType, TypeProvider.From(clrType), "LEFT", new[] { arg1, arg2 }, mc.SourceExpression); //return left; var result = new SqlBinary(SqlNodeType.Add, typeof(string), TypeProvider.From(typeof(string)), left, ValueFromObject(insertString, mc.SourceExpression)); var len = new SqlFunctionCall(typeof(int), TypeProvider.From(typeof(int)), "CHAR_LENGTH", new[] { (mc.Object) }, mc.SourceExpression); var binary = new SqlBinary(SqlNodeType.Sub, typeof(int), TypeProvider.From(typeof(int)), len, arg2); var right = new SqlFunctionCall(typeof(string), TypeProvider.From(typeof(string)), "RIGHT", new[] { arg1, binary }, mc.SourceExpression); result = new SqlBinary(SqlNodeType.Add, typeof(string), TypeProvider.From(typeof(string)), result, right); return result; } internal override SqlExpression Math_Max(SqlMethodCall mc) { return FunctionCall(mc.ClrType, "MAXVALUE", mc.Arguments, mc.SourceExpression); } internal override SqlExpression Math_Min(SqlMethodCall mc) { return FunctionCall(mc.ClrType, "MINVALUE", mc.Arguments, mc.SourceExpression); } internal override SqlExpression String_Trim(SqlMethodCall mc) { return FunctionCall(mc.ClrType, "TRIM", new[] { mc.Object }, mc.SourceExpression); } internal override SqlExpression String_TrimEnd(SqlMethodCall mc) { //var arg0 = new FbFunctionArgument(mc.SourceExpression, "TRAILING", "From", mc.Object); var expr = mc.SourceExpression; var args = new[] { VariableFromName("TRAILING", expr), VariableFromName("FROM", expr), mc.Object }; return FbFunctionCall(mc.ClrType, "TRIM", args, mc.SourceExpression); } internal override SqlExpression String_TrimStart(SqlMethodCall mc) { var expr = mc.SourceExpression; var args = new[] { VariableFromName("LEADING", expr), VariableFromName("FROM", expr), mc.Object }; return FbFunctionCall(mc.ClrType, "TRIM", args, mc.SourceExpression); } internal override SqlExpression DATEPART(string partName, SqlExpression expr) { //var arg = new FbFunctionArgument(expr.SourceExpression, partName.ToUpper(), "FROM", expr); //return FunctionCall(typeof(int), "EXTRACT", new[] { arg }, expr.SourceExpression); //var args = new[] { new SqlVariable(typeof(void), null, partName.ToUpper(), expr.SourceExpression), expr }; if (partName == "DayOfYear") { partName = "YEARDAY"; var args = new[] { VariableFromName(partName.ToUpper(), expr.SourceExpression), VariableFromName("FROM",expr.SourceExpression) ,expr }; var func = FunctionCall(typeof(int), "EXTRACT", args, expr.SourceExpression); func.Comma = false; return Add(func, 1); } else { var args = new[] { VariableFromName(partName.ToUpper(), expr.SourceExpression), VariableFromName("FROM",expr.SourceExpression) ,expr }; var func = FunctionCall(typeof(int), "EXTRACT", args, expr.SourceExpression); func.Comma = false; return func; } } internal override SqlExpression UNICODE(Type clrType, SqlUnary uo) { return FunctionCall(clrType, TypeProvider.From(typeof(int)), "ASCII_VAL", new[] { uo.Operand }, uo.SourceExpression); } internal override SqlExpression DateTime_DayOfWeek(SqlMember m, SqlExpression expr) { var args = new[] { VariableFromName("WEEKDAY", expr.SourceExpression), VariableFromName("FROM",expr.SourceExpression) ,expr }; var func = FunctionCall(typeof(DayOfWeek), TypeProvider.From(typeof(DayOfWeek)), "EXTRACT", args, expr.SourceExpression); func.Comma = false; return func; } internal override SqlNode DateTime_TimeOfDay(SqlMember member, SqlExpression expr) { var h = DATEPART("Hour", expr); var m = DATEPART("Minute", expr); var s = DATEPART("Second", expr); //var expression11 = DATEPART("MILLISECOND", expr); h = Multiply(h, 0x861c46800L); m = Multiply(m, 0x23c34600L); s = Multiply(s, 0x989680L); //var expression15 = Multiply(ConvertToBigint(expression11), 0x2710L); return ConvertTo(typeof(TimeSpan), Add(new[] { h, m, s })); } internal override SqlExpression MakeCoalesce(SqlExpression left, SqlExpression right, Type type, Expression sourceExpression) { return FunctionCall(type, "COALESCE", new[] { left, right }, sourceExpression); } internal override SqlExpression Math_Log10(SqlMethodCall mc) { Debug.Assert(mc.Arguments.Count == 1); var value = ValueFromObject(10, mc.SourceExpression); mc.Arguments.Insert(0, value); return CreateFunctionCallStatic2(typeof(double), "LOG", mc.Arguments, mc.SourceExpression); } internal override SqlExpression Math_Log(SqlMethodCall mc) { Debug.Assert(mc.Method.Name == "Log"); if (mc.Arguments.Count == 1) { var value = ValueFromObject(Math.E, mc.SourceExpression); mc.Arguments.Insert(0, value); } return CreateFunctionCallStatic2(typeof(double), "LOG", mc.Arguments, mc.SourceExpression); } internal override MethodSupport GetSqlMethodsMethodSupport(SqlMethodCall mc) { if (mc.Method.Name.StartsWith("DateDiff")) return MethodSupport.None; return base.GetSqlMethodsMethodSupport(mc); } internal override MethodSupport GetDateTimeMethodSupport(SqlMethodCall mc) { if (mc.Method.Name == "Subtract") return MethodSupport.Method; return base.GetDateTimeMethodSupport(mc); } } }
// // Copyright (c) Microsoft Corporation. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Management.Automation.Language; using System.Reflection; namespace Microsoft.Windows.PowerShell.ScriptAnalyzer { internal enum SettingsMode { None = 0, Auto, File, Hashtable, Preset }; /// <summary> /// A class to represent the settings provided to ScriptAnalyzer class. /// </summary> public class Settings { private string filePath; private List<string> includeRules; private List<string> excludeRules; private List<string> severities; private Dictionary<string, Dictionary<string, object>> ruleArguments; public string FilePath { get { return filePath; } } public IEnumerable<string> IncludeRules { get { return includeRules; } } public IEnumerable<string> ExcludeRules { get { return excludeRules; } } public IEnumerable<string> Severities { get { return severities; } } public Dictionary<string, Dictionary<string, object>> RuleArguments { get { return ruleArguments; } } /// <summary> /// Create a settings object from the input object. /// </summary> /// <param name="settings">An input object of type Hashtable or string.</param> /// <param name="presetResolver">A function that takes in a preset and resolves it to a path.</param> public Settings(object settings, Func<string, string> presetResolver) { if (settings == null) { throw new ArgumentNullException(nameof(settings)); } includeRules = new List<string>(); excludeRules = new List<string>(); severities = new List<string>(); ruleArguments = new Dictionary<string, Dictionary<string, object>>(StringComparer.OrdinalIgnoreCase); var settingsFilePath = settings as string; //it can either be a preset or path to a file or a hashtable if (settingsFilePath != null) { if (presetResolver != null) { var resolvedFilePath = presetResolver(settingsFilePath); if (resolvedFilePath != null) { settingsFilePath = resolvedFilePath; } } if (File.Exists(settingsFilePath)) { filePath = settingsFilePath; parseSettingsFile(settingsFilePath); } else { throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Strings.InvalidPath, settingsFilePath)); } } else { var settingsHashtable = settings as Hashtable; if (settingsHashtable != null) { parseSettingsHashtable(settingsHashtable); } else { throw new ArgumentException(Strings.SettingsInvalidType); } } } /// <summary> /// Create a Settings object from the input object. /// </summary> /// <param name="settings">An input object of type Hashtable or string.</param> public Settings(object settings) : this(settings, null) { } /// <summary> /// Retrieves the Settings directory from the Module directory structure /// </summary> public static string GetShippedSettingsDirectory() { // Find the compatibility files in Settings folder var path = typeof(Helper).GetTypeInfo().Assembly.Location; if (String.IsNullOrWhiteSpace(path)) { return null; } var settingsPath = Path.Combine(Path.GetDirectoryName(path), "Settings"); if (!Directory.Exists(settingsPath)) { // try one level down as the PSScriptAnalyzer module structure is not consistent // CORECLR binaries are in PSScriptAnalyzer/coreclr/, PowerShell v3 binaries are in PSScriptAnalyzer/PSv3/ // and PowerShell v5 binaries are in PSScriptAnalyzer/ settingsPath = Path.Combine(Path.GetDirectoryName(Path.GetDirectoryName(path)), "Settings"); if (!Directory.Exists(settingsPath)) { return null; } } return settingsPath; } /// <summary> /// Returns the builtin setting presets /// /// Looks for powershell data files (*.psd1) in the PSScriptAnalyzer module settings directory /// and returns the names of the files without extension /// </summary> public static IEnumerable<string> GetSettingPresets() { var settingsPath = GetShippedSettingsDirectory(); if (settingsPath != null) { foreach (var filepath in System.IO.Directory.EnumerateFiles(settingsPath, "*.psd1")) { yield return System.IO.Path.GetFileNameWithoutExtension(filepath); } } } /// <summary> /// Gets the path to the settings file corresponding to the given preset. /// /// If the corresponding preset file is not found, the method returns null. /// </summary> public static string GetSettingPresetFilePath(string settingPreset) { var settingsPath = GetShippedSettingsDirectory(); if (settingsPath != null) { if (GetSettingPresets().Contains(settingPreset, StringComparer.OrdinalIgnoreCase)) { return System.IO.Path.Combine(settingsPath, settingPreset + ".psd1"); } } return null; } /// <summary> /// Create a settings object from an input object. /// </summary> /// <param name="settingsObj">An input object of type Hashtable or string.</param> /// <param name="cwd">The path in which to search for a settings file.</param> /// <param name="outputWriter">An output writer.</param> /// <returns>An object of Settings type.</returns> public static Settings Create(object settingsObj, string cwd, IOutputWriter outputWriter) { object settingsFound; var settingsMode = FindSettingsMode(settingsObj, cwd, out settingsFound); switch (settingsMode) { case SettingsMode.Auto: outputWriter?.WriteVerbose( String.Format( CultureInfo.CurrentCulture, Strings.SettingsNotProvided, "")); outputWriter?.WriteVerbose( String.Format( CultureInfo.CurrentCulture, Strings.SettingsAutoDiscovered, (string)settingsFound)); break; case SettingsMode.Preset: case SettingsMode.File: outputWriter?.WriteVerbose( String.Format( CultureInfo.CurrentCulture, Strings.SettingsUsingFile, (string)settingsFound)); break; case SettingsMode.Hashtable: outputWriter?.WriteVerbose( String.Format( CultureInfo.CurrentCulture, Strings.SettingsUsingHashtable)); break; default: // case SettingsMode.None outputWriter?.WriteVerbose( String.Format( CultureInfo.CurrentCulture, Strings.SettingsCannotFindFile)); break; } if (settingsMode != SettingsMode.None) { return new Settings(settingsFound); } return null; } /// <summary> /// Recursively convert hashtable to dictionary /// </summary> /// <param name="hashtable"></param> /// <returns>Dictionary that maps string to object</returns> private Dictionary<string, object> GetDictionaryFromHashtable(Hashtable hashtable) { var dictionary = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase); foreach (var obj in hashtable.Keys) { string key = obj as string; if (key == null) { throw new InvalidDataException( string.Format( CultureInfo.CurrentCulture, Strings.KeyNotString, key)); } var valueHashtableObj = hashtable[obj]; if (valueHashtableObj == null) { throw new InvalidDataException( string.Format( CultureInfo.CurrentCulture, Strings.WrongValueHashTable, "", key)); } var valueHashtable = valueHashtableObj as Hashtable; if (valueHashtable == null) { dictionary.Add(key, valueHashtableObj); } else { dictionary.Add(key, GetDictionaryFromHashtable(valueHashtable)); } } return dictionary; } private bool IsStringOrStringArray(object val) { if (val is string) { return true; } var valArr = val as object[]; return val == null ? false : valArr.All(x => x is string); } private List<string> GetData(object val, string key) { // value must be either string or or an array of strings if (val == null) { throw new InvalidDataException( string.Format( CultureInfo.CurrentCulture, Strings.WrongValueHashTable, "", key)); } List<string> values = new List<string>(); var valueStr = val as string; if (valueStr != null) { values.Add(valueStr); } else { var valueArr = val as object[]; if (valueArr == null) { // check if it is an array of strings valueArr = val as string[]; } if (valueArr != null) { foreach (var item in valueArr) { var itemStr = item as string; if (itemStr != null) { values.Add(itemStr); } else { throw new InvalidDataException( string.Format( CultureInfo.CurrentCulture, Strings.WrongValueHashTable, val, key)); } } } else { throw new InvalidDataException( string.Format( CultureInfo.CurrentCulture, Strings.WrongValueHashTable, val, key)); } } return values; } /// <summary> /// Sets the arguments for consumption by rules /// </summary> /// <param name="ruleArgs">A hashtable with rule names as keys</param> private Dictionary<string, Dictionary<string, object>> ConvertToRuleArgumentType(object ruleArguments) { var ruleArgs = ruleArguments as Dictionary<string, object>; if (ruleArgs == null) { throw new ArgumentException(Strings.SettingsInputShouldBeDictionary, nameof(ruleArguments)); } if (ruleArgs.Comparer != StringComparer.OrdinalIgnoreCase) { throw new ArgumentException(Strings.SettingsDictionaryShouldBeCaseInsesitive, nameof(ruleArguments)); } var ruleArgsDict = new Dictionary<string, Dictionary<string, object>>(StringComparer.OrdinalIgnoreCase); foreach (var rule in ruleArgs.Keys) { var argsDict = ruleArgs[rule] as Dictionary<string, object>; if (argsDict == null) { throw new InvalidDataException(Strings.SettingsInputShouldBeDictionary); } ruleArgsDict[rule] = argsDict; } return ruleArgsDict; } private void parseSettingsHashtable(Hashtable settingsHashtable) { HashSet<string> validKeys = new HashSet<string>(StringComparer.OrdinalIgnoreCase); var settings = GetDictionaryFromHashtable(settingsHashtable); foreach (var settingKey in settings.Keys) { var key = settingKey.ToLower(); object val = settings[key]; switch (key) { case "severity": severities = GetData(val, key); break; case "includerules": includeRules = GetData(val, key); break; case "excluderules": excludeRules = GetData(val, key); break; case "rules": try { ruleArguments = ConvertToRuleArgumentType(val); } catch (ArgumentException argumentException) { throw new InvalidDataException( string.Format(CultureInfo.CurrentCulture, Strings.WrongValueHashTable, "", key), argumentException); } break; default: throw new InvalidDataException( string.Format( CultureInfo.CurrentCulture, Strings.WrongKeyHashTable, key)); } } } private void parseSettingsFile(string settingsFilePath) { Token[] parserTokens = null; ParseError[] parserErrors = null; Ast profileAst = Parser.ParseFile(settingsFilePath, out parserTokens, out parserErrors); IEnumerable<Ast> hashTableAsts = profileAst.FindAll(item => item is HashtableAst, false); // no hashtable, raise warning if (hashTableAsts.Count() == 0) { throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Strings.InvalidProfile, settingsFilePath)); } HashtableAst hashTableAst = hashTableAsts.First() as HashtableAst; Hashtable hashtable; try { // ideally we should use HashtableAst.SafeGetValue() but since // it is not available on PSv3, we resort to our own narrow implementation. hashtable = GetHashtableFromHashTableAst(hashTableAst); } catch (InvalidOperationException e) { throw new ArgumentException(Strings.InvalidProfile, e); } if (hashtable == null) { throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Strings.InvalidProfile, settingsFilePath)); } parseSettingsHashtable(hashtable); } private Hashtable GetHashtableFromHashTableAst(HashtableAst hashTableAst) { var output = new Hashtable(); foreach (var kvp in hashTableAst.KeyValuePairs) { var keyAst = kvp.Item1 as StringConstantExpressionAst; if (keyAst == null) { // first item (the key) should be a string ThrowInvalidDataException(kvp.Item1); } var key = keyAst.Value; // parse the item2 as array PipelineAst pipeAst = kvp.Item2 as PipelineAst; List<string> rhsList = new List<string>(); if (pipeAst != null) { ExpressionAst pureExp = pipeAst.GetPureExpression(); var constExprAst = pureExp as ConstantExpressionAst; if (constExprAst != null) { var strConstExprAst = constExprAst as StringConstantExpressionAst; if (strConstExprAst != null) { // it is a string literal output[key] = strConstExprAst.Value; } else { // it is either an integer or a float output[key] = constExprAst.Value; } continue; } else if (pureExp is HashtableAst) { output[key] = GetHashtableFromHashTableAst((HashtableAst)pureExp); continue; } else if (pureExp is VariableExpressionAst) { var varExprAst = (VariableExpressionAst)pureExp; switch (varExprAst.VariablePath.UserPath.ToLower()) { case "true": output[key] = true; break; case "false": output[key] = false; break; default: ThrowInvalidDataException(varExprAst.Extent); break; } continue; } else { rhsList = GetArrayFromAst(pureExp); } } if (rhsList.Count == 0) { ThrowInvalidDataException(kvp.Item2); } output[key] = rhsList.ToArray(); } return output; } private List<string> GetArrayFromAst(ExpressionAst exprAst) { ArrayLiteralAst arrayLitAst = exprAst as ArrayLiteralAst; var result = new List<string>(); if (arrayLitAst == null && exprAst is ArrayExpressionAst) { ArrayExpressionAst arrayExp = (ArrayExpressionAst)exprAst; return arrayExp == null ? null : GetArrayFromArrayExpressionAst(arrayExp); } if (arrayLitAst == null) { ThrowInvalidDataException(arrayLitAst); } foreach (var element in arrayLitAst.Elements) { var elementValue = element as StringConstantExpressionAst; if (elementValue == null) { ThrowInvalidDataException(element); } result.Add(elementValue.Value); } return result; } private List<string> GetArrayFromArrayExpressionAst(ArrayExpressionAst arrayExp) { var result = new List<string>(); if (arrayExp.SubExpression != null) { StatementAst stateAst = arrayExp.SubExpression.Statements.FirstOrDefault(); if (stateAst != null && stateAst is PipelineAst) { CommandBaseAst cmdBaseAst = (stateAst as PipelineAst).PipelineElements.FirstOrDefault(); if (cmdBaseAst != null && cmdBaseAst is CommandExpressionAst) { CommandExpressionAst cmdExpAst = cmdBaseAst as CommandExpressionAst; if (cmdExpAst.Expression is StringConstantExpressionAst) { return new List<string>() { (cmdExpAst.Expression as StringConstantExpressionAst).Value }; } else { // It should be an ArrayLiteralAst at this point return GetArrayFromAst(cmdExpAst.Expression); } } } } return null; } private void ThrowInvalidDataException(Ast ast) { ThrowInvalidDataException(ast.Extent); } private void ThrowInvalidDataException(IScriptExtent extent) { throw new InvalidDataException(string.Format( CultureInfo.CurrentCulture, Strings.WrongValueFormat, extent.StartLineNumber, extent.StartColumnNumber, extent.File ?? "")); } private static bool IsBuiltinSettingPreset(object settingPreset) { var preset = settingPreset as string; if (preset != null) { return GetSettingPresets().Contains(preset, StringComparer.OrdinalIgnoreCase); } return false; } internal static SettingsMode FindSettingsMode(object settings, string path, out object settingsFound) { var settingsMode = SettingsMode.None; settingsFound = settings; if (settingsFound == null) { if (path != null) { // add a directory separator character because if there is no trailing separator character, it will return the parent var directory = path.TrimEnd(System.IO.Path.DirectorySeparatorChar); if (File.Exists(directory)) { // if given path is a file, get its directory directory = Path.GetDirectoryName(directory); } if (Directory.Exists(directory)) { // if settings are not provided explicitly, look for it in the given path // check if pssasettings.psd1 exists var settingsFilename = "PSScriptAnalyzerSettings.psd1"; var settingsFilePath = Path.Combine(directory, settingsFilename); settingsFound = settingsFilePath; if (File.Exists(settingsFilePath)) { settingsMode = SettingsMode.Auto; } } } } else { var settingsFilePath = settingsFound as String; if (settingsFilePath != null) { if (IsBuiltinSettingPreset(settingsFilePath)) { settingsMode = SettingsMode.Preset; settingsFound = GetSettingPresetFilePath(settingsFilePath); } else { settingsMode = SettingsMode.File; settingsFound = settingsFilePath; } } else { if (settingsFound is Hashtable) { settingsMode = SettingsMode.Hashtable; } } } return settingsMode; } } }
/* * 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.Collections.Generic; using System.Reflection; using log4net; using OpenMetaverse; using OpenSim.Services.Interfaces; namespace OpenSim.Framework.Communications.Cache { /// <summary> /// Holds user profile information and retrieves it from backend services. /// </summary> public class UserProfileCacheService { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); /// <value> /// Standard format for names. /// </value> public const string NAME_FORMAT = "{0} {1}"; /// <summary> /// The comms manager holds references to services (user, grid, inventory, etc.) /// </summary> private readonly CommunicationsManager m_commsManager; /// <summary> /// User profiles indexed by UUID /// </summary> private readonly Dictionary<UUID, CachedUserInfo> m_userProfilesById = new Dictionary<UUID, CachedUserInfo>(); /// <summary> /// User profiles indexed by name /// </summary> private readonly Dictionary<string, CachedUserInfo> m_userProfilesByName = new Dictionary<string, CachedUserInfo>(); /// <summary> /// The root library folder. /// </summary> public readonly InventoryFolderImpl LibraryRoot; private IInventoryService m_InventoryService; /// <summary> /// Constructor /// </summary> /// <param name="commsManager"></param> /// <param name="libraryRootFolder"></param> public UserProfileCacheService(CommunicationsManager commsManager, LibraryRootFolder libraryRootFolder) { m_commsManager = commsManager; LibraryRoot = libraryRootFolder; } public void SetInventoryService(IInventoryService invService) { m_InventoryService = invService; } /// <summary> /// A new user has moved into a region in this instance so retrieve their profile from the user service. /// </summary> /// /// It isn't strictly necessary to make this call since user data can be lazily requested later on. However, /// it might be helpful in order to avoid an initial response delay later on /// /// <param name="userID"></param> public void AddNewUser(UUID userID) { if (userID == UUID.Zero) return; //m_log.DebugFormat("[USER CACHE]: Adding user profile for {0}", userID); GetUserDetails(userID); } /// <summary> /// Remove this user's profile cache. /// </summary> /// <param name="userID"></param> /// <returns>true if the user was successfully removed, false otherwise</returns> public bool RemoveUser(UUID userId) { if (!RemoveFromCaches(userId)) { m_log.WarnFormat( "[USER CACHE]: Tried to remove the profile of user {0}, but this was not in the scene", userId); return false; } return true; } /// <summary> /// Get details of the given user. /// </summary> /// If the user isn't in cache then the user is requested from the profile service. /// <param name="userID"></param> /// <returns>null if no user details are found</returns> public CachedUserInfo GetUserDetails(string fname, string lname) { lock (m_userProfilesByName) { CachedUserInfo userInfo; if (m_userProfilesByName.TryGetValue(string.Format(NAME_FORMAT, fname, lname), out userInfo)) { return userInfo; } else { UserProfileData userProfile = m_commsManager.UserService.GetUserProfile(fname, lname); if (userProfile != null) { if ((userProfile.UserAssetURI == null || userProfile.UserAssetURI == "") && m_commsManager.NetworkServersInfo != null) userProfile.UserAssetURI = m_commsManager.NetworkServersInfo.AssetURL; if ((userProfile.UserInventoryURI == null || userProfile.UserInventoryURI == "") && m_commsManager.NetworkServersInfo != null) userProfile.UserInventoryURI = m_commsManager.NetworkServersInfo.InventoryURL; return AddToCaches(userProfile); } else return null; } } } /// <summary> /// Get details of the given user. /// </summary> /// If the user isn't in cache then the user is requested from the profile service. /// <param name="userID"></param> /// <returns>null if no user details are found</returns> public CachedUserInfo GetUserDetails(UUID userID) { if (userID == UUID.Zero) return null; lock (m_userProfilesById) { if (m_userProfilesById.ContainsKey(userID)) { return m_userProfilesById[userID]; } else { UserProfileData userProfile = m_commsManager.UserService.GetUserProfile(userID); if (userProfile != null) { if ((userProfile.UserAssetURI == null || userProfile.UserAssetURI == "") && m_commsManager.NetworkServersInfo != null) userProfile.UserAssetURI = m_commsManager.NetworkServersInfo.AssetURL; if ((userProfile.UserInventoryURI == null || userProfile.UserInventoryURI == "") && m_commsManager.NetworkServersInfo != null) userProfile.UserInventoryURI = m_commsManager.NetworkServersInfo.InventoryURL; return AddToCaches(userProfile); } else return null; } } } /// <summary> /// Update an existing profile /// </summary> /// <param name="userProfile"></param> /// <returns>true if a user profile was found to update, false otherwise</returns> // Commented out for now. The implementation needs to be improved by protecting against race conditions, // probably by making sure that the update doesn't use the UserCacheInfo.UserProfile directly (possibly via // returning a read only class from the cache). // public bool StoreProfile(UserProfileData userProfile) // { // lock (m_userProfilesById) // { // CachedUserInfo userInfo = GetUserDetails(userProfile.ID); // // if (userInfo != null) // { // userInfo.m_userProfile = userProfile; // m_commsManager.UserService.UpdateUserProfile(userProfile); // // return true; // } // } // // return false; // } /// <summary> /// Populate caches with the given user profile /// </summary> /// <param name="userProfile"></param> protected CachedUserInfo AddToCaches(UserProfileData userProfile) { CachedUserInfo createdUserInfo = new CachedUserInfo(m_InventoryService, userProfile); lock (m_userProfilesById) { m_userProfilesById[createdUserInfo.UserProfile.ID] = createdUserInfo; lock (m_userProfilesByName) { m_userProfilesByName[createdUserInfo.UserProfile.Name] = createdUserInfo; } } return createdUserInfo; } /// <summary> /// Remove profile belong to the given uuid from the caches /// </summary> /// <param name="userUuid"></param> /// <returns>true if there was a profile to remove, false otherwise</returns> protected bool RemoveFromCaches(UUID userId) { lock (m_userProfilesById) { if (m_userProfilesById.ContainsKey(userId)) { CachedUserInfo userInfo = m_userProfilesById[userId]; m_userProfilesById.Remove(userId); lock (m_userProfilesByName) { m_userProfilesByName.Remove(userInfo.UserProfile.Name); } return true; } } return false; } /// <summary> /// Preloads User data into the region cache. Modules may use this service to add non-standard clients /// </summary> /// <param name="userData"></param> public void PreloadUserCache(UserProfileData userData) { AddToCaches(userData); } } }
// 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.Collections.Generic; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.Formatting; using Microsoft.CodeAnalysis.Editor.Implementation.AutomaticCompletion; using Microsoft.CodeAnalysis.Editor.Shared.Options; using Microsoft.CodeAnalysis.Editor.UnitTests.AutomaticCompletion; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Options; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.AutomaticCompletion { public class AutomaticBraceCompletionTests : AbstractAutomaticBraceCompletionTests { [WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)] public async Task Creation() { using (var session = await CreateSessionAsync("$$")) { Assert.NotNull(session); } } [WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)] public async Task InvalidLocation_String() { var code = @"class C { string s = ""$$ }"; using (var session = await CreateSessionAsync(code)) { Assert.Null(session); } } [WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)] public async Task InvalidLocation_String2() { var code = @"class C { string s = @"" $$ }"; using (var session = await CreateSessionAsync(code)) { Assert.Null(session); } } [WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)] public async Task ValidLocation_InterpolatedString1() { var code = @"class C { string s = $""$$ }"; using (var session = await CreateSessionAsync(code)) { Assert.NotNull(session); CheckStart(session.Session); } } [WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)] public async Task ValidLocation_InterpolatedString2() { var code = @"class C { string s = $@""$$ }"; using (var session = await CreateSessionAsync(code)) { Assert.NotNull(session); CheckStart(session.Session); } } [WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)] public async Task ValidLocation_InterpolatedString3() { var code = @"class C { string x = ""foo"" string s = $""{x} $$ }"; using (var session = await CreateSessionAsync(code)) { Assert.NotNull(session); CheckStart(session.Session); } } [WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)] public async Task ValidLocation_InterpolatedString4() { var code = @"class C { string x = ""foo"" string s = $@""{x} $$ }"; using (var session = await CreateSessionAsync(code)) { Assert.NotNull(session); CheckStart(session.Session); } } [WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)] public async Task ValidLocation_InterpolatedString5() { var code = @"class C { string s = $""{{$$ }"; using (var session = await CreateSessionAsync(code)) { Assert.NotNull(session); CheckStart(session.Session); } } [WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)] public async Task ValidLocation_InterpolatedString6() { var code = @"class C { string s = $""{}$$ }"; using (var session = await CreateSessionAsync(code)) { Assert.NotNull(session); CheckStart(session.Session); } } [WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)] public async Task InvalidLocation_InterpolatedString1() { var code = @"class C { string s = @""$$ }"; using (var session = await CreateSessionAsync(code)) { Assert.Null(session); } } [WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)] public async Task InvalidLocation_InterpolatedString2() { var code = @"class C { string s = ""$$ }"; using (var session = await CreateSessionAsync(code)) { Assert.Null(session); } } [WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)] public async Task InvalidLocation_Comment() { var code = @"class C { //$$ }"; using (var session = await CreateSessionAsync(code)) { Assert.Null(session); } } [WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)] public async Task InvalidLocation_Comment2() { var code = @"class C { /* $$ }"; using (var session = await CreateSessionAsync(code)) { Assert.Null(session); } } [WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)] public async Task InvalidLocation_Comment3() { var code = @"class C { /// $$ }"; using (var session = await CreateSessionAsync(code)) { Assert.Null(session); } } [WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)] public async Task InvalidLocation_Comment4() { var code = @"class C { /** $$ }"; using (var session = await CreateSessionAsync(code)) { Assert.Null(session); } } [WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)] public async Task MultiLine_Comment() { var code = @"class C { void Method() { /* */$$ } }"; using (var session = await CreateSessionAsync(code)) { Assert.NotNull(session); CheckStart(session.Session); } } [WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)] public async Task MultiLine_DocComment() { var code = @"class C { void Method() { /** */$$ } }"; using (var session = await CreateSessionAsync(code)) { Assert.NotNull(session); CheckStart(session.Session); } } [WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)] public async Task String1() { var code = @"class C { void Method() { var s = """"$$ } }"; using (var session = await CreateSessionAsync(code)) { Assert.NotNull(session); CheckStart(session.Session); } } [WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)] public async Task String2() { var code = @"class C { void Method() { var s = @""""$$ } }"; using (var session = await CreateSessionAsync(code)) { Assert.NotNull(session); CheckStart(session.Session); } } [WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)] public async Task Class_OpenBrace() { var code = @"class C $$"; using (var session = await CreateSessionAsync(code)) { Assert.NotNull(session); CheckStart(session.Session); } } [WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)] public async Task Class_Delete() { var code = @"class C $$"; using (var session = await CreateSessionAsync(code)) { Assert.NotNull(session); CheckStart(session.Session); CheckBackspace(session.Session); } } [WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)] public async Task Class_Tab() { var code = @"class C $$"; using (var session = await CreateSessionAsync(code)) { Assert.NotNull(session); CheckStart(session.Session); CheckTab(session.Session); } } [WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)] public async Task Class_CloseBrace() { var code = @"class C $$"; using (var session = await CreateSessionAsync(code)) { Assert.NotNull(session); CheckStart(session.Session); CheckOverType(session.Session); } } [WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)] public async Task Method_OpenBrace_Multiple() { var code = @"class C { void Method() { $$ }"; using (var session = await CreateSessionAsync(code)) { Assert.NotNull(session); CheckStart(session.Session); } } [WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)] public async Task Class_OpenBrace_Enter() { var code = @"class C $$"; using (var session = await CreateSessionAsync(code)) { Assert.NotNull(session); CheckStart(session.Session); CheckReturn(session.Session, 4); } } [WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)] public async Task Class_ObjectInitializer_OpenBrace_Enter() { var code = @"using System.Collections.Generic; class C { List<C> list = new List<C> { new C $$ }; }"; var expected = @"using System.Collections.Generic; class C { List<C> list = new List<C> { new C { } }; }"; using (var session = await CreateSessionAsync(code)) { Assert.NotNull(session); CheckStart(session.Session); CheckReturn(session.Session, 12, expected); } } [WorkItem(1070773, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1070773")] [WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)] public async Task Collection_Initializer_OpenBraceOnSameLine_Enter() { var code = @"using System.Collections.Generic; class C { public void man() { List<C> list = new List<C> $$ } }"; var expected = @"using System.Collections.Generic; class C { public void man() { List<C> list = new List<C> { } } }"; var optionSet = new Dictionary<OptionKey, object> { { CSharpFormattingOptions.NewLinesForBracesInObjectCollectionArrayInitializers, false } }; using (var session = await CreateSessionAsync(code, optionSet)) { Assert.NotNull(session); CheckStart(session.Session); CheckReturn(session.Session, 12, expected); } } [WorkItem(1070773, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1070773")] [WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)] public async Task Collection_Initializer_OpenBraceOnDifferentLine_Enter() { var code = @"using System.Collections.Generic; class C { public void man() { List<C> list = new List<C> $$ } }"; var expected = @"using System.Collections.Generic; class C { public void man() { List<C> list = new List<C> { } } }"; using (var session = await CreateSessionAsync(code)) { Assert.NotNull(session); CheckStart(session.Session); CheckReturn(session.Session, 12, expected); } } [WorkItem(1070773, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1070773")] [WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)] public async Task Object_Initializer_OpenBraceOnSameLine_Enter() { var code = @"class C { public void man() { var foo = new Foo $$ } } class Foo { public int bar; }"; var expected = @"class C { public void man() { var foo = new Foo { } } } class Foo { public int bar; }"; var optionSet = new Dictionary<OptionKey, object> { { CSharpFormattingOptions.NewLinesForBracesInObjectCollectionArrayInitializers, false } }; using (var session = await CreateSessionAsync(code, optionSet)) { Assert.NotNull(session); CheckStart(session.Session); CheckReturn(session.Session, 12, expected); } } [WorkItem(1070773, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1070773")] [WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)] public async Task Object_Initializer_OpenBraceOnDifferentLine_Enter() { var code = @"class C { public void man() { var foo = new Foo $$ } } class Foo { public int bar; }"; var expected = @"class C { public void man() { var foo = new Foo { } } } class Foo { public int bar; }"; using (var session = await CreateSessionAsync(code)) { Assert.NotNull(session); CheckStart(session.Session); CheckReturn(session.Session, 12, expected); } } [WorkItem(1070773, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1070773")] [WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)] public async Task ArrayImplicit_Initializer_OpenBraceOnSameLine_Enter() { var code = @"class C { public void man() { int[] arr = $$ } }"; var expected = @"class C { public void man() { int[] arr = { } } }"; var optionSet = new Dictionary<OptionKey, object> { { CSharpFormattingOptions.NewLinesForBracesInObjectCollectionArrayInitializers, false } }; using (var session = await CreateSessionAsync(code, optionSet)) { Assert.NotNull(session); CheckStart(session.Session); CheckReturn(session.Session, 12, expected); } } [WorkItem(1070773, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1070773")] [WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)] public async Task ArrayImplicit_Initializer_OpenBraceOnDifferentLine_Enter() { var code = @"class C { public void man() { int[] arr = $$ } }"; var expected = @"class C { public void man() { int[] arr = { } } }"; using (var session = await CreateSessionAsync(code)) { Assert.NotNull(session); CheckStart(session.Session); CheckReturn(session.Session, 12, expected); } } [WorkItem(1070773, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1070773")] [WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)] public async Task ArrayExplicit1_Initializer_OpenBraceOnSameLine_Enter() { var code = @"class C { public void man() { int[] arr = new[] $$ } }"; var expected = @"class C { public void man() { int[] arr = new[] { } } }"; var optionSet = new Dictionary<OptionKey, object> { { CSharpFormattingOptions.NewLinesForBracesInObjectCollectionArrayInitializers, false } }; using (var session = await CreateSessionAsync(code, optionSet)) { Assert.NotNull(session); CheckStart(session.Session); CheckReturn(session.Session, 12, expected); } } [WorkItem(1070773, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1070773")] [WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)] public async Task ArrayExplicit1_Initializer_OpenBraceOnDifferentLine_Enter() { var code = @"class C { public void man() { int[] arr = new[] $$ } }"; var expected = @"class C { public void man() { int[] arr = new[] { } } }"; using (var session = await CreateSessionAsync(code)) { Assert.NotNull(session); CheckStart(session.Session); CheckReturn(session.Session, 12, expected); } } [WorkItem(1070773, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1070773")] [WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)] public async Task ArrayExplicit2_Initializer_OpenBraceOnSameLine_Enter() { var code = @"class C { public void man() { int[] arr = new int[] $$ } }"; var expected = @"class C { public void man() { int[] arr = new int[] { } } }"; var optionSet = new Dictionary<OptionKey, object> { { CSharpFormattingOptions.NewLinesForBracesInObjectCollectionArrayInitializers, false } }; using (var session = await CreateSessionAsync(code, optionSet)) { Assert.NotNull(session); CheckStart(session.Session); CheckReturn(session.Session, 12, expected); } } [WorkItem(1070773, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1070773")] [WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)] public async Task ArrayExplicit2_Initializer_OpenBraceOnDifferentLine_Enter() { var code = @"class C { public void man() { int[] arr = new int[] $$ } }"; var expected = @"class C { public void man() { int[] arr = new int[] { } } }"; using (var session = await CreateSessionAsync(code)) { Assert.NotNull(session); CheckStart(session.Session); CheckReturn(session.Session, 12, expected); } } [WorkItem(3447, "https://github.com/dotnet/roslyn/issues/3447")] [WorkItem(850540, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850540")] [WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)] public async Task BlockIndentationWithAutomaticBraceFormattingDisabled() { var code = @"class C { public void X() $$ }"; var expected = @"class C { public void X() {} }"; var expectedAfterReturn = @"class C { public void X() { } }"; var optionSet = new Dictionary<OptionKey, object> { { new OptionKey(FeatureOnOffOptions.AutoFormattingOnCloseBrace, LanguageNames.CSharp), false }, { new OptionKey(FormattingOptions.SmartIndent, LanguageNames.CSharp), FormattingOptions.IndentStyle.Block } }; using (var session = await CreateSessionAsync(code, optionSet)) { Assert.NotNull(session); CheckStart(session.Session); Assert.Equal(expected, session.Session.SubjectBuffer.CurrentSnapshot.GetText()); CheckReturn(session.Session, 4, expectedAfterReturn); } } [WorkItem(2224, "https://github.com/dotnet/roslyn/issues/2224")] [WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)] public async Task NoSmartOrBlockIndentationWithAutomaticBraceFormattingDisabled() { var code = @"namespace NS1 { public class C1 $$ }"; var expected = @"namespace NS1 { public class C1 { } }"; var optionSet = new Dictionary<OptionKey, object> { { new OptionKey(FormattingOptions.SmartIndent, LanguageNames.CSharp), FormattingOptions.IndentStyle.None } }; using (var session = await CreateSessionAsync(code, optionSet)) { Assert.NotNull(session); CheckStart(session.Session); Assert.Equal(expected, session.Session.SubjectBuffer.CurrentSnapshot.GetText()); } } [WorkItem(2330, "https://github.com/dotnet/roslyn/issues/2330")] [WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)] public async Task BlockIndentationWithAutomaticBraceFormatting() { var code = @"namespace NS1 { public class C1 $$ }"; var expected = @"namespace NS1 { public class C1 { } }"; var expectedAfterReturn = @"namespace NS1 { public class C1 { } }"; var optionSet = new Dictionary<OptionKey, object> { { new OptionKey(FormattingOptions.SmartIndent, LanguageNames.CSharp), FormattingOptions.IndentStyle.Block } }; using (var session = await CreateSessionAsync(code, optionSet)) { Assert.NotNull(session); CheckStart(session.Session); Assert.Equal(expected, session.Session.SubjectBuffer.CurrentSnapshot.GetText()); CheckReturn(session.Session, 8, expectedAfterReturn); } } [WorkItem(2330, "https://github.com/dotnet/roslyn/issues/2330")] [WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)] public async Task BlockIndentationWithAutomaticBraceFormattingSecondSet() { var code = @"namespace NS1 { public class C1 { public class C2 $$ } }"; var expected = @"namespace NS1 { public class C1 { public class C2 { } } }"; var expectedAfterReturn = @"namespace NS1 { public class C1 { public class C2 { } } }"; var optionSet = new Dictionary<OptionKey, object> { { new OptionKey(FormattingOptions.SmartIndent, LanguageNames.CSharp), FormattingOptions.IndentStyle.Block } }; using (var session = await CreateSessionAsync(code, optionSet)) { Assert.NotNull(session); CheckStart(session.Session); Assert.Equal(expected, session.Session.SubjectBuffer.CurrentSnapshot.GetText()); CheckReturn(session.Session, 8, expectedAfterReturn); } } internal async Task<Holder> CreateSessionAsync(string code, Dictionary<OptionKey, object> optionSet = null) { return CreateSession( await TestWorkspace.CreateCSharpAsync(code), BraceCompletionSessionProvider.CurlyBrace.OpenCharacter, BraceCompletionSessionProvider.CurlyBrace.CloseCharacter, optionSet); } } }
/* * Farseer Physics Engine: * Copyright (c) 2012 Ian Qvist * * Original source Box2D: * Copyright (c) 2006-2011 Erin Catto http://www.box2d.org * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. */ using System.Diagnostics; using Astrid.Core; using Astrid.FarseerPhysics.Common; namespace Astrid.FarseerPhysics.Dynamics.Joints { // p = attached point, m = mouse point // C = p - m // Cdot = v // = v + cross(w, r) // J = [I r_skew] // Identity used: // w k % (rx i + ry j) = w * (-ry i + rx j) /// <summary> /// A mouse joint is used to make a point on a body track a /// specified world point. This a soft constraint with a maximum /// force. This allows the constraint to stretch and without /// applying huge forces. /// NOTE: this joint is not documented in the manual because it was /// developed to be used in the testbed. If you want to learn how to /// use the mouse joint, look at the testbed. /// </summary> public class FixedMouseJoint : Joint { private Vector2 _worldAnchor; private float _frequency; private float _dampingRatio; private float _beta; // Solver shared private Vector2 _impulse; private float _maxForce; private float _gamma; // Solver temp private int _indexA; private Vector2 _rA; private Vector2 _localCenterA; private float _invMassA; private float _invIA; private Mat22 _mass; private Vector2 _C; /// <summary> /// This requires a world target point, /// tuning parameters, and the time step. /// </summary> /// <param name="body">The body.</param> /// <param name="worldAnchor">The target.</param> public FixedMouseJoint(Body body, Vector2 worldAnchor) : base(body) { JointType = JointType.FixedMouse; Frequency = 5.0f; DampingRatio = 0.7f; MaxForce = 1000 * body.Mass; Debug.Assert(worldAnchor.IsValid()); _worldAnchor = worldAnchor; LocalAnchorA = MathUtils.MulT(BodyA._xf, worldAnchor); } /// <summary> /// The local anchor point on BodyA /// </summary> public Vector2 LocalAnchorA { get; set; } public override Vector2 WorldAnchorA { get { return BodyA.GetWorldPoint(LocalAnchorA); } set { LocalAnchorA = BodyA.GetLocalPoint(value); } } public override Vector2 WorldAnchorB { get { return _worldAnchor; } set { WakeBodies(); _worldAnchor = value; } } /// <summary> /// The maximum constraint force that can be exerted /// to move the candidate body. Usually you will express /// as some multiple of the weight (multiplier * mass * gravity). /// </summary> public float MaxForce { get { return _maxForce; } set { Debug.Assert(MathUtils.IsValid(value) && value >= 0.0f); _maxForce = value; } } /// <summary> /// The response speed. /// </summary> public float Frequency { get { return _frequency; } set { Debug.Assert(MathUtils.IsValid(value) && value >= 0.0f); _frequency = value; } } /// <summary> /// The damping ratio. 0 = no damping, 1 = critical damping. /// </summary> public float DampingRatio { get { return _dampingRatio; } set { Debug.Assert(MathUtils.IsValid(value) && value >= 0.0f); _dampingRatio = value; } } public override Vector2 GetReactionForce(float invDt) { return invDt * _impulse; } public override float GetReactionTorque(float invDt) { return invDt * 0.0f; } internal override void InitVelocityConstraints(ref SolverData data) { _indexA = BodyA.IslandIndex; _localCenterA = BodyA._sweep.LocalCenter; _invMassA = BodyA._invMass; _invIA = BodyA._invI; Vector2 cA = data.positions[_indexA].c; float aA = data.positions[_indexA].a; Vector2 vA = data.velocities[_indexA].v; float wA = data.velocities[_indexA].w; Rot qA = new Rot(aA); float mass = BodyA.Mass; // Frequency float omega = 2.0f * Settings.Pi * Frequency; // Damping coefficient float d = 2.0f * mass * DampingRatio * omega; // Spring stiffness float k = mass * (omega * omega); // magic formulas // gamma has units of inverse mass. // beta has units of inverse time. float h = data.step.dt; Debug.Assert(d + h * k > Settings.Epsilon); _gamma = h * (d + h * k); if (_gamma != 0.0f) { _gamma = 1.0f / _gamma; } _beta = h * k * _gamma; // Compute the effective mass matrix. _rA = MathUtils.Mul(qA, LocalAnchorA - _localCenterA); // K = [(1/m1 + 1/m2) * eye(2) - skew(r1) * invI1 * skew(r1) - skew(r2) * invI2 * skew(r2)] // = [1/m1+1/m2 0 ] + invI1 * [r1.Y*r1.Y -r1.X*r1.Y] + invI2 * [r1.Y*r1.Y -r1.X*r1.Y] // [ 0 1/m1+1/m2] [-r1.X*r1.Y r1.X*r1.X] [-r1.X*r1.Y r1.X*r1.X] Mat22 K = new Mat22(); K.ex.X = _invMassA + _invIA * _rA.Y * _rA.Y + _gamma; K.ex.Y = -_invIA * _rA.X * _rA.Y; K.ey.X = K.ex.Y; K.ey.Y = _invMassA + _invIA * _rA.X * _rA.X + _gamma; _mass = K.Inverse; _C = cA + _rA - _worldAnchor; _C *= _beta; // Cheat with some damping wA *= 0.98f; if (Settings.EnableWarmstarting) { _impulse *= data.step.dtRatio; vA += _invMassA * _impulse; wA += _invIA * MathUtils.Cross(_rA, _impulse); } else { _impulse = Vector2.Zero; } data.velocities[_indexA].v = vA; data.velocities[_indexA].w = wA; } internal override void SolveVelocityConstraints(ref SolverData data) { Vector2 vA = data.velocities[_indexA].v; float wA = data.velocities[_indexA].w; // Cdot = v + cross(w, r) Vector2 Cdot = vA + MathUtils.Cross(wA, _rA); Vector2 impulse = MathUtils.Mul(ref _mass, -(Cdot + _C + _gamma * _impulse)); Vector2 oldImpulse = _impulse; _impulse += impulse; float maxImpulse = data.step.dt * MaxForce; if (_impulse.LengthSquared() > maxImpulse * maxImpulse) { _impulse *= maxImpulse / _impulse.Length(); } impulse = _impulse - oldImpulse; vA += _invMassA * impulse; wA += _invIA * MathUtils.Cross(_rA, impulse); data.velocities[_indexA].v = vA; data.velocities[_indexA].w = wA; } internal override bool SolvePositionConstraints(ref SolverData data) { return true; } } }
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 SPA.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; } } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== // The Debugger class is a part of the System.Diagnostics package // and is used for communicating with a debugger. namespace System.Diagnostics { using System; using System.IO; using System.Collections; using System.Reflection; using System.Runtime.CompilerServices; using System.Security; using System.Security.Permissions; using System.Runtime.Versioning; // No data, does not need to be marked with the serializable attribute [System.Runtime.InteropServices.ComVisible(true)] public sealed class Debugger { // This should have been a static class, but wasn't as of v3.5. Clearly, this is // broken. We'll keep this in V4 for binary compat, but marked obsolete as error // so migrated source code gets fixed. [Obsolete("Do not create instances of the Debugger class. Call the static methods directly on this type instead", true)] public Debugger() { // Should not have been instantiable - here for binary compatibility in V4. } // Break causes a breakpoint to be signalled to an attached debugger. If no debugger // is attached, the user is asked if he wants to attach a debugger. If yes, then the // debugger is launched. [System.Security.SecuritySafeCritical] // auto-generated [ResourceExposure(ResourceScope.Process)] [ResourceConsumption(ResourceScope.Process)] public static void Break() { if (!IsDebuggerAttached()) { // Try and demand UnmanagedCodePermission. This is done in a try block because if this // fails we want to be able to silently eat the exception and just return so // that the call to Break does not possibly cause an unhandled exception. // The idea here is that partially trusted code shouldn't be able to launch a debugger // without the user going through Watson. try { #pragma warning disable 618 new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Demand(); #pragma warning restore 618 } // If we enter this block, we do not have permission to break into the debugger // and so we just return. catch (SecurityException) { return; } } // Causing a break is now allowed. BreakInternal(); } [System.Security.SecuritySafeCritical] // auto-generated [ResourceExposure(ResourceScope.Process)] [ResourceConsumption(ResourceScope.Process)] static void BreakCanThrow() { if (!IsDebuggerAttached()) { #pragma warning disable 618 new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Demand(); #pragma warning restore 618 } // Causing a break is now allowed. BreakInternal(); } [System.Security.SecurityCritical] // auto-generated [ResourceExposure(ResourceScope.Process)] [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern void BreakInternal(); // Launch launches & attaches a debugger to the process. If a debugger is already attached, // nothing happens. // [System.Security.SecuritySafeCritical] // auto-generated [ResourceExposure(ResourceScope.Machine)] [ResourceConsumption(ResourceScope.Machine)] public static bool Launch() { if (IsDebuggerAttached()) return (true); // Try and demand UnmanagedCodePermission. This is done in a try block because if this // fails we want to be able to silently eat the exception and just return so // that the call to Break does not possibly cause an unhandled exception. // The idea here is that partially trusted code shouldn't be able to launch a debugger // without the user going through Watson. try { #pragma warning disable 618 new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Demand(); #pragma warning restore 618 } // If we enter this block, we do not have permission to break into the debugger // and so we just return. catch (SecurityException) { return (false); } // Causing the debugger to launch is now allowed. return (LaunchInternal()); } // This class implements code:ICustomDebuggerNotification and provides a type to be used to notify // the debugger that execution is about to enter a path that involves a cross-thread dependency. // See code:NotifyOfCrossThreadDependency for more details. private class CrossThreadDependencyNotification : ICustomDebuggerNotification { // constructor public CrossThreadDependencyNotification() { } } // Sends a notification to the debugger to indicate that execution is about to enter a path // involving a cross thread dependency. A debugger that has opted into this type of notification // can take appropriate action on receipt. For example, performing a funceval normally requires // freezing all threads but the one performing the funceval. If the funceval requires execution on // more than one thread, as might occur in remoting scenarios, the funceval will block. This // notification will apprise the debugger that it will need to slip a thread or abort the funceval // in such a situation. The notification is subject to collection after this function returns. // [ResourceExposure(ResourceScope.Process)] [ResourceConsumption(ResourceScope.Process)] [method:System.Runtime.InteropServices.ComVisible(false)] public static void NotifyOfCrossThreadDependency() { if (Debugger.IsAttached) { CrossThreadDependencyNotification notification = new CrossThreadDependencyNotification(); CustomNotification(notification); } } [System.Security.SecurityCritical] // auto-generated [ResourceExposure(ResourceScope.Machine)] [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern bool LaunchInternal(); // Returns whether or not a debugger is attached to the process. // public static bool IsAttached { [ResourceExposure(ResourceScope.Process)] [ResourceConsumption(ResourceScope.Process)] get { return IsDebuggerAttached(); } } [System.Security.SecuritySafeCritical] // auto-generated [ResourceExposure(ResourceScope.Process)] [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern bool IsDebuggerAttached(); // Constants representing the importance level of messages to be logged. // // An attached debugger can enable or disable which messages will // actually be reported to the user through the COM+ debugger // services API. This info is communicated to the runtime so only // desired events are actually reported to the debugger. // // Constant representing the default category public static readonly String DefaultCategory = null; // Posts a message for the attached debugger. If there is no // debugger attached, has no effect. The debugger may or may not // report the message depending on its settings. [System.Security.SecuritySafeCritical] // auto-generated [ResourceExposure(ResourceScope.None)] [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern void Log(int level, String category, String message); // Checks to see if an attached debugger has logging enabled // [System.Security.SecuritySafeCritical] // auto-generated [ResourceExposure(ResourceScope.None)] [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern bool IsLogging(); // Posts a custom notification for the attached debugger. If there is no // debugger attached, has no effect. The debugger may or may not // report the notification depending on its settings. [System.Security.SecuritySafeCritical] // auto-generated [ResourceExposure(ResourceScope.None)] [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern void CustomNotification(ICustomDebuggerNotification data); } }
#region License // Distributed under the MIT License // ============================================================ // Copyright (c) 2019 Hotcakes Commerce, LLC // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software // and associated documentation files (the "Software"), to deal in the Software without restriction, // including without limitation the rights to use, copy, modify, merge, publish, distribute, // sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #endregion using System; using System.Collections; namespace Hotcakes.Web.Barcodes { [Serializable] internal class Code39 : BarcodeCommon, IBarcode { private readonly bool _AllowExtended; private readonly Hashtable C39_Code = new Hashtable(); //is initialized by init_Code39() private readonly Hashtable ExtC39_Translation = new Hashtable(); /// <summary> /// Encodes with Code39. /// </summary> /// <param name="input">Data to encode.</param> public Code39(string input) { Raw_Data = input; } /// <summary> /// Encodes with Code39. /// </summary> /// <param name="input">Data to encode.</param> /// <param name="AllowExtended">Allow Extended Code 39 (Full Ascii mode).</param> public Code39(string input, bool AllowExtended) { Raw_Data = input; _AllowExtended = AllowExtended; } #region IBarcode Members public string Encoded_Value { get { return Encode_Code39(); } } #endregion /// <summary> /// Encode the raw data using the Code 39 algorithm. /// </summary> private string Encode_Code39() { init_Code39(); init_ExtendedCode39(); var strFormattedData = "*" + Raw_Data.Replace("*", "") + "*"; if (_AllowExtended) InsertExtendedCharsIfNeeded(ref strFormattedData); FormattedData = strFormattedData; var result = ""; foreach (var c in FormattedData) { try { result += C39_Code[c].ToString(); result += "0"; //whitespace } catch { if (_AllowExtended) throw new Exception("EC39-1: Invalid data."); throw new Exception("EC39-1: Invalid data. (Try using Extended Code39)"); } } result = result.Substring(0, result.Length - 1); //clear the hashtable so it no longer takes up memory C39_Code.Clear(); return result; } private void init_Code39() { C39_Code.Clear(); C39_Code.Add('0', "101001101101"); C39_Code.Add('1', "110100101011"); C39_Code.Add('2', "101100101011"); C39_Code.Add('3', "110110010101"); C39_Code.Add('4', "101001101011"); C39_Code.Add('5', "110100110101"); C39_Code.Add('6', "101100110101"); C39_Code.Add('7', "101001011011"); C39_Code.Add('8', "110100101101"); C39_Code.Add('9', "101100101101"); C39_Code.Add('A', "110101001011"); C39_Code.Add('B', "101101001011"); C39_Code.Add('C', "110110100101"); C39_Code.Add('D', "101011001011"); C39_Code.Add('E', "110101100101"); C39_Code.Add('F', "101101100101"); C39_Code.Add('G', "101010011011"); C39_Code.Add('H', "110101001101"); C39_Code.Add('I', "101101001101"); C39_Code.Add('J', "101011001101"); C39_Code.Add('K', "110101010011"); C39_Code.Add('L', "101101010011"); C39_Code.Add('M', "110110101001"); C39_Code.Add('N', "101011010011"); C39_Code.Add('O', "110101101001"); C39_Code.Add('P', "101101101001"); C39_Code.Add('Q', "101010110011"); C39_Code.Add('R', "110101011001"); C39_Code.Add('S', "101101011001"); C39_Code.Add('T', "101011011001"); C39_Code.Add('U', "110010101011"); C39_Code.Add('V', "100110101011"); C39_Code.Add('W', "110011010101"); C39_Code.Add('X', "100101101011"); C39_Code.Add('Y', "110010110101"); C39_Code.Add('Z', "100110110101"); C39_Code.Add('-', "100101011011"); C39_Code.Add('.', "110010101101"); C39_Code.Add(' ', "100110101101"); C39_Code.Add('$', "100100100101"); C39_Code.Add('/', "100100101001"); C39_Code.Add('+', "100101001001"); C39_Code.Add('%', "101001001001"); C39_Code.Add('*', "100101101101"); } private void init_ExtendedCode39() { ExtC39_Translation.Clear(); ExtC39_Translation.Add(Convert.ToChar(0).ToString(), "%U"); ExtC39_Translation.Add(Convert.ToChar(1).ToString(), "$A"); ExtC39_Translation.Add(Convert.ToChar(2).ToString(), "$B"); ExtC39_Translation.Add(Convert.ToChar(3).ToString(), "$C"); ExtC39_Translation.Add(Convert.ToChar(4).ToString(), "$D"); ExtC39_Translation.Add(Convert.ToChar(5).ToString(), "$E"); ExtC39_Translation.Add(Convert.ToChar(6).ToString(), "$F"); ExtC39_Translation.Add(Convert.ToChar(7).ToString(), "$G"); ExtC39_Translation.Add(Convert.ToChar(8).ToString(), "$H"); ExtC39_Translation.Add(Convert.ToChar(9).ToString(), "$I"); ExtC39_Translation.Add(Convert.ToChar(10).ToString(), "$J"); ExtC39_Translation.Add(Convert.ToChar(11).ToString(), "$K"); ExtC39_Translation.Add(Convert.ToChar(12).ToString(), "$L"); ExtC39_Translation.Add(Convert.ToChar(13).ToString(), "$M"); ExtC39_Translation.Add(Convert.ToChar(14).ToString(), "$N"); ExtC39_Translation.Add(Convert.ToChar(15).ToString(), "$O"); ExtC39_Translation.Add(Convert.ToChar(16).ToString(), "$P"); ExtC39_Translation.Add(Convert.ToChar(17).ToString(), "$Q"); ExtC39_Translation.Add(Convert.ToChar(18).ToString(), "$R"); ExtC39_Translation.Add(Convert.ToChar(19).ToString(), "$S"); ExtC39_Translation.Add(Convert.ToChar(20).ToString(), "$T"); ExtC39_Translation.Add(Convert.ToChar(21).ToString(), "$U"); ExtC39_Translation.Add(Convert.ToChar(22).ToString(), "$V"); ExtC39_Translation.Add(Convert.ToChar(23).ToString(), "$W"); ExtC39_Translation.Add(Convert.ToChar(24).ToString(), "$X"); ExtC39_Translation.Add(Convert.ToChar(25).ToString(), "$Y"); ExtC39_Translation.Add(Convert.ToChar(26).ToString(), "$Z"); ExtC39_Translation.Add(Convert.ToChar(27).ToString(), "%A"); ExtC39_Translation.Add(Convert.ToChar(28).ToString(), "%B"); ExtC39_Translation.Add(Convert.ToChar(29).ToString(), "%C"); ExtC39_Translation.Add(Convert.ToChar(30).ToString(), "%D"); ExtC39_Translation.Add(Convert.ToChar(31).ToString(), "%E"); ExtC39_Translation.Add("!", "/A"); ExtC39_Translation.Add("\"", "/B"); ExtC39_Translation.Add("#", "/C"); ExtC39_Translation.Add("$", "/D"); ExtC39_Translation.Add("%", "/E"); ExtC39_Translation.Add("&", "/F"); ExtC39_Translation.Add("'", "/G"); ExtC39_Translation.Add("(", "/H"); ExtC39_Translation.Add(")", "/I"); ExtC39_Translation.Add("*", "/J"); ExtC39_Translation.Add("+", "/K"); ExtC39_Translation.Add(",", "/L"); ExtC39_Translation.Add("/", "/O"); ExtC39_Translation.Add(":", "/Z"); ExtC39_Translation.Add(";", "%F"); ExtC39_Translation.Add("<", "%G"); ExtC39_Translation.Add("=", "%H"); ExtC39_Translation.Add(">", "%I"); ExtC39_Translation.Add("?", "%J"); ExtC39_Translation.Add("[", "%K"); ExtC39_Translation.Add("\\", "%L"); ExtC39_Translation.Add("]", "%M"); ExtC39_Translation.Add("^", "%N"); ExtC39_Translation.Add("_", "%O"); ExtC39_Translation.Add("{", "%P"); ExtC39_Translation.Add("|", "%Q"); ExtC39_Translation.Add("}", "%R"); ExtC39_Translation.Add("~", "%S"); ExtC39_Translation.Add("`", "%W"); ExtC39_Translation.Add("@", "%V"); ExtC39_Translation.Add("a", "+A"); ExtC39_Translation.Add("b", "+B"); ExtC39_Translation.Add("c", "+C"); ExtC39_Translation.Add("d", "+D"); ExtC39_Translation.Add("e", "+E"); ExtC39_Translation.Add("f", "+F"); ExtC39_Translation.Add("g", "+G"); ExtC39_Translation.Add("h", "+H"); ExtC39_Translation.Add("i", "+I"); ExtC39_Translation.Add("j", "+J"); ExtC39_Translation.Add("k", "+K"); ExtC39_Translation.Add("l", "+L"); ExtC39_Translation.Add("m", "+M"); ExtC39_Translation.Add("n", "+N"); ExtC39_Translation.Add("o", "+O"); ExtC39_Translation.Add("p", "+P"); ExtC39_Translation.Add("q", "+Q"); ExtC39_Translation.Add("r", "+R"); ExtC39_Translation.Add("s", "+S"); ExtC39_Translation.Add("t", "+T"); ExtC39_Translation.Add("u", "+U"); ExtC39_Translation.Add("v", "+V"); ExtC39_Translation.Add("w", "+W"); ExtC39_Translation.Add("x", "+X"); ExtC39_Translation.Add("y", "+Y"); ExtC39_Translation.Add("z", "+Z"); ExtC39_Translation.Add(Convert.ToChar(127).ToString(), "%T"); //also %X, %Y, %Z } private void InsertExtendedCharsIfNeeded(ref string FormattedData) { var output = string.Empty; foreach (var c in Raw_Data) { try { var s = C39_Code[c].ToString(); output += c; } catch { //insert extended substitution var oTrans = ExtC39_Translation[c.ToString()]; output += oTrans.ToString(); } } FormattedData = output; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Web; using Umbraco.Core.Logging; using Umbraco.Core.Profiling; namespace Umbraco.Core { /// <summary> /// Starts the timer and invokes a callback upon disposal. Provides a simple way of timing an operation by wrapping it in a <code>using</code> (C#) statement. /// </summary> public class DisposableTimer : DisposableObjectSlim { private readonly ILogger _logger; private readonly LogType? _logType; private readonly IProfiler _profiler; private readonly Type _loggerType; private readonly string _endMessage; private readonly IDisposable _profilerStep; private readonly Stopwatch _stopwatch = Stopwatch.StartNew(); private readonly Action<long> _callback; internal enum LogType { Debug, Info } internal DisposableTimer(ILogger logger, LogType logType, IProfiler profiler, Type loggerType, string startMessage, string endMessage) { if (logger == null) throw new ArgumentNullException("logger"); if (loggerType == null) throw new ArgumentNullException("loggerType"); _logger = logger; _logType = logType; _profiler = profiler; _loggerType = loggerType; _endMessage = endMessage; switch (logType) { case LogType.Debug: logger.Debug(loggerType, startMessage); break; case LogType.Info: logger.Info(loggerType, startMessage); break; default: throw new ArgumentOutOfRangeException("logType"); } if (profiler != null) { _profilerStep = profiler.Step(loggerType, startMessage); } } protected internal DisposableTimer(Action<long> callback) { if (callback == null) throw new ArgumentNullException("callback"); _callback = callback; } public Stopwatch Stopwatch { get { return _stopwatch; } } /// <summary> /// Starts the timer and invokes the specified callback upon disposal. /// </summary> /// <param name="callback">The callback.</param> /// <returns></returns> [Obsolete("Use either TraceDuration or DebugDuration instead of using Start")] public static DisposableTimer Start(Action<long> callback) { return new DisposableTimer(callback); } #region TraceDuration [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("Use the other methods that specify strings instead of Func")] public static DisposableTimer TraceDuration<T>(Func<string> startMessage, Func<string> completeMessage) { return TraceDuration(typeof(T), startMessage, completeMessage); } [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("Use the other methods that specify strings instead of Func")] public static DisposableTimer TraceDuration(Type loggerType, Func<string> startMessage, Func<string> completeMessage) { return new DisposableTimer( LoggerResolver.Current.Logger, LogType.Info, ProfilerResolver.HasCurrent ? ProfilerResolver.Current.Profiler : null, loggerType, startMessage(), completeMessage()); } /// <summary> /// Adds a start and end log entry as Info and tracks how long it takes until disposed. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="startMessage"></param> /// <param name="completeMessage"></param> /// <returns></returns> [Obsolete("Use the Umbraco.Core.Logging.ProfilingLogger to create instances of DisposableTimer")] public static DisposableTimer TraceDuration<T>(string startMessage, string completeMessage) { return TraceDuration(typeof(T), startMessage, completeMessage); } /// <summary> /// Adds a start and end log entry as Info and tracks how long it takes until disposed. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="startMessage"></param> /// <returns></returns> [Obsolete("Use the Umbraco.Core.Logging.ProfilingLogger to create instances of DisposableTimer")] public static DisposableTimer TraceDuration<T>(string startMessage) { return TraceDuration(typeof(T), startMessage, "Complete"); } /// <summary> /// Adds a start and end log entry as Info and tracks how long it takes until disposed. /// </summary> /// <param name="loggerType"></param> /// <param name="startMessage"></param> /// <param name="completeMessage"></param> /// <returns></returns> [Obsolete("Use the Umbraco.Core.Logging.ProfilingLogger to create instances of DisposableTimer")] public static DisposableTimer TraceDuration(Type loggerType, string startMessage, string completeMessage) { return new DisposableTimer( LoggerResolver.Current.Logger, LogType.Info, ProfilerResolver.HasCurrent ? ProfilerResolver.Current.Profiler : null, loggerType, startMessage, completeMessage); } #endregion #region DebugDuration /// <summary> /// Adds a start and end log entry as Debug and tracks how long it takes until disposed. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="startMessage"></param> /// <param name="completeMessage"></param> /// <returns></returns> [Obsolete("Use the Umbraco.Core.Logging.ProfilingLogger to create instances of DisposableTimer")] public static DisposableTimer DebugDuration<T>(string startMessage, string completeMessage) { return DebugDuration(typeof(T), startMessage, completeMessage); } /// <summary> /// Adds a start and end log entry as Debug and tracks how long it takes until disposed. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="startMessage"></param> /// <returns></returns> [Obsolete("Use the Umbraco.Core.Logging.ProfilingLogger to create instances of DisposableTimer")] public static DisposableTimer DebugDuration<T>(string startMessage) { return DebugDuration(typeof(T), startMessage, "Complete"); } [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("Use the other methods that specify strings instead of Func")] public static DisposableTimer DebugDuration<T>(Func<string> startMessage, Func<string> completeMessage) { return DebugDuration(typeof(T), startMessage, completeMessage); } /// <summary> /// Adds a start and end log entry as Debug and tracks how long it takes until disposed. /// </summary> /// <param name="loggerType"></param> /// <param name="startMessage"></param> /// <param name="completeMessage"></param> /// <returns></returns> [Obsolete("Use the Umbraco.Core.Logging.ProfilingLogger to create instances of DisposableTimer")] public static DisposableTimer DebugDuration(Type loggerType, string startMessage, string completeMessage) { return new DisposableTimer( LoggerResolver.Current.Logger, LogType.Debug, ProfilerResolver.HasCurrent ? ProfilerResolver.Current.Profiler : null, loggerType, startMessage, completeMessage); } [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("Use the other methods that specify strings instead of Func")] public static DisposableTimer DebugDuration(Type loggerType, Func<string> startMessage, Func<string> completeMessage) { return new DisposableTimer( LoggerResolver.Current.Logger, LogType.Debug, ProfilerResolver.HasCurrent ? ProfilerResolver.Current.Profiler : null, loggerType, startMessage(), completeMessage()); } #endregion /// <summary> /// Handles the disposal of resources. Derived from abstract class <see cref="DisposableObjectSlim"/> which handles common required locking logic. /// </summary> protected override void DisposeResources() { if (_profiler != null) { _profiler.DisposeIfDisposable(); } if (_profilerStep != null) { _profilerStep.Dispose(); } if (_logType.HasValue && _endMessage.IsNullOrWhiteSpace() == false && _loggerType != null && _logger != null) { switch (_logType) { case LogType.Debug: _logger.Debug(_loggerType, () => _endMessage + " (took " + Stopwatch.ElapsedMilliseconds + "ms)"); break; case LogType.Info: _logger.Info(_loggerType, () => _endMessage + " (took " + Stopwatch.ElapsedMilliseconds + "ms)"); break; default: throw new ArgumentOutOfRangeException("logType"); } } if (_callback != null) { _callback.Invoke(Stopwatch.ElapsedMilliseconds); } } } }
using System; using NUnit.Framework; using OpenQA.Selenium.Environment; namespace OpenQA.Selenium { [TestFixture] public class PageLoadingTest : DriverTestFixture { private IWebDriver localDriver; [SetUp] public void RestartOriginalDriver() { driver = EnvironmentManager.Instance.GetCurrentDriver(); } [TearDown] public void QuitAdditionalDriver() { if (localDriver != null) { localDriver.Quit(); localDriver = null; } } [Test] public void NoneStrategyShouldNotWaitForPageToLoad() { InitLocalDriver(PageLoadStrategy.None); string slowPage = EnvironmentManager.Instance.UrlBuilder.WhereIs("sleep?time=5"); DateTime start = DateTime.Now; localDriver.Url = slowPage; DateTime end = DateTime.Now; TimeSpan duration = end - start; // The slow loading resource on that page takes 6 seconds to return, // but with 'none' page loading strategy 'get' operation should not wait. Assert.That(duration.TotalMilliseconds, Is.LessThan(1000), "Took too long to load page: " + duration.TotalMilliseconds); } [Test] public void NoneStrategyShouldNotWaitForPageToRefresh() { InitLocalDriver(PageLoadStrategy.None); string slowPage = EnvironmentManager.Instance.UrlBuilder.WhereIs("sleep?time=5"); // We discard the element, but want a check to make sure the page is loaded WaitFor(() => localDriver.FindElement(By.TagName("body")), TimeSpan.FromSeconds(10), "did not find body"); DateTime start = DateTime.Now; localDriver.Navigate().Refresh(); DateTime end = DateTime.Now; TimeSpan duration = end - start; // The slow loading resource on that page takes 6 seconds to return, // but with 'none' page loading strategy 'refresh' operation should not wait. Assert.That(duration.TotalMilliseconds, Is.LessThan(1000), "Took too long to load page: " + duration.TotalMilliseconds); } [Test] [IgnoreBrowser(Browser.Chrome, "Chrome driver does not support eager page load strategy")] public void EagerStrategyShouldNotWaitForResources() { InitLocalDriver(PageLoadStrategy.Eager); string slowPage = EnvironmentManager.Instance.UrlBuilder.WhereIs("slowLoadingResourcePage.html"); DateTime start = DateTime.Now; localDriver.Url = slowPage; // We discard the element, but want a check to make sure the GET actually // completed. WaitFor(() => localDriver.FindElement(By.Id("peas")), TimeSpan.FromSeconds(10), "did not find element"); DateTime end = DateTime.Now; // The slow loading resource on that page takes 6 seconds to return. If we // waited for it, our load time should be over 6 seconds. TimeSpan duration = end - start; Assert.That(duration.TotalMilliseconds, Is.LessThan(5 * 1000), "Took too long to load page: " + duration.TotalMilliseconds); } [Test] [IgnoreBrowser(Browser.Chrome, "Chrome driver does not support eager page load strategy")] public void EagerStrategyShouldNotWaitForResourcesOnRefresh() { InitLocalDriver(PageLoadStrategy.Eager); string slowPage = EnvironmentManager.Instance.UrlBuilder.WhereIs("slowLoadingResourcePage.html"); localDriver.Url = slowPage; // We discard the element, but want a check to make sure the GET actually // completed. WaitFor(() => localDriver.FindElement(By.Id("peas")), TimeSpan.FromSeconds(10), "did not find element"); DateTime start = DateTime.Now; localDriver.Navigate().Refresh(); // We discard the element, but want a check to make sure the GET actually // completed. WaitFor(() => localDriver.FindElement(By.Id("peas")), TimeSpan.FromSeconds(10), "did not find element"); DateTime end = DateTime.Now; // The slow loading resource on that page takes 6 seconds to return. If we // waited for it, our load time should be over 6 seconds. TimeSpan duration = end - start; Assert.That(duration.TotalMilliseconds, Is.LessThan(5 * 1000), "Took too long to load page: " + duration.TotalMilliseconds); } [Test] [IgnoreBrowser(Browser.Chrome, "Chrome driver does not support eager page load strategy")] public void EagerStrategyShouldWaitForDocumentToBeLoaded() { InitLocalDriver(PageLoadStrategy.Eager); string slowPage = EnvironmentManager.Instance.UrlBuilder.WhereIs("sleep?time=3"); localDriver.Url = slowPage; // We discard the element, but want a check to make sure the GET actually completed. WaitFor(() => localDriver.FindElement(By.TagName("body")), TimeSpan.FromSeconds(10), "did not find body"); } [Test] public void NormalStrategyShouldWaitForDocumentToBeLoaded() { driver.Url = simpleTestPage; Assert.AreEqual(driver.Title, "Hello WebDriver"); } [Test] public void ShouldFollowRedirectsSentInTheHttpResponseHeaders() { driver.Url = redirectPage; Assert.AreEqual(driver.Title, "We Arrive Here"); } [Test] public void ShouldFollowMetaRedirects() { driver.Url = metaRedirectPage; WaitFor(() => { return driver.Title == "We Arrive Here"; }, "Browser title was not 'We Arrive Here'"); Assert.AreEqual(driver.Title, "We Arrive Here"); } [Test] public void ShouldBeAbleToGetAFragmentOnTheCurrentPage() { if (TestUtilities.IsMarionette(driver)) { // Don't run this test on Marionette. Assert.Ignore("Marionette doesn't see subsequent navigation to a fragment as a new navigation."); } driver.Url = xhtmlTestPage; driver.Url = xhtmlTestPage + "#text"; driver.FindElement(By.Id("id1")); } [Test] public void ShouldReturnWhenGettingAUrlThatDoesNotResolve() { try { // Of course, we're up the creek if this ever does get registered driver.Url = "http://www.thisurldoesnotexist.comx/"; } catch (Exception e) { if (!IsIeDriverTimedOutException(e)) { throw e; } } } [Test] [IgnoreBrowser(Browser.Safari, "Safari driver does not throw on malformed URL, causing long delay awaiting timeout")] [NeedsFreshDriver(IsCreatedBeforeTest = true)] public void ShouldThrowIfUrlIsMalformed() { Assert.That(() => driver.Url = "www.test.com", Throws.InstanceOf<WebDriverException>()); } [Test] [IgnoreBrowser(Browser.Safari, "Safari driver does not throw on malformed URL")] [NeedsFreshDriver(IsCreatedBeforeTest = true)] public void ShouldThrowIfUrlIsMalformedInPortPart() { Assert.That(() => driver.Url = "http://localhost:30001bla", Throws.InstanceOf<WebDriverException>()); } [Test] public void ShouldReturnWhenGettingAUrlThatDoesNotConnect() { // Here's hoping that there's nothing here. There shouldn't be driver.Url = "http://localhost:3001"; } [Test] public void ShouldReturnUrlOnNotExistedPage() { string url = EnvironmentManager.Instance.UrlBuilder.WhereIs("not_existed_page.html"); driver.Url = url; Assert.AreEqual(url, driver.Url); } [Test] public void ShouldBeAbleToLoadAPageWithFramesetsAndWaitUntilAllFramesAreLoaded() { driver.Url = framesetPage; driver.SwitchTo().Frame(0); IWebElement pageNumber = driver.FindElement(By.XPath("//span[@id='pageNumber']")); Assert.AreEqual(pageNumber.Text.Trim(), "1"); driver.SwitchTo().DefaultContent().SwitchTo().Frame(1); pageNumber = driver.FindElement(By.XPath("//span[@id='pageNumber']")); Assert.AreEqual(pageNumber.Text.Trim(), "2"); } [Test] [NeedsFreshDriver(IsCreatedBeforeTest = true)] public void ShouldDoNothingIfThereIsNothingToGoBackTo() { string originalTitle = driver.Title; driver.Url = formsPage; driver.Navigate().Back(); // We may have returned to the browser's home page string currentTitle = driver.Title; Assert.That(currentTitle, Is.EqualTo(originalTitle).Or.EqualTo("We Leave From Here")); if (driver.Title == originalTitle) { driver.Navigate().Back(); Assert.AreEqual(originalTitle, driver.Title); } } [Test] public void ShouldBeAbleToNavigateBackInTheBrowserHistory() { driver.Url = formsPage; driver.FindElement(By.Id("imageButton")).Submit(); WaitFor(TitleToBeEqualTo("We Arrive Here"), "Browser title was not 'We Arrive Here'"); Assert.AreEqual(driver.Title, "We Arrive Here"); driver.Navigate().Back(); WaitFor(TitleToBeEqualTo("We Leave From Here"), "Browser title was not 'We Leave From Here'"); Assert.AreEqual(driver.Title, "We Leave From Here"); } [Test] public void ShouldBeAbleToNavigateBackInTheBrowserHistoryInPresenceOfIframes() { driver.Url = xhtmlTestPage; driver.FindElement(By.Name("sameWindow")).Click(); WaitFor(TitleToBeEqualTo("This page has iframes"), "Browser title was not 'This page has iframes'"); Assert.AreEqual(driver.Title, "This page has iframes"); driver.Navigate().Back(); WaitFor(TitleToBeEqualTo("XHTML Test Page"), "Browser title was not 'XHTML Test Page'"); Assert.AreEqual(driver.Title, "XHTML Test Page"); } [Test] public void ShouldBeAbleToNavigateForwardsInTheBrowserHistory() { driver.Url = formsPage; driver.FindElement(By.Id("imageButton")).Submit(); WaitFor(TitleToBeEqualTo("We Arrive Here"), "Browser title was not 'We Arrive Here'"); Assert.AreEqual(driver.Title, "We Arrive Here"); driver.Navigate().Back(); WaitFor(TitleToBeEqualTo("We Leave From Here"), "Browser title was not 'We Leave From Here'"); Assert.AreEqual(driver.Title, "We Leave From Here"); driver.Navigate().Forward(); WaitFor(TitleToBeEqualTo("We Arrive Here"), "Browser title was not 'We Arrive Here'"); Assert.AreEqual(driver.Title, "We Arrive Here"); } [Test] [IgnoreBrowser(Browser.IE, "Browser does not support using insecure SSL certs")] [IgnoreBrowser(Browser.Safari, "Browser does not support using insecure SSL certs")] [IgnoreBrowser(Browser.Edge, "Browser does not support using insecure SSL certs")] public void ShouldBeAbleToAccessPagesWithAnInsecureSslCertificate() { String url = EnvironmentManager.Instance.UrlBuilder.WhereIsSecure("simpleTest.html"); driver.Url = url; // This should work Assert.AreEqual(driver.Title, "Hello WebDriver"); } [Test] public void ShouldBeAbleToRefreshAPage() { driver.Url = xhtmlTestPage; driver.Navigate().Refresh(); Assert.AreEqual(driver.Title, "XHTML Test Page"); } /// <summary> /// see <a href="http://code.google.com/p/selenium/issues/detail?id=208">Issue 208</a> /// </summary> [Test] [IgnoreBrowser(Browser.IE, "Browser does, in fact, hang in this case.")] [IgnoreBrowser(Browser.Firefox, "Browser does, in fact, hang in this case.")] public void ShouldNotHangIfDocumentOpenCallIsNeverFollowedByDocumentCloseCall() { driver.Url = documentWrite; // If this command succeeds, then all is well. driver.FindElement(By.XPath("//body")); } [Test] [IgnoreBrowser(Browser.Safari)] [NeedsFreshDriver(IsCreatedAfterTest = true)] public void PageLoadTimeoutCanBeChanged() { TestPageLoadTimeoutIsEnforced(2); TestPageLoadTimeoutIsEnforced(3); } [Test] [IgnoreBrowser(Browser.Safari)] [NeedsFreshDriver(IsCreatedAfterTest = true)] public void CanHandleSequentialPageLoadTimeouts() { long pageLoadTimeout = 2; long pageLoadTimeBuffer = 10; string slowLoadingPageUrl = EnvironmentManager.Instance.UrlBuilder.WhereIs("sleep?time=" + (pageLoadTimeout + pageLoadTimeBuffer)); driver.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(2); AssertPageLoadTimeoutIsEnforced(() => driver.Url = slowLoadingPageUrl, pageLoadTimeout, pageLoadTimeBuffer); AssertPageLoadTimeoutIsEnforced(() => driver.Url = slowLoadingPageUrl, pageLoadTimeout, pageLoadTimeBuffer); } [Test] [IgnoreBrowser(Browser.Opera, "Not implemented for browser")] [NeedsFreshDriver(IsCreatedAfterTest = true)] public void ShouldTimeoutIfAPageTakesTooLongToLoad() { try { TestPageLoadTimeoutIsEnforced(2); } finally { driver.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(300); } // Load another page after get() timed out but before test HTTP server served previous page. driver.Url = xhtmlTestPage; WaitFor(TitleToBeEqualTo("XHTML Test Page"), "Title was not expected value"); } [Test] [IgnoreBrowser(Browser.Opera, "Not implemented for browser")] [IgnoreBrowser(Browser.Edge, "Not implemented for browser")] [NeedsFreshDriver(IsCreatedAfterTest = true)] public void ShouldTimeoutIfAPageTakesTooLongToLoadAfterClick() { driver.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(2); driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("page_with_link_to_slow_loading_page.html"); IWebElement link = WaitFor(() => driver.FindElement(By.Id("link-to-slow-loading-page")), "Could not find link"); try { AssertPageLoadTimeoutIsEnforced(() => link.Click(), 2, 3); } finally { driver.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(300); } // Load another page after get() timed out but before test HTTP server served previous page. driver.Url = xhtmlTestPage; WaitFor(TitleToBeEqualTo("XHTML Test Page"), "Title was not expected value"); } [Test] [IgnoreBrowser(Browser.Opera, "Not implemented for browser")] [NeedsFreshDriver(IsCreatedAfterTest = true)] public void ShouldTimeoutIfAPageTakesTooLongToRefresh() { // Get the sleeping servlet with a pause of 5 seconds long pageLoadTimeout = 2; long pageLoadTimeBuffer = 0; string slowLoadingPageUrl = EnvironmentManager.Instance.UrlBuilder.WhereIs("sleep?time=" + (pageLoadTimeout + pageLoadTimeBuffer)); driver.Url = slowLoadingPageUrl; driver.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(2); try { AssertPageLoadTimeoutIsEnforced(() => driver.Navigate().Refresh(), 2, 4); } finally { driver.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(300); } // Load another page after get() timed out but before test HTTP server served previous page. driver.Url = xhtmlTestPage; WaitFor(TitleToBeEqualTo("XHTML Test Page"), "Title was not expected value"); } [Test] [IgnoreBrowser(Browser.Edge, "Test hangs browser.")] [IgnoreBrowser(Browser.Chrome, "Chrome driver does, in fact, stop loading page after a timeout.")] [IgnoreBrowser(Browser.Opera, "Not implemented for browser")] [IgnoreBrowser(Browser.Safari, "Safari behaves correctly with page load timeout, but getting text does not propertly trim, leading to a test run time of over 30 seconds")] [NeedsFreshDriver(IsCreatedAfterTest = true)] public void ShouldNotStopLoadingPageAfterTimeout() { try { TestPageLoadTimeoutIsEnforced(1); } finally { driver.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(300); } WaitFor(() => { try { string text = driver.FindElement(By.TagName("body")).Text; return text == "Slept for 11s"; } catch (NoSuchElementException) { } catch (StaleElementReferenceException) { } return false; }, TimeSpan.FromSeconds(30), "Did not find expected text"); } private Func<bool> TitleToBeEqualTo(string expectedTitle) { return () => { return driver.Title == expectedTitle; }; } /** * Sets given pageLoadTimeout to the {@link #driver} and asserts that attempt to navigate to a * page that takes much longer (10 seconds longer) to load results in a TimeoutException. * <p> * Side effects: 1) {@link #driver} is configured to use given pageLoadTimeout, * 2) test HTTP server still didn't serve the page to browser (some browsers may still * be waiting for the page to load despite the fact that driver responded with the timeout). */ private void TestPageLoadTimeoutIsEnforced(long webDriverPageLoadTimeoutInSeconds) { // Test page will load this many seconds longer than WD pageLoadTimeout. long pageLoadTimeBufferInSeconds = 10; string slowLoadingPageUrl = EnvironmentManager.Instance.UrlBuilder.WhereIs("sleep?time=" + (webDriverPageLoadTimeoutInSeconds + pageLoadTimeBufferInSeconds)); driver.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(webDriverPageLoadTimeoutInSeconds); AssertPageLoadTimeoutIsEnforced(() => driver.Url = slowLoadingPageUrl, webDriverPageLoadTimeoutInSeconds, pageLoadTimeBufferInSeconds); } private void AssertPageLoadTimeoutIsEnforced(TestDelegate delegateToTest, long webDriverPageLoadTimeoutInSeconds, long pageLoadTimeBufferInSeconds) { DateTime start = DateTime.Now; Assert.That(delegateToTest, Throws.InstanceOf<WebDriverTimeoutException>(), "I should have timed out after " + webDriverPageLoadTimeoutInSeconds + " seconds"); DateTime end = DateTime.Now; TimeSpan duration = end - start; Assert.That(duration.TotalSeconds, Is.GreaterThan(webDriverPageLoadTimeoutInSeconds)); Assert.That(duration.TotalSeconds, Is.LessThan(webDriverPageLoadTimeoutInSeconds + pageLoadTimeBufferInSeconds)); } private void InitLocalDriver(PageLoadStrategy strategy) { EnvironmentManager.Instance.CloseCurrentDriver(); if (localDriver != null) { localDriver.Quit(); } PageLoadStrategyOptions options = new PageLoadStrategyOptions(); options.PageLoadStrategy = strategy; localDriver = EnvironmentManager.Instance.CreateDriverInstance(options); } private class PageLoadStrategyOptions : DriverOptions { public override void AddAdditionalCapability(string capabilityName, object capabilityValue) { } public override ICapabilities ToCapabilities() { return null; } } } }
using System; using System.Linq; using System.Collections.Generic; using UnityEngine; using UnityEditor.Experimental.VFX; using UnityEngine.UIElements; using System.Reflection; using UnityObject = UnityEngine.Object; using NodeID = System.UInt32; namespace UnityEditor.VFX.UI { class VFXCopyPasteCommon { protected const NodeID TypeMask = 3u << 30; protected const NodeID ParameterFlag = 1u << 30; protected const NodeID ContextFlag = 2u << 30; protected const NodeID OperatorFlag = 3u << 30; protected const NodeID BlockFlag = 0u << 30; protected const NodeID InvalidID = 0xFFFFFFFF; //NodeID are 32 identifiers to any node that can be in a groupNode or have links //The two high bits are use with the above flags to give the type. // For operators and context all the 30 remaining bit are used as an index // For blocks the high bits 2 to 13 are a block index in the context the 18 remaining bits are an index in the contexts // For parameters the high bits 2 to 13 are a parameter node index the 18 remaining are an index in the parameters // Therefore you can copy : // Up to 2^30 operators // Up to 2^30 contexts, but only the first 2^18 can have blocks with links // Up to 2^30 parameters, but only the first 2^18 can have nodes with links // Up to 2^11 block per context can have links // Up to 2^11 parameter nodes per parameter can have links // Note : 2^30 > 1 billion, 2^18 = 262144, 2^11 = 2048 [Serializable] protected struct DataAnchor { public NodeID targetIndex; public int[] slotPath; } [Serializable] protected struct DataEdge { public DataAnchor input; public DataAnchor output; } [Serializable] protected struct FlowAnchor { public NodeID contextIndex; public int flowIndex; } [Serializable] protected struct FlowEdge { public FlowAnchor input; public FlowAnchor output; } [Serializable] protected struct Property { public string name; public VFXSerializableObject value; } [Serializable] protected struct Node { public Vector2 position; [Flags] public enum Flags { Collapsed = 1 << 0, SuperCollapsed = 1 << 1, Enabled = 1 << 2 } public Flags flags; public SerializableType type; public Property[] settings; public Property[] inputSlots; public string[] expandedInputs; public string[] expandedOutputs; } [Serializable] protected struct Context { public Node node; public int dataIndex; public string label; public Node[] blocks; } [Serializable] protected struct Data { public Property[] settings; } [Serializable] protected struct ParameterNode { public Vector2 position; public bool collapsed; public string[] expandedOutput; } [Serializable] protected struct Parameter { public int originalInstanceID; public string name; public VFXSerializableObject value; public bool exposed; public bool range; public VFXSerializableObject min; public VFXSerializableObject max; public string tooltip; public ParameterNode[] nodes; } [Serializable] protected struct GroupNode { public VFXUI.UIInfo infos; public NodeID[] contents; public int stickNodeCount; } [Serializable] protected class SerializableGraph { public Rect bounds; public bool blocksOnly; public Context[] contexts; public Node[] operatorsOrBlocks; // this contains blocks if blocksOnly else it contains operators and blocks are included in their respective contexts public Data[] datas; public Parameter[] parameters; public DataEdge[] dataEdges; public FlowEdge[] flowEdges; public VFXUI.StickyNoteInfo[] stickyNotes; public GroupNode[] groupNodes; } static Dictionary<Type, List<FieldInfo>> s_SerializableFieldByType = new Dictionary<Type, List<FieldInfo>>(); protected static List<FieldInfo> GetFields(Type type) { List<FieldInfo> fields = null; if (!s_SerializableFieldByType.TryGetValue(type, out fields)) { fields = new List<FieldInfo>(); while (type != typeof(VFXContext) && type != typeof(VFXOperator) && type != typeof(VFXBlock) && type != typeof(VFXData)) { var typeFields = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly); foreach (var field in typeFields) { if (!field.IsPublic) { object[] attributes = field.GetCustomAttributes(true); if (!attributes.Any(t => t is VFXSettingAttribute || t is SerializeField)) continue; } if (field.IsNotSerialized) continue; if (!field.FieldType.IsSerializable && !typeof(UnityObject).IsAssignableFrom(field.FieldType)) // Skip field that are not serializable except for UnityObject that are anyway continue; if (typeof(VFXModel).IsAssignableFrom(field.FieldType) || field.FieldType.IsGenericType && typeof(VFXModel).IsAssignableFrom(field.FieldType.GetGenericArguments()[0])) continue; fields.Add(field); } type = type.BaseType; } s_SerializableFieldByType[type] = fields; } return fields; } protected static IEnumerable<VFXSlot> AllSlots(IEnumerable<VFXSlot> slots) { foreach (var slot in slots) { yield return slot; foreach (var child in AllSlots(slot.children)) { yield return child; } } } protected static NodeID GetBlockID(uint contextIndex, uint blockIndex) { if (contextIndex < (1 << 18) && blockIndex < (1 << 11)) { return BlockFlag | (blockIndex << 18) | contextIndex; } return InvalidID; } protected static NodeID GetParameterNodeID(uint parameterIndex, uint nodeIndex) { if (parameterIndex < (1 << 18) && nodeIndex < (1 << 11)) { return ParameterFlag | (nodeIndex << 18) | parameterIndex; } return InvalidID; } } }
using System; using System.Runtime.InteropServices; using System.Text; using System.Collections.Generic; using OpenHome.Net.Core; namespace OpenHome.Net.Device.Providers { public interface IDvProviderAvOpenhomeOrgExakt3 : IDisposable { /// <summary> /// Set the value of the DeviceList property /// </summary> /// <param name="aValue">New value for the property</param> /// <returns>true if the value has been updated; false if aValue was the same as the previous value</returns> bool SetPropertyDeviceList(string aValue); /// <summary> /// Get a copy of the value of the DeviceList property /// </summary> /// <returns>Value of the DeviceList property.</param> string PropertyDeviceList(); /// <summary> /// Set the value of the ConnectionStatus property /// </summary> /// <param name="aValue">New value for the property</param> /// <returns>true if the value has been updated; false if aValue was the same as the previous value</returns> bool SetPropertyConnectionStatus(string aValue); /// <summary> /// Get a copy of the value of the ConnectionStatus property /// </summary> /// <returns>Value of the ConnectionStatus property.</param> string PropertyConnectionStatus(); /// <summary> /// Set the value of the ChannelMap property /// </summary> /// <param name="aValue">New value for the property</param> /// <returns>true if the value has been updated; false if aValue was the same as the previous value</returns> bool SetPropertyChannelMap(string aValue); /// <summary> /// Get a copy of the value of the ChannelMap property /// </summary> /// <returns>Value of the ChannelMap property.</param> string PropertyChannelMap(); /// <summary> /// Set the value of the AudioChannels property /// </summary> /// <param name="aValue">New value for the property</param> /// <returns>true if the value has been updated; false if aValue was the same as the previous value</returns> bool SetPropertyAudioChannels(string aValue); /// <summary> /// Get a copy of the value of the AudioChannels property /// </summary> /// <returns>Value of the AudioChannels property.</param> string PropertyAudioChannels(); /// <summary> /// Set the value of the Version property /// </summary> /// <param name="aValue">New value for the property</param> /// <returns>true if the value has been updated; false if aValue was the same as the previous value</returns> bool SetPropertyVersion(string aValue); /// <summary> /// Get a copy of the value of the Version property /// </summary> /// <returns>Value of the Version property.</param> string PropertyVersion(); } /// <summary> /// Provider for the av.openhome.org:Exakt:3 UPnP service /// </summary> public class DvProviderAvOpenhomeOrgExakt3 : DvProvider, IDisposable, IDvProviderAvOpenhomeOrgExakt3 { private GCHandle iGch; private ActionDelegate iDelegateDeviceList; private ActionDelegate iDelegateDeviceSettings; private ActionDelegate iDelegateConnectionStatus; private ActionDelegate iDelegateSet; private ActionDelegate iDelegateReprogram; private ActionDelegate iDelegateReprogramFallback; private ActionDelegate iDelegateChannelMap; private ActionDelegate iDelegateSetChannelMap; private ActionDelegate iDelegateAudioChannels; private ActionDelegate iDelegateSetAudioChannels; private ActionDelegate iDelegateVersion; private PropertyString iPropertyDeviceList; private PropertyString iPropertyConnectionStatus; private PropertyString iPropertyChannelMap; private PropertyString iPropertyAudioChannels; private PropertyString iPropertyVersion; /// <summary> /// Constructor /// </summary> /// <param name="aDevice">Device which owns this provider</param> protected DvProviderAvOpenhomeOrgExakt3(DvDevice aDevice) : base(aDevice, "av.openhome.org", "Exakt", 3) { iGch = GCHandle.Alloc(this); } /// <summary> /// Enable the DeviceList property. /// </summary> public void EnablePropertyDeviceList() { List<String> allowedValues = new List<String>(); iPropertyDeviceList = new PropertyString(new ParameterString("DeviceList", allowedValues)); AddProperty(iPropertyDeviceList); } /// <summary> /// Enable the ConnectionStatus property. /// </summary> public void EnablePropertyConnectionStatus() { List<String> allowedValues = new List<String>(); iPropertyConnectionStatus = new PropertyString(new ParameterString("ConnectionStatus", allowedValues)); AddProperty(iPropertyConnectionStatus); } /// <summary> /// Enable the ChannelMap property. /// </summary> public void EnablePropertyChannelMap() { List<String> allowedValues = new List<String>(); iPropertyChannelMap = new PropertyString(new ParameterString("ChannelMap", allowedValues)); AddProperty(iPropertyChannelMap); } /// <summary> /// Enable the AudioChannels property. /// </summary> public void EnablePropertyAudioChannels() { List<String> allowedValues = new List<String>(); iPropertyAudioChannels = new PropertyString(new ParameterString("AudioChannels", allowedValues)); AddProperty(iPropertyAudioChannels); } /// <summary> /// Enable the Version property. /// </summary> public void EnablePropertyVersion() { List<String> allowedValues = new List<String>(); iPropertyVersion = new PropertyString(new ParameterString("Version", allowedValues)); AddProperty(iPropertyVersion); } /// <summary> /// Set the value of the DeviceList property /// </summary> /// <remarks>Can only be called if EnablePropertyDeviceList has previously been called.</remarks> /// <param name="aValue">New value for the property</param> /// <returns>true if the value has been updated; false if aValue was the same as the previous value</returns> public bool SetPropertyDeviceList(string aValue) { if (iPropertyDeviceList == null) throw new PropertyDisabledError(); return SetPropertyString(iPropertyDeviceList, aValue); } /// <summary> /// Get a copy of the value of the DeviceList property /// </summary> /// <remarks>Can only be called if EnablePropertyDeviceList has previously been called.</remarks> /// <returns>Value of the DeviceList property.</returns> public string PropertyDeviceList() { if (iPropertyDeviceList == null) throw new PropertyDisabledError(); return iPropertyDeviceList.Value(); } /// <summary> /// Set the value of the ConnectionStatus property /// </summary> /// <remarks>Can only be called if EnablePropertyConnectionStatus has previously been called.</remarks> /// <param name="aValue">New value for the property</param> /// <returns>true if the value has been updated; false if aValue was the same as the previous value</returns> public bool SetPropertyConnectionStatus(string aValue) { if (iPropertyConnectionStatus == null) throw new PropertyDisabledError(); return SetPropertyString(iPropertyConnectionStatus, aValue); } /// <summary> /// Get a copy of the value of the ConnectionStatus property /// </summary> /// <remarks>Can only be called if EnablePropertyConnectionStatus has previously been called.</remarks> /// <returns>Value of the ConnectionStatus property.</returns> public string PropertyConnectionStatus() { if (iPropertyConnectionStatus == null) throw new PropertyDisabledError(); return iPropertyConnectionStatus.Value(); } /// <summary> /// Set the value of the ChannelMap property /// </summary> /// <remarks>Can only be called if EnablePropertyChannelMap has previously been called.</remarks> /// <param name="aValue">New value for the property</param> /// <returns>true if the value has been updated; false if aValue was the same as the previous value</returns> public bool SetPropertyChannelMap(string aValue) { if (iPropertyChannelMap == null) throw new PropertyDisabledError(); return SetPropertyString(iPropertyChannelMap, aValue); } /// <summary> /// Get a copy of the value of the ChannelMap property /// </summary> /// <remarks>Can only be called if EnablePropertyChannelMap has previously been called.</remarks> /// <returns>Value of the ChannelMap property.</returns> public string PropertyChannelMap() { if (iPropertyChannelMap == null) throw new PropertyDisabledError(); return iPropertyChannelMap.Value(); } /// <summary> /// Set the value of the AudioChannels property /// </summary> /// <remarks>Can only be called if EnablePropertyAudioChannels has previously been called.</remarks> /// <param name="aValue">New value for the property</param> /// <returns>true if the value has been updated; false if aValue was the same as the previous value</returns> public bool SetPropertyAudioChannels(string aValue) { if (iPropertyAudioChannels == null) throw new PropertyDisabledError(); return SetPropertyString(iPropertyAudioChannels, aValue); } /// <summary> /// Get a copy of the value of the AudioChannels property /// </summary> /// <remarks>Can only be called if EnablePropertyAudioChannels has previously been called.</remarks> /// <returns>Value of the AudioChannels property.</returns> public string PropertyAudioChannels() { if (iPropertyAudioChannels == null) throw new PropertyDisabledError(); return iPropertyAudioChannels.Value(); } /// <summary> /// Set the value of the Version property /// </summary> /// <remarks>Can only be called if EnablePropertyVersion has previously been called.</remarks> /// <param name="aValue">New value for the property</param> /// <returns>true if the value has been updated; false if aValue was the same as the previous value</returns> public bool SetPropertyVersion(string aValue) { if (iPropertyVersion == null) throw new PropertyDisabledError(); return SetPropertyString(iPropertyVersion, aValue); } /// <summary> /// Get a copy of the value of the Version property /// </summary> /// <remarks>Can only be called if EnablePropertyVersion has previously been called.</remarks> /// <returns>Value of the Version property.</returns> public string PropertyVersion() { if (iPropertyVersion == null) throw new PropertyDisabledError(); return iPropertyVersion.Value(); } /// <summary> /// Signal that the action DeviceList is supported. /// </summary> /// <remarks>The action's availability will be published in the device's service.xml. /// DeviceList must be overridden if this is called.</remarks> protected void EnableActionDeviceList() { OpenHome.Net.Core.Action action = new OpenHome.Net.Core.Action("DeviceList"); action.AddOutputParameter(new ParameterRelated("List", iPropertyDeviceList)); iDelegateDeviceList = new ActionDelegate(DoDeviceList); EnableAction(action, iDelegateDeviceList, GCHandle.ToIntPtr(iGch)); } /// <summary> /// Signal that the action DeviceSettings is supported. /// </summary> /// <remarks>The action's availability will be published in the device's service.xml. /// DeviceSettings must be overridden if this is called.</remarks> protected void EnableActionDeviceSettings() { OpenHome.Net.Core.Action action = new OpenHome.Net.Core.Action("DeviceSettings"); List<String> allowedValues = new List<String>(); action.AddInputParameter(new ParameterString("DeviceId", allowedValues)); action.AddOutputParameter(new ParameterString("Settings", allowedValues)); iDelegateDeviceSettings = new ActionDelegate(DoDeviceSettings); EnableAction(action, iDelegateDeviceSettings, GCHandle.ToIntPtr(iGch)); } /// <summary> /// Signal that the action ConnectionStatus is supported. /// </summary> /// <remarks>The action's availability will be published in the device's service.xml. /// ConnectionStatus must be overridden if this is called.</remarks> protected void EnableActionConnectionStatus() { OpenHome.Net.Core.Action action = new OpenHome.Net.Core.Action("ConnectionStatus"); action.AddOutputParameter(new ParameterRelated("ConnectionStatus", iPropertyConnectionStatus)); iDelegateConnectionStatus = new ActionDelegate(DoConnectionStatus); EnableAction(action, iDelegateConnectionStatus, GCHandle.ToIntPtr(iGch)); } /// <summary> /// Signal that the action Set is supported. /// </summary> /// <remarks>The action's availability will be published in the device's service.xml. /// Set must be overridden if this is called.</remarks> protected void EnableActionSet() { OpenHome.Net.Core.Action action = new OpenHome.Net.Core.Action("Set"); List<String> allowedValues = new List<String>(); action.AddInputParameter(new ParameterString("DeviceId", allowedValues)); action.AddInputParameter(new ParameterUint("BankId")); action.AddInputParameter(new ParameterString("FileUri", allowedValues)); action.AddInputParameter(new ParameterBool("Mute")); action.AddInputParameter(new ParameterBool("Persist")); iDelegateSet = new ActionDelegate(DoSet); EnableAction(action, iDelegateSet, GCHandle.ToIntPtr(iGch)); } /// <summary> /// Signal that the action Reprogram is supported. /// </summary> /// <remarks>The action's availability will be published in the device's service.xml. /// Reprogram must be overridden if this is called.</remarks> protected void EnableActionReprogram() { OpenHome.Net.Core.Action action = new OpenHome.Net.Core.Action("Reprogram"); List<String> allowedValues = new List<String>(); action.AddInputParameter(new ParameterString("DeviceId", allowedValues)); action.AddInputParameter(new ParameterString("FileUri", allowedValues)); iDelegateReprogram = new ActionDelegate(DoReprogram); EnableAction(action, iDelegateReprogram, GCHandle.ToIntPtr(iGch)); } /// <summary> /// Signal that the action ReprogramFallback is supported. /// </summary> /// <remarks>The action's availability will be published in the device's service.xml. /// ReprogramFallback must be overridden if this is called.</remarks> protected void EnableActionReprogramFallback() { OpenHome.Net.Core.Action action = new OpenHome.Net.Core.Action("ReprogramFallback"); List<String> allowedValues = new List<String>(); action.AddInputParameter(new ParameterString("DeviceId", allowedValues)); action.AddInputParameter(new ParameterString("FileUri", allowedValues)); iDelegateReprogramFallback = new ActionDelegate(DoReprogramFallback); EnableAction(action, iDelegateReprogramFallback, GCHandle.ToIntPtr(iGch)); } /// <summary> /// Signal that the action ChannelMap is supported. /// </summary> /// <remarks>The action's availability will be published in the device's service.xml. /// ChannelMap must be overridden if this is called.</remarks> protected void EnableActionChannelMap() { OpenHome.Net.Core.Action action = new OpenHome.Net.Core.Action("ChannelMap"); action.AddOutputParameter(new ParameterRelated("ChannelMap", iPropertyChannelMap)); iDelegateChannelMap = new ActionDelegate(DoChannelMap); EnableAction(action, iDelegateChannelMap, GCHandle.ToIntPtr(iGch)); } /// <summary> /// Signal that the action SetChannelMap is supported. /// </summary> /// <remarks>The action's availability will be published in the device's service.xml. /// SetChannelMap must be overridden if this is called.</remarks> protected void EnableActionSetChannelMap() { OpenHome.Net.Core.Action action = new OpenHome.Net.Core.Action("SetChannelMap"); action.AddInputParameter(new ParameterRelated("ChannelMap", iPropertyChannelMap)); iDelegateSetChannelMap = new ActionDelegate(DoSetChannelMap); EnableAction(action, iDelegateSetChannelMap, GCHandle.ToIntPtr(iGch)); } /// <summary> /// Signal that the action AudioChannels is supported. /// </summary> /// <remarks>The action's availability will be published in the device's service.xml. /// AudioChannels must be overridden if this is called.</remarks> protected void EnableActionAudioChannels() { OpenHome.Net.Core.Action action = new OpenHome.Net.Core.Action("AudioChannels"); action.AddOutputParameter(new ParameterRelated("AudioChannels", iPropertyAudioChannels)); iDelegateAudioChannels = new ActionDelegate(DoAudioChannels); EnableAction(action, iDelegateAudioChannels, GCHandle.ToIntPtr(iGch)); } /// <summary> /// Signal that the action SetAudioChannels is supported. /// </summary> /// <remarks>The action's availability will be published in the device's service.xml. /// SetAudioChannels must be overridden if this is called.</remarks> protected void EnableActionSetAudioChannels() { OpenHome.Net.Core.Action action = new OpenHome.Net.Core.Action("SetAudioChannels"); action.AddInputParameter(new ParameterRelated("AudioChannels", iPropertyAudioChannels)); iDelegateSetAudioChannels = new ActionDelegate(DoSetAudioChannels); EnableAction(action, iDelegateSetAudioChannels, GCHandle.ToIntPtr(iGch)); } /// <summary> /// Signal that the action Version is supported. /// </summary> /// <remarks>The action's availability will be published in the device's service.xml. /// Version must be overridden if this is called.</remarks> protected void EnableActionVersion() { OpenHome.Net.Core.Action action = new OpenHome.Net.Core.Action("Version"); action.AddOutputParameter(new ParameterRelated("Version", iPropertyVersion)); iDelegateVersion = new ActionDelegate(DoVersion); EnableAction(action, iDelegateVersion, GCHandle.ToIntPtr(iGch)); } /// <summary> /// DeviceList action. /// </summary> /// <remarks>Will be called when the device stack receives an invocation of the /// DeviceList action for the owning device. /// /// Must be implemented iff EnableActionDeviceList was called.</remarks> /// <param name="aInvocation">Interface allowing querying of aspects of this particular action invocation.</param> /// <param name="aList"></param> protected virtual void DeviceList(IDvInvocation aInvocation, out string aList) { throw (new ActionDisabledError()); } /// <summary> /// DeviceSettings action. /// </summary> /// <remarks>Will be called when the device stack receives an invocation of the /// DeviceSettings action for the owning device. /// /// Must be implemented iff EnableActionDeviceSettings was called.</remarks> /// <param name="aInvocation">Interface allowing querying of aspects of this particular action invocation.</param> /// <param name="aDeviceId"></param> /// <param name="aSettings"></param> protected virtual void DeviceSettings(IDvInvocation aInvocation, string aDeviceId, out string aSettings) { throw (new ActionDisabledError()); } /// <summary> /// ConnectionStatus action. /// </summary> /// <remarks>Will be called when the device stack receives an invocation of the /// ConnectionStatus action for the owning device. /// /// Must be implemented iff EnableActionConnectionStatus was called.</remarks> /// <param name="aInvocation">Interface allowing querying of aspects of this particular action invocation.</param> /// <param name="aConnectionStatus"></param> protected virtual void ConnectionStatus(IDvInvocation aInvocation, out string aConnectionStatus) { throw (new ActionDisabledError()); } /// <summary> /// Set action. /// </summary> /// <remarks>Will be called when the device stack receives an invocation of the /// Set action for the owning device. /// /// Must be implemented iff EnableActionSet was called.</remarks> /// <param name="aInvocation">Interface allowing querying of aspects of this particular action invocation.</param> /// <param name="aDeviceId"></param> /// <param name="aBankId"></param> /// <param name="aFileUri"></param> /// <param name="aMute"></param> /// <param name="aPersist"></param> protected virtual void Set(IDvInvocation aInvocation, string aDeviceId, uint aBankId, string aFileUri, bool aMute, bool aPersist) { throw (new ActionDisabledError()); } /// <summary> /// Reprogram action. /// </summary> /// <remarks>Will be called when the device stack receives an invocation of the /// Reprogram action for the owning device. /// /// Must be implemented iff EnableActionReprogram was called.</remarks> /// <param name="aInvocation">Interface allowing querying of aspects of this particular action invocation.</param> /// <param name="aDeviceId"></param> /// <param name="aFileUri"></param> protected virtual void Reprogram(IDvInvocation aInvocation, string aDeviceId, string aFileUri) { throw (new ActionDisabledError()); } /// <summary> /// ReprogramFallback action. /// </summary> /// <remarks>Will be called when the device stack receives an invocation of the /// ReprogramFallback action for the owning device. /// /// Must be implemented iff EnableActionReprogramFallback was called.</remarks> /// <param name="aInvocation">Interface allowing querying of aspects of this particular action invocation.</param> /// <param name="aDeviceId"></param> /// <param name="aFileUri"></param> protected virtual void ReprogramFallback(IDvInvocation aInvocation, string aDeviceId, string aFileUri) { throw (new ActionDisabledError()); } /// <summary> /// ChannelMap action. /// </summary> /// <remarks>Will be called when the device stack receives an invocation of the /// ChannelMap action for the owning device. /// /// Must be implemented iff EnableActionChannelMap was called.</remarks> /// <param name="aInvocation">Interface allowing querying of aspects of this particular action invocation.</param> /// <param name="aChannelMap"></param> protected virtual void ChannelMap(IDvInvocation aInvocation, out string aChannelMap) { throw (new ActionDisabledError()); } /// <summary> /// SetChannelMap action. /// </summary> /// <remarks>Will be called when the device stack receives an invocation of the /// SetChannelMap action for the owning device. /// /// Must be implemented iff EnableActionSetChannelMap was called.</remarks> /// <param name="aInvocation">Interface allowing querying of aspects of this particular action invocation.</param> /// <param name="aChannelMap"></param> protected virtual void SetChannelMap(IDvInvocation aInvocation, string aChannelMap) { throw (new ActionDisabledError()); } /// <summary> /// AudioChannels action. /// </summary> /// <remarks>Will be called when the device stack receives an invocation of the /// AudioChannels action for the owning device. /// /// Must be implemented iff EnableActionAudioChannels was called.</remarks> /// <param name="aInvocation">Interface allowing querying of aspects of this particular action invocation.</param> /// <param name="aAudioChannels"></param> protected virtual void AudioChannels(IDvInvocation aInvocation, out string aAudioChannels) { throw (new ActionDisabledError()); } /// <summary> /// SetAudioChannels action. /// </summary> /// <remarks>Will be called when the device stack receives an invocation of the /// SetAudioChannels action for the owning device. /// /// Must be implemented iff EnableActionSetAudioChannels was called.</remarks> /// <param name="aInvocation">Interface allowing querying of aspects of this particular action invocation.</param> /// <param name="aAudioChannels"></param> protected virtual void SetAudioChannels(IDvInvocation aInvocation, string aAudioChannels) { throw (new ActionDisabledError()); } /// <summary> /// Version action. /// </summary> /// <remarks>Will be called when the device stack receives an invocation of the /// Version action for the owning device. /// /// Must be implemented iff EnableActionVersion was called.</remarks> /// <param name="aInvocation">Interface allowing querying of aspects of this particular action invocation.</param> /// <param name="aVersion"></param> protected virtual void Version(IDvInvocation aInvocation, out string aVersion) { throw (new ActionDisabledError()); } private static int DoDeviceList(IntPtr aPtr, IntPtr aInvocation) { GCHandle gch = GCHandle.FromIntPtr(aPtr); DvProviderAvOpenhomeOrgExakt3 self = (DvProviderAvOpenhomeOrgExakt3)gch.Target; DvInvocation invocation = new DvInvocation(aInvocation); string list; try { invocation.ReadStart(); invocation.ReadEnd(); self.DeviceList(invocation, out list); } catch (ActionError e) { invocation.ReportActionError(e, "DeviceList"); return -1; } catch (PropertyUpdateError) { invocation.ReportError(501, String.Format("Invalid value for property {0}", new object[] { "DeviceList" })); return -1; } catch (Exception e) { System.Diagnostics.Debug.WriteLine("WARNING: unexpected exception {0} thrown by {1}", new object[] { e, "DeviceList" }); System.Diagnostics.Debug.WriteLine(" Only ActionError or PropertyUpdateError should be thrown by actions"); return -1; } try { invocation.WriteStart(); invocation.WriteString("List", list); invocation.WriteEnd(); } catch (ActionError) { return -1; } catch (System.Exception e) { System.Diagnostics.Debug.WriteLine("WARNING: unexpected exception {0} thrown by {1}", new object[] { e, "DeviceList" }); System.Diagnostics.Debug.WriteLine(" Only ActionError can be thrown by action response writer"); } return 0; } private static int DoDeviceSettings(IntPtr aPtr, IntPtr aInvocation) { GCHandle gch = GCHandle.FromIntPtr(aPtr); DvProviderAvOpenhomeOrgExakt3 self = (DvProviderAvOpenhomeOrgExakt3)gch.Target; DvInvocation invocation = new DvInvocation(aInvocation); string deviceId; string settings; try { invocation.ReadStart(); deviceId = invocation.ReadString("DeviceId"); invocation.ReadEnd(); self.DeviceSettings(invocation, deviceId, out settings); } catch (ActionError e) { invocation.ReportActionError(e, "DeviceSettings"); return -1; } catch (PropertyUpdateError) { invocation.ReportError(501, String.Format("Invalid value for property {0}", new object[] { "DeviceSettings" })); return -1; } catch (Exception e) { System.Diagnostics.Debug.WriteLine("WARNING: unexpected exception {0} thrown by {1}", new object[] { e, "DeviceSettings" }); System.Diagnostics.Debug.WriteLine(" Only ActionError or PropertyUpdateError should be thrown by actions"); return -1; } try { invocation.WriteStart(); invocation.WriteString("Settings", settings); invocation.WriteEnd(); } catch (ActionError) { return -1; } catch (System.Exception e) { System.Diagnostics.Debug.WriteLine("WARNING: unexpected exception {0} thrown by {1}", new object[] { e, "DeviceSettings" }); System.Diagnostics.Debug.WriteLine(" Only ActionError can be thrown by action response writer"); } return 0; } private static int DoConnectionStatus(IntPtr aPtr, IntPtr aInvocation) { GCHandle gch = GCHandle.FromIntPtr(aPtr); DvProviderAvOpenhomeOrgExakt3 self = (DvProviderAvOpenhomeOrgExakt3)gch.Target; DvInvocation invocation = new DvInvocation(aInvocation); string connectionStatus; try { invocation.ReadStart(); invocation.ReadEnd(); self.ConnectionStatus(invocation, out connectionStatus); } catch (ActionError e) { invocation.ReportActionError(e, "ConnectionStatus"); return -1; } catch (PropertyUpdateError) { invocation.ReportError(501, String.Format("Invalid value for property {0}", new object[] { "ConnectionStatus" })); return -1; } catch (Exception e) { System.Diagnostics.Debug.WriteLine("WARNING: unexpected exception {0} thrown by {1}", new object[] { e, "ConnectionStatus" }); System.Diagnostics.Debug.WriteLine(" Only ActionError or PropertyUpdateError should be thrown by actions"); return -1; } try { invocation.WriteStart(); invocation.WriteString("ConnectionStatus", connectionStatus); invocation.WriteEnd(); } catch (ActionError) { return -1; } catch (System.Exception e) { System.Diagnostics.Debug.WriteLine("WARNING: unexpected exception {0} thrown by {1}", new object[] { e, "ConnectionStatus" }); System.Diagnostics.Debug.WriteLine(" Only ActionError can be thrown by action response writer"); } return 0; } private static int DoSet(IntPtr aPtr, IntPtr aInvocation) { GCHandle gch = GCHandle.FromIntPtr(aPtr); DvProviderAvOpenhomeOrgExakt3 self = (DvProviderAvOpenhomeOrgExakt3)gch.Target; DvInvocation invocation = new DvInvocation(aInvocation); string deviceId; uint bankId; string fileUri; bool mute; bool persist; try { invocation.ReadStart(); deviceId = invocation.ReadString("DeviceId"); bankId = invocation.ReadUint("BankId"); fileUri = invocation.ReadString("FileUri"); mute = invocation.ReadBool("Mute"); persist = invocation.ReadBool("Persist"); invocation.ReadEnd(); self.Set(invocation, deviceId, bankId, fileUri, mute, persist); } catch (ActionError e) { invocation.ReportActionError(e, "Set"); return -1; } catch (PropertyUpdateError) { invocation.ReportError(501, String.Format("Invalid value for property {0}", new object[] { "Set" })); return -1; } catch (Exception e) { System.Diagnostics.Debug.WriteLine("WARNING: unexpected exception {0} thrown by {1}", new object[] { e, "Set" }); System.Diagnostics.Debug.WriteLine(" Only ActionError or PropertyUpdateError should be thrown by actions"); return -1; } try { invocation.WriteStart(); invocation.WriteEnd(); } catch (ActionError) { return -1; } catch (System.Exception e) { System.Diagnostics.Debug.WriteLine("WARNING: unexpected exception {0} thrown by {1}", new object[] { e, "Set" }); System.Diagnostics.Debug.WriteLine(" Only ActionError can be thrown by action response writer"); } return 0; } private static int DoReprogram(IntPtr aPtr, IntPtr aInvocation) { GCHandle gch = GCHandle.FromIntPtr(aPtr); DvProviderAvOpenhomeOrgExakt3 self = (DvProviderAvOpenhomeOrgExakt3)gch.Target; DvInvocation invocation = new DvInvocation(aInvocation); string deviceId; string fileUri; try { invocation.ReadStart(); deviceId = invocation.ReadString("DeviceId"); fileUri = invocation.ReadString("FileUri"); invocation.ReadEnd(); self.Reprogram(invocation, deviceId, fileUri); } catch (ActionError e) { invocation.ReportActionError(e, "Reprogram"); return -1; } catch (PropertyUpdateError) { invocation.ReportError(501, String.Format("Invalid value for property {0}", new object[] { "Reprogram" })); return -1; } catch (Exception e) { System.Diagnostics.Debug.WriteLine("WARNING: unexpected exception {0} thrown by {1}", new object[] { e, "Reprogram" }); System.Diagnostics.Debug.WriteLine(" Only ActionError or PropertyUpdateError should be thrown by actions"); return -1; } try { invocation.WriteStart(); invocation.WriteEnd(); } catch (ActionError) { return -1; } catch (System.Exception e) { System.Diagnostics.Debug.WriteLine("WARNING: unexpected exception {0} thrown by {1}", new object[] { e, "Reprogram" }); System.Diagnostics.Debug.WriteLine(" Only ActionError can be thrown by action response writer"); } return 0; } private static int DoReprogramFallback(IntPtr aPtr, IntPtr aInvocation) { GCHandle gch = GCHandle.FromIntPtr(aPtr); DvProviderAvOpenhomeOrgExakt3 self = (DvProviderAvOpenhomeOrgExakt3)gch.Target; DvInvocation invocation = new DvInvocation(aInvocation); string deviceId; string fileUri; try { invocation.ReadStart(); deviceId = invocation.ReadString("DeviceId"); fileUri = invocation.ReadString("FileUri"); invocation.ReadEnd(); self.ReprogramFallback(invocation, deviceId, fileUri); } catch (ActionError e) { invocation.ReportActionError(e, "ReprogramFallback"); return -1; } catch (PropertyUpdateError) { invocation.ReportError(501, String.Format("Invalid value for property {0}", new object[] { "ReprogramFallback" })); return -1; } catch (Exception e) { System.Diagnostics.Debug.WriteLine("WARNING: unexpected exception {0} thrown by {1}", new object[] { e, "ReprogramFallback" }); System.Diagnostics.Debug.WriteLine(" Only ActionError or PropertyUpdateError should be thrown by actions"); return -1; } try { invocation.WriteStart(); invocation.WriteEnd(); } catch (ActionError) { return -1; } catch (System.Exception e) { System.Diagnostics.Debug.WriteLine("WARNING: unexpected exception {0} thrown by {1}", new object[] { e, "ReprogramFallback" }); System.Diagnostics.Debug.WriteLine(" Only ActionError can be thrown by action response writer"); } return 0; } private static int DoChannelMap(IntPtr aPtr, IntPtr aInvocation) { GCHandle gch = GCHandle.FromIntPtr(aPtr); DvProviderAvOpenhomeOrgExakt3 self = (DvProviderAvOpenhomeOrgExakt3)gch.Target; DvInvocation invocation = new DvInvocation(aInvocation); string channelMap; try { invocation.ReadStart(); invocation.ReadEnd(); self.ChannelMap(invocation, out channelMap); } catch (ActionError e) { invocation.ReportActionError(e, "ChannelMap"); return -1; } catch (PropertyUpdateError) { invocation.ReportError(501, String.Format("Invalid value for property {0}", new object[] { "ChannelMap" })); return -1; } catch (Exception e) { System.Diagnostics.Debug.WriteLine("WARNING: unexpected exception {0} thrown by {1}", new object[] { e, "ChannelMap" }); System.Diagnostics.Debug.WriteLine(" Only ActionError or PropertyUpdateError should be thrown by actions"); return -1; } try { invocation.WriteStart(); invocation.WriteString("ChannelMap", channelMap); invocation.WriteEnd(); } catch (ActionError) { return -1; } catch (System.Exception e) { System.Diagnostics.Debug.WriteLine("WARNING: unexpected exception {0} thrown by {1}", new object[] { e, "ChannelMap" }); System.Diagnostics.Debug.WriteLine(" Only ActionError can be thrown by action response writer"); } return 0; } private static int DoSetChannelMap(IntPtr aPtr, IntPtr aInvocation) { GCHandle gch = GCHandle.FromIntPtr(aPtr); DvProviderAvOpenhomeOrgExakt3 self = (DvProviderAvOpenhomeOrgExakt3)gch.Target; DvInvocation invocation = new DvInvocation(aInvocation); string channelMap; try { invocation.ReadStart(); channelMap = invocation.ReadString("ChannelMap"); invocation.ReadEnd(); self.SetChannelMap(invocation, channelMap); } catch (ActionError e) { invocation.ReportActionError(e, "SetChannelMap"); return -1; } catch (PropertyUpdateError) { invocation.ReportError(501, String.Format("Invalid value for property {0}", new object[] { "SetChannelMap" })); return -1; } catch (Exception e) { System.Diagnostics.Debug.WriteLine("WARNING: unexpected exception {0} thrown by {1}", new object[] { e, "SetChannelMap" }); System.Diagnostics.Debug.WriteLine(" Only ActionError or PropertyUpdateError should be thrown by actions"); return -1; } try { invocation.WriteStart(); invocation.WriteEnd(); } catch (ActionError) { return -1; } catch (System.Exception e) { System.Diagnostics.Debug.WriteLine("WARNING: unexpected exception {0} thrown by {1}", new object[] { e, "SetChannelMap" }); System.Diagnostics.Debug.WriteLine(" Only ActionError can be thrown by action response writer"); } return 0; } private static int DoAudioChannels(IntPtr aPtr, IntPtr aInvocation) { GCHandle gch = GCHandle.FromIntPtr(aPtr); DvProviderAvOpenhomeOrgExakt3 self = (DvProviderAvOpenhomeOrgExakt3)gch.Target; DvInvocation invocation = new DvInvocation(aInvocation); string audioChannels; try { invocation.ReadStart(); invocation.ReadEnd(); self.AudioChannels(invocation, out audioChannels); } catch (ActionError e) { invocation.ReportActionError(e, "AudioChannels"); return -1; } catch (PropertyUpdateError) { invocation.ReportError(501, String.Format("Invalid value for property {0}", new object[] { "AudioChannels" })); return -1; } catch (Exception e) { System.Diagnostics.Debug.WriteLine("WARNING: unexpected exception {0} thrown by {1}", new object[] { e, "AudioChannels" }); System.Diagnostics.Debug.WriteLine(" Only ActionError or PropertyUpdateError should be thrown by actions"); return -1; } try { invocation.WriteStart(); invocation.WriteString("AudioChannels", audioChannels); invocation.WriteEnd(); } catch (ActionError) { return -1; } catch (System.Exception e) { System.Diagnostics.Debug.WriteLine("WARNING: unexpected exception {0} thrown by {1}", new object[] { e, "AudioChannels" }); System.Diagnostics.Debug.WriteLine(" Only ActionError can be thrown by action response writer"); } return 0; } private static int DoSetAudioChannels(IntPtr aPtr, IntPtr aInvocation) { GCHandle gch = GCHandle.FromIntPtr(aPtr); DvProviderAvOpenhomeOrgExakt3 self = (DvProviderAvOpenhomeOrgExakt3)gch.Target; DvInvocation invocation = new DvInvocation(aInvocation); string audioChannels; try { invocation.ReadStart(); audioChannels = invocation.ReadString("AudioChannels"); invocation.ReadEnd(); self.SetAudioChannels(invocation, audioChannels); } catch (ActionError e) { invocation.ReportActionError(e, "SetAudioChannels"); return -1; } catch (PropertyUpdateError) { invocation.ReportError(501, String.Format("Invalid value for property {0}", new object[] { "SetAudioChannels" })); return -1; } catch (Exception e) { System.Diagnostics.Debug.WriteLine("WARNING: unexpected exception {0} thrown by {1}", new object[] { e, "SetAudioChannels" }); System.Diagnostics.Debug.WriteLine(" Only ActionError or PropertyUpdateError should be thrown by actions"); return -1; } try { invocation.WriteStart(); invocation.WriteEnd(); } catch (ActionError) { return -1; } catch (System.Exception e) { System.Diagnostics.Debug.WriteLine("WARNING: unexpected exception {0} thrown by {1}", new object[] { e, "SetAudioChannels" }); System.Diagnostics.Debug.WriteLine(" Only ActionError can be thrown by action response writer"); } return 0; } private static int DoVersion(IntPtr aPtr, IntPtr aInvocation) { GCHandle gch = GCHandle.FromIntPtr(aPtr); DvProviderAvOpenhomeOrgExakt3 self = (DvProviderAvOpenhomeOrgExakt3)gch.Target; DvInvocation invocation = new DvInvocation(aInvocation); string version; try { invocation.ReadStart(); invocation.ReadEnd(); self.Version(invocation, out version); } catch (ActionError e) { invocation.ReportActionError(e, "Version"); return -1; } catch (PropertyUpdateError) { invocation.ReportError(501, String.Format("Invalid value for property {0}", new object[] { "Version" })); return -1; } catch (Exception e) { System.Diagnostics.Debug.WriteLine("WARNING: unexpected exception {0} thrown by {1}", new object[] { e, "Version" }); System.Diagnostics.Debug.WriteLine(" Only ActionError or PropertyUpdateError should be thrown by actions"); return -1; } try { invocation.WriteStart(); invocation.WriteString("Version", version); invocation.WriteEnd(); } catch (ActionError) { return -1; } catch (System.Exception e) { System.Diagnostics.Debug.WriteLine("WARNING: unexpected exception {0} thrown by {1}", new object[] { e, "Version" }); System.Diagnostics.Debug.WriteLine(" Only ActionError can be thrown by action response writer"); } return 0; } /// <summary> /// Must be called for each class instance. Must be called before Core.Library.Close(). /// </summary> public virtual void Dispose() { if (DisposeProvider()) iGch.Free(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.Serialization.Formatters.Binary; using System.Text; using Xunit; namespace System.Runtime.Serialization.Formatters.Tests { public partial class BinaryFormatterTests : RemoteExecutorTestBase { [Theory] [MemberData(nameof(BasicObjectsRoundtrip_MemberData))] public void ValidateBasicObjectsRoundtrip(object obj, FormatterAssemblyStyle assemblyFormat, TypeFilterLevel filterLevel, FormatterTypeStyle typeFormat) { object clone = FormatterClone(obj, null, assemblyFormat, filterLevel, typeFormat); if (!ReferenceEquals(obj, string.Empty)) // "" is interned and will roundtrip as the same object { Assert.NotSame(obj, clone); } CheckForAnyEquals(obj, clone); } // Used for updating blobs in BinaryFormatterTestData.cs //[Fact] public void UpdateBlobs() { string testDataFilePath = GetTestDataFilePath(); IEnumerable<object[]> coreTypeRecords = GetCoreTypeRecords(); string[] coreTypeBlobs = GetCoreTypeBlobs(coreTypeRecords).ToArray(); UpdateCoreTypeBlobs(testDataFilePath, coreTypeBlobs); } [Theory] [MemberData(nameof(SerializableObjects_MemberData))] public void ValidateAgainstBlobs(object obj, string[] blobs) { if (blobs == null || blobs.Length == 0) { throw new ArgumentOutOfRangeException($"Type {obj} has no blobs to deserialize and test equality against. Blob: " + SerializeObjectToBlob(obj)); } foreach (string blob in blobs) { CheckForAnyEquals(obj, DeserializeBlobToObject(blob)); } } [Fact] public void ArraySegmentDefaultCtor() { // This is workaround for Xunit bug which tries to pretty print test case name and enumerate this object. // When inner array is not initialized it throws an exception when this happens. object obj = new ArraySegment<int>(); string corefxBlob = "AAEAAAD/////AQAAAAAAAAAEAQAAAHJTeXN0ZW0uQXJyYXlTZWdtZW50YDFbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0DAAAABl9hcnJheQdfb2Zmc2V0Bl9jb3VudAcAAAgICAoAAAAAAAAAAAs="; string netfxBlob = "AAEAAAD/////AQAAAAAAAAAEAQAAAHJTeXN0ZW0uQXJyYXlTZWdtZW50YDFbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0DAAAABl9hcnJheQdfb2Zmc2V0Bl9jb3VudAcAAAgICAoAAAAAAAAAAAs="; CheckForAnyEquals(obj, DeserializeBlobToObject(corefxBlob)); CheckForAnyEquals(obj, DeserializeBlobToObject(netfxBlob)); } [Fact] public void ValidateDeserializationOfObjectWithDifferentAssemblyVersion() { // To generate this properly, change AssemblyVersion to a value which is unlikely to happen in production and generate base64(serialized-data) // For this test 9.98.7.987 is being used var obj = new SomeType() { SomeField = 7 }; string serializedObj = @"AAEAAAD/////AQAAAAAAAAAMAgAAAHNTeXN0ZW0uUnVudGltZS5TZXJpYWxpemF0aW9uLkZvcm1hdHRlcnMuVGVzdHMsIFZlcnNpb249OS45OC43Ljk4NywgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj05ZDc3Y2M3YWQzOWI2OGViBQEAAAA2U3lzdGVtLlJ1bnRpbWUuU2VyaWFsaXphdGlvbi5Gb3JtYXR0ZXJzLlRlc3RzLlNvbWVUeXBlAQAAAAlTb21lRmllbGQACAIAAAAHAAAACw=="; var deserialized = (SomeType)DeserializeBlobToObject(serializedObj); Assert.Equal(obj, deserialized); } [Fact] public void ValidateDeserializationOfObjectWithGenericTypeWhichGenericArgumentHasDifferentAssemblyVersion() { // To generate this properly, change AssemblyVersion to a value which is unlikely to happen in production and generate base64(serialized-data) // For this test 9.98.7.987 is being used var obj = new GenericTypeWithArg<SomeType>() { Test = new SomeType() { SomeField = 9 } }; string serializedObj = @"AAEAAAD/////AQAAAAAAAAAMAgAAAHNTeXN0ZW0uUnVudGltZS5TZXJpYWxpemF0aW9uLkZvcm1hdHRlcnMuVGVzdHMsIFZlcnNpb249OS45OC43Ljk4NywgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj05ZDc3Y2M3YWQzOWI2OGViBQEAAADxAVN5c3RlbS5SdW50aW1lLlNlcmlhbGl6YXRpb24uRm9ybWF0dGVycy5UZXN0cy5HZW5lcmljVHlwZVdpdGhBcmdgMVtbU3lzdGVtLlJ1bnRpbWUuU2VyaWFsaXphdGlvbi5Gb3JtYXR0ZXJzLlRlc3RzLlNvbWVUeXBlLCBTeXN0ZW0uUnVudGltZS5TZXJpYWxpemF0aW9uLkZvcm1hdHRlcnMuVGVzdHMsIFZlcnNpb249OS45OC43Ljk4NywgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj05ZDc3Y2M3YWQzOWI2OGViXV0BAAAABFRlc3QENlN5c3RlbS5SdW50aW1lLlNlcmlhbGl6YXRpb24uRm9ybWF0dGVycy5UZXN0cy5Tb21lVHlwZQIAAAACAAAACQMAAAAFAwAAADZTeXN0ZW0uUnVudGltZS5TZXJpYWxpemF0aW9uLkZvcm1hdHRlcnMuVGVzdHMuU29tZVR5cGUBAAAACVNvbWVGaWVsZAAIAgAAAAkAAAAL"; var deserialized = (GenericTypeWithArg<SomeType>)DeserializeBlobToObject(serializedObj); Assert.Equal(obj, deserialized); } [Theory] [MemberData(nameof(SerializableEqualityComparers_MemberData))] public void ValidateDeserializationOfEqualityComparers(object obj, string[] blobs) { if (blobs == null || blobs.Length == 0) { throw new ArgumentOutOfRangeException($"Type {obj} has no blobs to deserialize and test equality against. Blob: " + SerializeObjectToBlob(obj)); } foreach (string base64Serialized in blobs) { object deserializedInstance = DeserializeBlobToObject(base64Serialized); Type objType = deserializedInstance.GetType(); Assert.True(objType.IsGenericType, $"Type `{objType.FullName}` must be generic."); Assert.Equal("System.Collections.Generic.ObjectEqualityComparer`1", objType.GetGenericTypeDefinition().FullName); Assert.Equal(obj.GetType().GetGenericArguments()[0], objType.GetGenericArguments()[0]); } } [Fact] public void RoundtripManyObjectsInOneStream() { object[][] objects = SerializableObjects_MemberData().ToArray(); var s = new MemoryStream(); var f = new BinaryFormatter(); foreach (object[] obj in objects) { f.Serialize(s, obj[0]); } s.Position = 0; foreach (object[] obj in objects) { object clone = f.Deserialize(s); CheckForAnyEquals(obj[0], clone); } } [Fact] public void SameObjectRepeatedInArray() { object o = new object(); object[] arr = new[] { o, o, o, o, o }; object[] result = FormatterClone(arr); Assert.Equal(arr.Length, result.Length); Assert.NotSame(arr, result); Assert.NotSame(arr[0], result[0]); for (int i = 1; i < result.Length; i++) { Assert.Same(result[0], result[i]); } } [Theory] [MemberData(nameof(SerializableExceptions_MemberData))] public void Roundtrip_Exceptions(Exception expected) { BinaryFormatterHelpers.AssertRoundtrips(expected); } [Theory] [MemberData(nameof(NonSerializableTypes_MemberData))] public void ValidateNonSerializableTypes(object obj, FormatterAssemblyStyle assemblyFormat, TypeFilterLevel filterLevel, FormatterTypeStyle typeFormat) { var f = new BinaryFormatter() { AssemblyFormat = assemblyFormat, FilterLevel = filterLevel, TypeFormat = typeFormat }; using (var s = new MemoryStream()) { Assert.Throws<SerializationException>(() => f.Serialize(s, obj)); } } [Fact] public void SerializeNonSerializableTypeWithSurrogate() { var p = new NonSerializablePair<int, string>() { Value1 = 1, Value2 = "2" }; Assert.False(p.GetType().IsSerializable); Assert.Throws<SerializationException>(() => FormatterClone(p)); NonSerializablePair<int, string> result = FormatterClone(p, new NonSerializablePairSurrogate()); Assert.NotSame(p, result); Assert.Equal(p.Value1, result.Value1); Assert.Equal(p.Value2, result.Value2); } [Fact] public void SerializationEvents_FireAsExpected() { var f = new BinaryFormatter(); var obj = new IncrementCountsDuringRoundtrip(null); Assert.Equal(0, obj.IncrementedDuringOnSerializingMethod); Assert.Equal(0, obj.IncrementedDuringOnSerializedMethod); Assert.Equal(0, obj.IncrementedDuringOnDeserializingMethod); Assert.Equal(0, obj.IncrementedDuringOnDeserializedMethod); using (var s = new MemoryStream()) { f.Serialize(s, obj); s.Position = 0; Assert.Equal(1, obj.IncrementedDuringOnSerializingMethod); Assert.Equal(1, obj.IncrementedDuringOnSerializedMethod); Assert.Equal(0, obj.IncrementedDuringOnDeserializingMethod); Assert.Equal(0, obj.IncrementedDuringOnDeserializedMethod); var result = (IncrementCountsDuringRoundtrip)f.Deserialize(s); Assert.Equal(1, obj.IncrementedDuringOnSerializingMethod); Assert.Equal(1, obj.IncrementedDuringOnSerializedMethod); Assert.Equal(0, obj.IncrementedDuringOnDeserializingMethod); Assert.Equal(0, obj.IncrementedDuringOnDeserializedMethod); Assert.Equal(1, result.IncrementedDuringOnSerializingMethod); Assert.Equal(0, result.IncrementedDuringOnSerializedMethod); Assert.Equal(1, result.IncrementedDuringOnDeserializingMethod); Assert.Equal(1, result.IncrementedDuringOnDeserializedMethod); } } [Fact] public void SerializationEvents_DerivedTypeWithEvents_FireAsExpected() { var f = new BinaryFormatter(); var obj = new DerivedIncrementCountsDuringRoundtrip(null); Assert.Equal(0, obj.IncrementedDuringOnSerializingMethod); Assert.Equal(0, obj.IncrementedDuringOnSerializedMethod); Assert.Equal(0, obj.IncrementedDuringOnDeserializingMethod); Assert.Equal(0, obj.IncrementedDuringOnDeserializedMethod); Assert.Equal(0, obj.DerivedIncrementedDuringOnSerializingMethod); Assert.Equal(0, obj.DerivedIncrementedDuringOnSerializedMethod); Assert.Equal(0, obj.DerivedIncrementedDuringOnDeserializingMethod); Assert.Equal(0, obj.DerivedIncrementedDuringOnDeserializedMethod); using (var s = new MemoryStream()) { f.Serialize(s, obj); s.Position = 0; Assert.Equal(1, obj.IncrementedDuringOnSerializingMethod); Assert.Equal(1, obj.IncrementedDuringOnSerializedMethod); Assert.Equal(0, obj.IncrementedDuringOnDeserializingMethod); Assert.Equal(0, obj.IncrementedDuringOnDeserializedMethod); Assert.Equal(1, obj.DerivedIncrementedDuringOnSerializingMethod); Assert.Equal(1, obj.DerivedIncrementedDuringOnSerializedMethod); Assert.Equal(0, obj.DerivedIncrementedDuringOnDeserializingMethod); Assert.Equal(0, obj.DerivedIncrementedDuringOnDeserializedMethod); var result = (DerivedIncrementCountsDuringRoundtrip)f.Deserialize(s); Assert.Equal(1, obj.IncrementedDuringOnSerializingMethod); Assert.Equal(1, obj.IncrementedDuringOnSerializedMethod); Assert.Equal(0, obj.IncrementedDuringOnDeserializingMethod); Assert.Equal(0, obj.IncrementedDuringOnDeserializedMethod); Assert.Equal(1, obj.DerivedIncrementedDuringOnSerializingMethod); Assert.Equal(1, obj.DerivedIncrementedDuringOnSerializedMethod); Assert.Equal(0, obj.DerivedIncrementedDuringOnDeserializingMethod); Assert.Equal(0, obj.DerivedIncrementedDuringOnDeserializedMethod); Assert.Equal(1, result.IncrementedDuringOnSerializingMethod); Assert.Equal(0, result.IncrementedDuringOnSerializedMethod); Assert.Equal(1, result.IncrementedDuringOnDeserializingMethod); Assert.Equal(1, result.IncrementedDuringOnDeserializedMethod); Assert.Equal(1, result.DerivedIncrementedDuringOnSerializingMethod); Assert.Equal(0, result.DerivedIncrementedDuringOnSerializedMethod); Assert.Equal(1, result.DerivedIncrementedDuringOnDeserializingMethod); Assert.Equal(1, result.DerivedIncrementedDuringOnDeserializedMethod); } } [Fact] public void Properties_Roundtrip() { var f = new BinaryFormatter(); Assert.Null(f.Binder); var binder = new DelegateBinder(); f.Binder = binder; Assert.Same(binder, f.Binder); Assert.NotNull(f.Context); Assert.Null(f.Context.Context); Assert.Equal(StreamingContextStates.All, f.Context.State); var context = new StreamingContext(StreamingContextStates.Clone); f.Context = context; Assert.Equal(StreamingContextStates.Clone, f.Context.State); Assert.Null(f.SurrogateSelector); var selector = new SurrogateSelector(); f.SurrogateSelector = selector; Assert.Same(selector, f.SurrogateSelector); Assert.Equal(FormatterAssemblyStyle.Simple, f.AssemblyFormat); f.AssemblyFormat = FormatterAssemblyStyle.Full; Assert.Equal(FormatterAssemblyStyle.Full, f.AssemblyFormat); Assert.Equal(TypeFilterLevel.Full, f.FilterLevel); f.FilterLevel = TypeFilterLevel.Low; Assert.Equal(TypeFilterLevel.Low, f.FilterLevel); Assert.Equal(FormatterTypeStyle.TypesAlways, f.TypeFormat); f.TypeFormat = FormatterTypeStyle.XsdString; Assert.Equal(FormatterTypeStyle.XsdString, f.TypeFormat); } [Fact] public void SerializeDeserialize_InvalidArguments_ThrowsException() { var f = new BinaryFormatter(); AssertExtensions.Throws<ArgumentNullException>("serializationStream", () => f.Serialize(null, new object())); AssertExtensions.Throws<ArgumentNullException>("serializationStream", () => f.Deserialize(null)); Assert.Throws<SerializationException>(() => f.Deserialize(new MemoryStream())); // seekable, 0-length } [Theory] [InlineData(FormatterAssemblyStyle.Simple, false)] [InlineData(FormatterAssemblyStyle.Full, true)] public void MissingField_FailsWithAppropriateStyle(FormatterAssemblyStyle style, bool exceptionExpected) { var f = new BinaryFormatter(); var s = new MemoryStream(); f.Serialize(s, new Version1ClassWithoutField()); s.Position = 0; f = new BinaryFormatter() { AssemblyFormat = style }; f.Binder = new DelegateBinder { BindToTypeDelegate = (_, __) => typeof(Version2ClassWithoutOptionalField) }; if (exceptionExpected) { Assert.Throws<SerializationException>(() => f.Deserialize(s)); } else { var result = (Version2ClassWithoutOptionalField)f.Deserialize(s); Assert.NotNull(result); Assert.Equal(null, result.Value); } } [Theory] [InlineData(FormatterAssemblyStyle.Simple)] [InlineData(FormatterAssemblyStyle.Full)] public void OptionalField_Missing_Success(FormatterAssemblyStyle style) { var f = new BinaryFormatter(); var s = new MemoryStream(); f.Serialize(s, new Version1ClassWithoutField()); s.Position = 0; f = new BinaryFormatter() { AssemblyFormat = style }; f.Binder = new DelegateBinder { BindToTypeDelegate = (_, __) => typeof(Version2ClassWithOptionalField) }; var result = (Version2ClassWithOptionalField)f.Deserialize(s); Assert.NotNull(result); Assert.Equal(null, result.Value); } [Fact] public void ObjectReference_RealObjectSerialized() { var obj = new ObjRefReturnsObj { Real = 42 }; object real = FormatterClone<object>(obj); Assert.Equal(42, real); } // Test is disabled becaues it can cause improbable memory allocations leading to interminable paging. // We're keeping the code because it could be useful to a dev making local changes to binary formatter code. //[OuterLoop] //[Theory] //[MemberData(nameof(FuzzInputs_MemberData))] public void Deserialize_FuzzInput(object obj, Random rand) { // Get the serialized data for the object byte[] data = SerializeObjectToRaw(obj); // Make some "random" changes to it for (int i = 1; i < rand.Next(1, 100); i++) { data[rand.Next(data.Length)] = (byte)rand.Next(256); } // Try to deserialize that. try { DeserializeRawToObject(data); // Since there's no checksum, it's possible we changed data that didn't corrupt the instance } catch (ArgumentOutOfRangeException) { } catch (ArrayTypeMismatchException) { } catch (DecoderFallbackException) { } catch (FormatException) { } catch (IndexOutOfRangeException) { } catch (InvalidCastException) { } catch (OutOfMemoryException) { } catch (OverflowException) { } catch (NullReferenceException) { } catch (SerializationException) { } catch (TargetInvocationException) { } catch (ArgumentException) { } catch (FileLoadException) { } } [Fact] public void Deserialize_EndOfStream_ThrowsException() { var f = new BinaryFormatter(); var s = new MemoryStream(); f.Serialize(s, 1024); for (long i = s.Length - 1; i >= 0; i--) { s.Position = 0; var data = new byte[i]; Assert.Equal(data.Length, s.Read(data, 0, data.Length)); Assert.Throws<SerializationException>(() => f.Deserialize(new MemoryStream(data))); } } [Theory] [MemberData(nameof(CrossProcessObjects_MemberData))] public void Roundtrip_CrossProcess(object obj) { string outputPath = GetTestFilePath(); string inputPath = GetTestFilePath(); // Serialize out to a file using (FileStream fs = File.OpenWrite(outputPath)) { new BinaryFormatter().Serialize(fs, obj); } // In another process, deserialize from that file and serialize to another RemoteInvoke((remoteInput, remoteOutput) => { Assert.False(File.Exists(remoteOutput)); using (FileStream input = File.OpenRead(remoteInput)) using (FileStream output = File.OpenWrite(remoteOutput)) { var b = new BinaryFormatter(); b.Serialize(output, b.Deserialize(input)); return SuccessExitCode; } }, $"\"{outputPath}\"", $"\"{inputPath}\"").Dispose(); // Deserialize what the other process serialized and compare it to the original using (FileStream fs = File.OpenRead(inputPath)) { object deserialized = new BinaryFormatter().Deserialize(fs); Assert.Equal(obj, deserialized); } } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, ".NET Framework fails when serializing arrays with non-zero lower bounds")] [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "UAPAOT does not support non-zero lower bounds")] public void Roundtrip_ArrayContainingArrayAtNonZeroLowerBound() { FormatterClone(Array.CreateInstance(typeof(uint[]), new[] { 5 }, new[] { 1 })); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // This program uses code hyperlinks available as part of the HyperAddin Visual Studio plug-in. // It is available from http://www.codeplex.com/hyperAddin #define FEATURE_MANAGED_ETW #if !ES_BUILD_STANDALONE #define FEATURE_ACTIVITYSAMPLING #endif #if ES_BUILD_STANDALONE #define FEATURE_MANAGED_ETW_CHANNELS // #define FEATURE_ADVANCED_MANAGED_ETW_CHANNELS #endif #if ES_BUILD_STANDALONE using Environment = Microsoft.Diagnostics.Tracing.Internal.Environment; using EventDescriptor = Microsoft.Diagnostics.Tracing.EventDescriptor; #endif using System; using System.Runtime.InteropServices; using System.Security; using System.Collections.ObjectModel; #if !ES_BUILD_AGAINST_DOTNET_V35 using Contract = System.Diagnostics.Contracts.Contract; using System.Collections.Generic; using System.Text; #else using Contract = Microsoft.Diagnostics.Contracts.Internal.Contract; using System.Collections.Generic; using System.Text; #endif #if ES_BUILD_STANDALONE namespace Microsoft.Diagnostics.Tracing #else namespace System.Diagnostics.Tracing #endif { public partial class EventSource { private byte[] providerMetadata; /// <summary> /// Construct an EventSource with a given name for non-contract based events (e.g. those using the Write() API). /// </summary> /// <param name="eventSourceName"> /// The name of the event source. Must not be null. /// </param> public EventSource( string eventSourceName) : this(eventSourceName, EventSourceSettings.EtwSelfDescribingEventFormat) { } /// <summary> /// Construct an EventSource with a given name for non-contract based events (e.g. those using the Write() API). /// </summary> /// <param name="eventSourceName"> /// The name of the event source. Must not be null. /// </param> /// <param name="config"> /// Configuration options for the EventSource as a whole. /// </param> public EventSource( string eventSourceName, EventSourceSettings config) : this(eventSourceName, config, null) { } /// <summary> /// Construct an EventSource with a given name for non-contract based events (e.g. those using the Write() API). /// /// Also specify a list of key-value pairs called traits (you must pass an even number of strings). /// The first string is the key and the second is the value. These are not interpreted by EventSource /// itself but may be interprated the listeners. Can be fetched with GetTrait(string). /// </summary> /// <param name="eventSourceName"> /// The name of the event source. Must not be null. /// </param> /// <param name="config"> /// Configuration options for the EventSource as a whole. /// </param> /// <param name="traits">A collection of key-value strings (must be an even number).</param> public EventSource( string eventSourceName, EventSourceSettings config, params string[] traits) : this( eventSourceName == null ? new Guid() : GenerateGuidFromName(eventSourceName.ToUpperInvariant()), eventSourceName, config, traits) { if (eventSourceName == null) { throw new ArgumentNullException(nameof(eventSourceName)); } Contract.EndContractBlock(); } /// <summary> /// Writes an event with no fields and default options. /// (Native API: EventWriteTransfer) /// </summary> /// <param name="eventName">The name of the event. Must not be null.</param> [SecuritySafeCritical] public unsafe void Write(string eventName) { if (eventName == null) { throw new ArgumentNullException(nameof(eventName)); } Contract.EndContractBlock(); if (!this.IsEnabled()) { return; } var options = new EventSourceOptions(); this.WriteImpl(eventName, ref options, null, null, null, SimpleEventTypes<EmptyStruct>.Instance); } /// <summary> /// Writes an event with no fields. /// (Native API: EventWriteTransfer) /// </summary> /// <param name="eventName">The name of the event. Must not be null.</param> /// <param name="options"> /// Options for the event, such as the level, keywords, and opcode. Unset /// options will be set to default values. /// </param> [SecuritySafeCritical] public unsafe void Write(string eventName, EventSourceOptions options) { if (eventName == null) { throw new ArgumentNullException(nameof(eventName)); } Contract.EndContractBlock(); if (!this.IsEnabled()) { return; } this.WriteImpl(eventName, ref options, null, null, null, SimpleEventTypes<EmptyStruct>.Instance); } /// <summary> /// Writes an event. /// (Native API: EventWriteTransfer) /// </summary> /// <typeparam name="T"> /// The type that defines the event and its payload. This must be an /// anonymous type or a type with an [EventData] attribute. /// </typeparam> /// <param name="eventName"> /// The name for the event. If null, the event name is automatically /// determined based on T, either from the Name property of T's EventData /// attribute or from typeof(T).Name. /// </param> /// <param name="data"> /// The object containing the event payload data. The type T must be /// an anonymous type or a type with an [EventData] attribute. The /// public instance properties of data will be written recursively to /// create the fields of the event. /// </param> [SecuritySafeCritical] public unsafe void Write<T>( string eventName, T data) { if (!this.IsEnabled()) { return; } var options = new EventSourceOptions(); this.WriteImpl(eventName, ref options, data, null, null, SimpleEventTypes<T>.Instance); } /// <summary> /// Writes an event. /// (Native API: EventWriteTransfer) /// </summary> /// <typeparam name="T"> /// The type that defines the event and its payload. This must be an /// anonymous type or a type with an [EventData] attribute. /// </typeparam> /// <param name="eventName"> /// The name for the event. If null, the event name is automatically /// determined based on T, either from the Name property of T's EventData /// attribute or from typeof(T).Name. /// </param> /// <param name="options"> /// Options for the event, such as the level, keywords, and opcode. Unset /// options will be set to default values. /// </param> /// <param name="data"> /// The object containing the event payload data. The type T must be /// an anonymous type or a type with an [EventData] attribute. The /// public instance properties of data will be written recursively to /// create the fields of the event. /// </param> [SecuritySafeCritical] public unsafe void Write<T>( string eventName, EventSourceOptions options, T data) { if (!this.IsEnabled()) { return; } this.WriteImpl(eventName, ref options, data, null, null, SimpleEventTypes<T>.Instance); } /// <summary> /// Writes an event. /// This overload is for use with extension methods that wish to efficiently /// forward the options or data parameter without performing an extra copy. /// (Native API: EventWriteTransfer) /// </summary> /// <typeparam name="T"> /// The type that defines the event and its payload. This must be an /// anonymous type or a type with an [EventData] attribute. /// </typeparam> /// <param name="eventName"> /// The name for the event. If null, the event name is automatically /// determined based on T, either from the Name property of T's EventData /// attribute or from typeof(T).Name. /// </param> /// <param name="options"> /// Options for the event, such as the level, keywords, and opcode. Unset /// options will be set to default values. /// </param> /// <param name="data"> /// The object containing the event payload data. The type T must be /// an anonymous type or a type with an [EventData] attribute. The /// public instance properties of data will be written recursively to /// create the fields of the event. /// </param> [SecuritySafeCritical] public unsafe void Write<T>( string eventName, ref EventSourceOptions options, ref T data) { if (!this.IsEnabled()) { return; } this.WriteImpl(eventName, ref options, data, null, null, SimpleEventTypes<T>.Instance); } /// <summary> /// Writes an event. /// This overload is meant for clients that need to manipuate the activityId /// and related ActivityId for the event. /// </summary> /// <typeparam name="T"> /// The type that defines the event and its payload. This must be an /// anonymous type or a type with an [EventData] attribute. /// </typeparam> /// <param name="eventName"> /// The name for the event. If null, the event name is automatically /// determined based on T, either from the Name property of T's EventData /// attribute or from typeof(T).Name. /// </param> /// <param name="options"> /// Options for the event, such as the level, keywords, and opcode. Unset /// options will be set to default values. /// </param> /// <param name="activityId"> /// The GUID of the activity associated with this event. /// </param> /// <param name="relatedActivityId"> /// The GUID of another activity that is related to this activity, or Guid.Empty /// if there is no related activity. Most commonly, the Start operation of a /// new activity specifies a parent activity as its related activity. /// </param> /// <param name="data"> /// The object containing the event payload data. The type T must be /// an anonymous type or a type with an [EventData] attribute. The /// public instance properties of data will be written recursively to /// create the fields of the event. /// </param> [SecuritySafeCritical] public unsafe void Write<T>( string eventName, ref EventSourceOptions options, ref Guid activityId, ref Guid relatedActivityId, ref T data) { if (!this.IsEnabled()) { return; } fixed (Guid* pActivity = &activityId, pRelated = &relatedActivityId) { this.WriteImpl( eventName, ref options, data, pActivity, relatedActivityId == Guid.Empty ? null : pRelated, SimpleEventTypes<T>.Instance); } } /// <summary> /// Writes an extended event, where the values of the event are the /// combined properties of any number of values. This method is /// intended for use in advanced logging scenarios that support a /// dynamic set of event context providers. /// This method does a quick check on whether this event is enabled. /// </summary> /// <param name="eventName"> /// The name for the event. If null, the name from eventTypes is used. /// (Note that providing the event name via the name parameter is slightly /// less efficient than using the name from eventTypes.) /// </param> /// <param name="options"> /// Optional overrides for the event, such as the level, keyword, opcode, /// activityId, and relatedActivityId. Any settings not specified by options /// are obtained from eventTypes. /// </param> /// <param name="eventTypes"> /// Information about the event and the types of the values in the event. /// Must not be null. Note that the eventTypes object should be created once and /// saved. It should not be recreated for each event. /// </param> /// <param name="activityID"> /// A pointer to the activity ID GUID to log /// </param> /// <param name="childActivityID"> /// A pointer to the child activity ID to log (can be null) </param> /// <param name="values"> /// The values to include in the event. Must not be null. The number and types of /// the values must match the number and types of the fields described by the /// eventTypes parameter. /// </param> [SecuritySafeCritical] private unsafe void WriteMultiMerge( string eventName, ref EventSourceOptions options, TraceLoggingEventTypes eventTypes, Guid* activityID, Guid* childActivityID, params object[] values) { if (!this.IsEnabled()) { return; } byte level = (options.valuesSet & EventSourceOptions.levelSet) != 0 ? options.level : eventTypes.level; EventKeywords keywords = (options.valuesSet & EventSourceOptions.keywordsSet) != 0 ? options.keywords : eventTypes.keywords; if (this.IsEnabled((EventLevel)level, keywords)) { WriteMultiMergeInner(eventName, ref options, eventTypes, activityID, childActivityID, values); } } /// <summary> /// Writes an extended event, where the values of the event are the /// combined properties of any number of values. This method is /// intended for use in advanced logging scenarios that support a /// dynamic set of event context providers. /// Attention: This API does not check whether the event is enabled or not. /// Please use WriteMultiMerge to avoid spending CPU cycles for events that are /// not enabled. /// </summary> /// <param name="eventName"> /// The name for the event. If null, the name from eventTypes is used. /// (Note that providing the event name via the name parameter is slightly /// less efficient than using the name from eventTypes.) /// </param> /// <param name="options"> /// Optional overrides for the event, such as the level, keyword, opcode, /// activityId, and relatedActivityId. Any settings not specified by options /// are obtained from eventTypes. /// </param> /// <param name="eventTypes"> /// Information about the event and the types of the values in the event. /// Must not be null. Note that the eventTypes object should be created once and /// saved. It should not be recreated for each event. /// </param> /// <param name="activityID"> /// A pointer to the activity ID GUID to log /// </param> /// <param name="childActivityID"> /// A pointer to the child activity ID to log (can be null) /// </param> /// <param name="values"> /// The values to include in the event. Must not be null. The number and types of /// the values must match the number and types of the fields described by the /// eventTypes parameter. /// </param> [SecuritySafeCritical] private unsafe void WriteMultiMergeInner( string eventName, ref EventSourceOptions options, TraceLoggingEventTypes eventTypes, Guid* activityID, Guid* childActivityID, params object[] values) { int identity = 0; byte level = (options.valuesSet & EventSourceOptions.levelSet) != 0 ? options.level : eventTypes.level; byte opcode = (options.valuesSet & EventSourceOptions.opcodeSet) != 0 ? options.opcode : eventTypes.opcode; EventTags tags = (options.valuesSet & EventSourceOptions.tagsSet) != 0 ? options.tags : eventTypes.Tags; EventKeywords keywords = (options.valuesSet & EventSourceOptions.keywordsSet) != 0 ? options.keywords : eventTypes.keywords; var nameInfo = eventTypes.GetNameInfo(eventName ?? eventTypes.Name, tags); if (nameInfo == null) { return; } identity = nameInfo.identity; EventDescriptor descriptor = new EventDescriptor(identity, level, opcode, (long)keywords); var pinCount = eventTypes.pinCount; var scratch = stackalloc byte[eventTypes.scratchSize]; var descriptors = stackalloc EventData[eventTypes.dataCount + 3]; var pins = stackalloc GCHandle[pinCount]; fixed (byte* pMetadata0 = this.providerMetadata, pMetadata1 = nameInfo.nameMetadata, pMetadata2 = eventTypes.typeMetadata) { descriptors[0].SetMetadata(pMetadata0, this.providerMetadata.Length, 2); descriptors[1].SetMetadata(pMetadata1, nameInfo.nameMetadata.Length, 1); descriptors[2].SetMetadata(pMetadata2, eventTypes.typeMetadata.Length, 1); #if (!ES_BUILD_PCL && !PROJECTN) System.Runtime.CompilerServices.RuntimeHelpers.PrepareConstrainedRegions(); #endif try { DataCollector.ThreadInstance.Enable( scratch, eventTypes.scratchSize, descriptors + 3, eventTypes.dataCount, pins, pinCount); for (int i = 0; i < eventTypes.typeInfos.Length; i++) { var info = eventTypes.typeInfos[i]; info.WriteData(TraceLoggingDataCollector.Instance, info.PropertyValueFactory(values[i])); } this.WriteEventRaw( eventName, ref descriptor, activityID, childActivityID, (int)(DataCollector.ThreadInstance.Finish() - descriptors), (IntPtr)descriptors); } finally { this.WriteCleanup(pins, pinCount); } } } /// <summary> /// Writes an extended event, where the values of the event have already /// been serialized in "data". /// </summary> /// <param name="eventName"> /// The name for the event. If null, the name from eventTypes is used. /// (Note that providing the event name via the name parameter is slightly /// less efficient than using the name from eventTypes.) /// </param> /// <param name="options"> /// Optional overrides for the event, such as the level, keyword, opcode, /// activityId, and relatedActivityId. Any settings not specified by options /// are obtained from eventTypes. /// </param> /// <param name="eventTypes"> /// Information about the event and the types of the values in the event. /// Must not be null. Note that the eventTypes object should be created once and /// saved. It should not be recreated for each event. /// </param> /// <param name="activityID"> /// A pointer to the activity ID GUID to log /// </param> /// <param name="childActivityID"> /// A pointer to the child activity ID to log (can be null) /// </param> /// <param name="data"> /// The previously serialized values to include in the event. Must not be null. /// The number and types of the values must match the number and types of the /// fields described by the eventTypes parameter. /// </param> [SecuritySafeCritical] internal unsafe void WriteMultiMerge( string eventName, ref EventSourceOptions options, TraceLoggingEventTypes eventTypes, Guid* activityID, Guid* childActivityID, EventData* data) { if (!this.IsEnabled()) { return; } fixed (EventSourceOptions* pOptions = &options) { EventDescriptor descriptor; var nameInfo = this.UpdateDescriptor(eventName, eventTypes, ref options, out descriptor); if (nameInfo == null) { return; } // We make a descriptor for each EventData, and because we morph strings to counted strings // we may have 2 for each arg, so we allocate enough for this. var descriptors = stackalloc EventData[eventTypes.dataCount + eventTypes.typeInfos.Length * 2 + 3]; fixed (byte* pMetadata0 = this.providerMetadata, pMetadata1 = nameInfo.nameMetadata, pMetadata2 = eventTypes.typeMetadata) { descriptors[0].SetMetadata(pMetadata0, this.providerMetadata.Length, 2); descriptors[1].SetMetadata(pMetadata1, nameInfo.nameMetadata.Length, 1); descriptors[2].SetMetadata(pMetadata2, eventTypes.typeMetadata.Length, 1); int numDescrs = 3; for (int i = 0; i < eventTypes.typeInfos.Length; i++) { // Until M3, we need to morph strings to a counted representation // When TDH supports null terminated strings, we can remove this. if (eventTypes.typeInfos[i].DataType == typeof(string)) { // Write out the size of the string descriptors[numDescrs].m_Ptr = (long)&descriptors[numDescrs + 1].m_Size; descriptors[numDescrs].m_Size = 2; numDescrs++; descriptors[numDescrs].m_Ptr = data[i].m_Ptr; descriptors[numDescrs].m_Size = data[i].m_Size - 2; // Remove the null terminator numDescrs++; } else { descriptors[numDescrs].m_Ptr = data[i].m_Ptr; descriptors[numDescrs].m_Size = data[i].m_Size; // old conventions for bool is 4 bytes, but meta-data assumes 1. if (data[i].m_Size == 4 && eventTypes.typeInfos[i].DataType == typeof(bool)) descriptors[numDescrs].m_Size = 1; numDescrs++; } } this.WriteEventRaw( eventName, ref descriptor, activityID, childActivityID, numDescrs, (IntPtr)descriptors); } } } [SecuritySafeCritical] private unsafe void WriteImpl( string eventName, ref EventSourceOptions options, object data, Guid* pActivityId, Guid* pRelatedActivityId, TraceLoggingEventTypes eventTypes) { try { fixed (EventSourceOptions* pOptions = &options) { EventDescriptor descriptor; options.Opcode = options.IsOpcodeSet ? options.Opcode : GetOpcodeWithDefault(options.Opcode, eventName); var nameInfo = this.UpdateDescriptor(eventName, eventTypes, ref options, out descriptor); if (nameInfo == null) { return; } var pinCount = eventTypes.pinCount; var scratch = stackalloc byte[eventTypes.scratchSize]; var descriptors = stackalloc EventData[eventTypes.dataCount + 3]; var pins = stackalloc GCHandle[pinCount]; fixed (byte* pMetadata0 = this.providerMetadata, pMetadata1 = nameInfo.nameMetadata, pMetadata2 = eventTypes.typeMetadata) { descriptors[0].SetMetadata(pMetadata0, this.providerMetadata.Length, 2); descriptors[1].SetMetadata(pMetadata1, nameInfo.nameMetadata.Length, 1); descriptors[2].SetMetadata(pMetadata2, eventTypes.typeMetadata.Length, 1); #if (!ES_BUILD_PCL && !PROJECTN) System.Runtime.CompilerServices.RuntimeHelpers.PrepareConstrainedRegions(); #endif EventOpcode opcode = (EventOpcode)descriptor.Opcode; Guid activityId = Guid.Empty; Guid relatedActivityId = Guid.Empty; if (pActivityId == null && pRelatedActivityId == null && ((options.ActivityOptions & EventActivityOptions.Disable) == 0)) { if (opcode == EventOpcode.Start) { m_activityTracker.OnStart(m_name, eventName, 0, ref activityId, ref relatedActivityId, options.ActivityOptions); } else if (opcode == EventOpcode.Stop) { m_activityTracker.OnStop(m_name, eventName, 0, ref activityId); } if (activityId != Guid.Empty) pActivityId = &activityId; if (relatedActivityId != Guid.Empty) pRelatedActivityId = &relatedActivityId; } try { DataCollector.ThreadInstance.Enable( scratch, eventTypes.scratchSize, descriptors + 3, eventTypes.dataCount, pins, pinCount); var info = eventTypes.typeInfos[0]; info.WriteData(TraceLoggingDataCollector.Instance, info.PropertyValueFactory(data)); this.WriteEventRaw( eventName, ref descriptor, pActivityId, pRelatedActivityId, (int)(DataCollector.ThreadInstance.Finish() - descriptors), (IntPtr)descriptors); // TODO enable filtering for listeners. if (m_Dispatchers != null) { var eventData = (EventPayload)(eventTypes.typeInfos[0].GetData(data)); WriteToAllListeners(eventName, ref descriptor, nameInfo.tags, pActivityId, eventData); } } catch (Exception ex) { if (ex is EventSourceException) throw; else ThrowEventSourceException(eventName, ex); } finally { this.WriteCleanup(pins, pinCount); } } } } catch (Exception ex) { if (ex is EventSourceException) throw; else ThrowEventSourceException(eventName, ex); } } [SecurityCritical] private unsafe void WriteToAllListeners(string eventName, ref EventDescriptor eventDescriptor, EventTags tags, Guid* pActivityId, EventPayload payload) { EventWrittenEventArgs eventCallbackArgs = new EventWrittenEventArgs(this); eventCallbackArgs.EventName = eventName; eventCallbackArgs.m_level = (EventLevel) eventDescriptor.Level; eventCallbackArgs.m_keywords = (EventKeywords) eventDescriptor.Keywords; eventCallbackArgs.m_opcode = (EventOpcode) eventDescriptor.Opcode; eventCallbackArgs.m_tags = tags; // Self described events do not have an id attached. We mark it internally with -1. eventCallbackArgs.EventId = -1; if (pActivityId != null) eventCallbackArgs.RelatedActivityId = *pActivityId; if (payload != null) { eventCallbackArgs.Payload = new ReadOnlyCollection<object>((IList<object>)payload.Values); eventCallbackArgs.PayloadNames = new ReadOnlyCollection<string>((IList<string>)payload.Keys); } DispatchToAllListeners(-1, pActivityId, eventCallbackArgs); } #if (!ES_BUILD_PCL && !PROJECTN) [System.Runtime.ConstrainedExecution.ReliabilityContract( System.Runtime.ConstrainedExecution.Consistency.WillNotCorruptState, System.Runtime.ConstrainedExecution.Cer.Success)] #endif [SecurityCritical] [NonEvent] private unsafe void WriteCleanup(GCHandle* pPins, int cPins) { DataCollector.ThreadInstance.Disable(); for (int i = 0; i != cPins; i++) { if (IntPtr.Zero != (IntPtr)pPins[i]) { pPins[i].Free(); } } } private void InitializeProviderMetadata() { if (m_traits != null) { List<byte> traitMetaData = new List<byte>(100); for (int i = 0; i < m_traits.Length - 1; i += 2) { if (m_traits[i].StartsWith("ETW_")) { string etwTrait = m_traits[i].Substring(4); byte traitNum; if (!byte.TryParse(etwTrait, out traitNum)) { if (etwTrait == "GROUP") { traitNum = 1; } else { throw new ArgumentException(Resources.GetResourceString("UnknownEtwTrait", etwTrait), "traits"); } } string value = m_traits[i + 1]; int lenPos = traitMetaData.Count; traitMetaData.Add(0); // Emit size (to be filled in later) traitMetaData.Add(0); traitMetaData.Add(traitNum); // Emit Trait number var valueLen = AddValueToMetaData(traitMetaData, value) + 3; // Emit the value bytes +3 accounts for 3 bytes we emited above. traitMetaData[lenPos] = unchecked((byte)valueLen); // Fill in size traitMetaData[lenPos + 1] = unchecked((byte)(valueLen >> 8)); } } providerMetadata = Statics.MetadataForString(this.Name, 0, traitMetaData.Count, 0); int startPos = providerMetadata.Length - traitMetaData.Count; foreach (var b in traitMetaData) providerMetadata[startPos++] = b; } else providerMetadata = Statics.MetadataForString(this.Name, 0, 0, 0); } private static int AddValueToMetaData(List<byte> metaData, string value) { if (value.Length == 0) return 0; int startPos = metaData.Count; char firstChar = value[0]; if (firstChar == '@') metaData.AddRange(Encoding.UTF8.GetBytes(value.Substring(1))); else if (firstChar == '{') metaData.AddRange(new Guid(value).ToByteArray()); else if (firstChar == '#') { for (int i = 1; i < value.Length; i++) { if (value[i] != ' ') // Skip spaces between bytes. { if (!(i + 1 < value.Length)) { throw new ArgumentException(Resources.GetResourceString("EvenHexDigits"), "traits"); } metaData.Add((byte)(HexDigit(value[i]) * 16 + HexDigit(value[i + 1]))); i++; } } } else if ('A' <= firstChar || ' ' == firstChar) // Is it alphabetic or space (excludes digits and most punctuation). { metaData.AddRange(Encoding.UTF8.GetBytes(value)); } else { throw new ArgumentException(Resources.GetResourceString("IllegalValue", value), "traits"); } return metaData.Count - startPos; } /// <summary> /// Returns a value 0-15 if 'c' is a hexadecimal digit. If it throws an argument exception. /// </summary> private static int HexDigit(char c) { if ('0' <= c && c <= '9') { return (c - '0'); } if ('a' <= c) { c = unchecked((char)(c - ('a' - 'A'))); // Convert to lower case } if ('A' <= c && c <= 'F') { return (c - 'A' + 10); } throw new ArgumentException(Resources.GetResourceString("BadHexDigit", c), "traits"); } private NameInfo UpdateDescriptor( string name, TraceLoggingEventTypes eventInfo, ref EventSourceOptions options, out EventDescriptor descriptor) { NameInfo nameInfo = null; int identity = 0; byte level = (options.valuesSet & EventSourceOptions.levelSet) != 0 ? options.level : eventInfo.level; byte opcode = (options.valuesSet & EventSourceOptions.opcodeSet) != 0 ? options.opcode : eventInfo.opcode; EventTags tags = (options.valuesSet & EventSourceOptions.tagsSet) != 0 ? options.tags : eventInfo.Tags; EventKeywords keywords = (options.valuesSet & EventSourceOptions.keywordsSet) != 0 ? options.keywords : eventInfo.keywords; if (this.IsEnabled((EventLevel)level, keywords)) { nameInfo = eventInfo.GetNameInfo(name ?? eventInfo.Name, tags); identity = nameInfo.identity; } descriptor = new EventDescriptor(identity, level, opcode, (long)keywords); return nameInfo; } } }
using System; using System.ComponentModel; using System.IO; namespace UltraSFV.HashFunctions { public sealed class Crc32 { #region Fields private readonly static uint CrcSeed = 0xFFFFFFFF; private readonly static uint[] CrcTable = new uint[] { 0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, 0x076DC419, 0x706AF48F, 0xE963A535, 0x9E6495A3, 0x0EDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988, 0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91, 0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE, 0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7, 0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC, 0x14015C4F, 0x63066CD9, 0xFA0F3D63, 0x8D080DF5, 0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172, 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B, 0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940, 0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59, 0x26D930AC, 0x51DE003A, 0xC8D75180, 0xBFD06116, 0x21B4F4B5, 0x56B3C423, 0xCFBA9599, 0xB8BDA50F, 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924, 0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D, 0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A, 0x71B18589, 0x06B6B51F, 0x9FBFE4A5, 0xE8B8D433, 0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818, 0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01, 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E, 0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457, 0x65B0D9C6, 0x12B7E950, 0x8BBEB8EA, 0xFCB9887C, 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65, 0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2, 0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB, 0x4369E96A, 0x346ED9FC, 0xAD678846, 0xDA60B8D0, 0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9, 0x5005713C, 0x270241AA, 0xBE0B1010, 0xC90C2086, 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F, 0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4, 0x59B33D17, 0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD, 0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A, 0xEAD54739, 0x9DD277AF, 0x04DB2615, 0x73DC1683, 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8, 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1, 0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE, 0xF762575D, 0x806567CB, 0x196C3671, 0x6E6B06E7, 0xFED41B76, 0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC, 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5, 0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252, 0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B, 0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60, 0xDF60EFC3, 0xA867DF55, 0x316E8EEF, 0x4669BE79, 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236, 0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F, 0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04, 0xC2D7FFA7, 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D, 0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A, 0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713, 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38, 0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21, 0x86D3D2D4, 0xF1D4E242, 0x68DDB3F8, 0x1FDA836E, 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777, 0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C, 0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45, 0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2, 0xA7672661, 0xD06016F7, 0x4969474D, 0x3E6E77DB, 0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, 0x37D83BF0, 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9, 0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6, 0xBAD03605, 0xCDD70693, 0x54DE5729, 0x23D967BF, 0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94, 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D }; private uint crc = 0; // crc data checksum so far. #endregion #region Properties /// <summary> /// Returns the CRC32 data checksum computed so far. /// </summary> public uint Value { get { return crc; } set { crc = value; } } #endregion #region Static Methods public static uint GetStreamCRC32(Stream stream) { if (stream == null) throw new ArgumentNullException("stream"); if (!stream.CanRead) throw new ArgumentException("stream is not readable."); Crc32 crc32 = new Crc32(); byte[] buffer = new byte[4096]; int bytesRead = 0; stream.Position = 0; while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) != 0) { crc32.Update(buffer, 0, bytesRead); } stream.Position = 0; return crc32.Value; } public static uint GetFileCRC32(string path, ref long byteCount, BackgroundWorker bw) { if (String.IsNullOrEmpty(path)) throw new ArgumentNullException("path"); Crc32 crc32 = new Crc32(); using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read)) { byte[] buffer = new byte[4096]; int bytesRead = 0; long size = fs.Length; long totalBytesRead = 0; int ticks = 0; while ((bytesRead = fs.Read(buffer, 0, buffer.Length)) != 0) { ticks++; totalBytesRead += bytesRead; byteCount += bytesRead; crc32.Update(buffer, 0, bytesRead); if (bw != null && ticks == 10) // Only report once every 10 loops so we dont hose the CPU { bw.ReportProgress((int)((double)totalBytesRead * 100 / size)); ticks = 0; } } } return crc32.Value; } #endregion #region Constructor public Crc32() { } #endregion #region Public Methods /// <summary> /// Resets the CRC32 data checksum as if no update was ever called. /// </summary> public void Reset() { crc = 0; } /// <summary> /// Updates the checksum with the int bval. /// </summary> /// <param name="bval">the byte is taken as the lower 8 bits of bval</param> public void Update(int bval) { crc ^= CrcSeed; crc = CrcTable[(crc ^ bval) & 0xFF] ^ (crc >> 8); crc ^= CrcSeed; } /// <summary> /// Updates the checksum with the bytes taken from the array. /// </summary> /// <param name="buffer">buffer an array of bytes</param> public void Update(byte[] buffer) { Update(buffer, 0, buffer.Length); } /// <summary> /// Adds the byte array to the data checksum. /// </summary> /// <param name="buf">the buffer which contains the data</param> /// <param name="off">the offset in the buffer where the data starts</param> /// <param name="len">the length of the data</param> public void Update(byte[] buf, int off, int len) { if (buf == null) throw new ArgumentNullException("buf"); if (off < 0 || len < 0 || off + len > buf.Length) throw new ArgumentOutOfRangeException(); crc ^= CrcSeed; while (--len >= 0) { crc = CrcTable[(crc ^ buf[off++]) & 0xFF] ^ (crc >> 8); } crc ^= CrcSeed; } #endregion } }
#region License // Copyright 2010 John Sheehan // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #endregion using System; using System.Collections.Generic; using System.IO; using System.Net; using RestSharp.Serializers; namespace RestSharp { public interface IRestRequest { /// <summary> /// Always send a multipart/form-data request - even when no Files are present. /// </summary> bool AlwaysMultipartFormData { get; set; } /// <summary> /// Serializer to use when writing JSON request bodies. Used if RequestFormat is Json. /// By default the included JsonSerializer is used (currently using JSON.NET default serialization). /// </summary> ISerializer JsonSerializer { get; set; } /// <summary> /// Serializer to use when writing XML request bodies. Used if RequestFormat is Xml. /// By default the included XmlSerializer is used. /// </summary> ISerializer XmlSerializer { get; set; } /// <summary> /// Set this to write response to Stream rather than reading into memory. /// </summary> Action<Stream> ResponseWriter { get; set; } /// <summary> /// Container of all HTTP parameters to be passed with the request. /// See AddParameter() for explanation of the types of parameters that can be passed /// </summary> List<Parameter> Parameters { get; } /// <summary> /// Container of all the files to be uploaded with the request. /// </summary> List<FileParameter> Files { get; } /// <summary> /// Determines what HTTP method to use for this request. Supported methods: GET, POST, PUT, DELETE, HEAD, OPTIONS /// Default is GET /// </summary> Method Method { get; set; } /// <summary> /// The Resource URL to make the request against. /// Tokens are substituted with UrlSegment parameters and match by name. /// Should not include the scheme or domain. Do not include leading slash. /// Combined with RestClient.BaseUrl to assemble final URL: /// {BaseUrl}/{Resource} (BaseUrl is scheme + domain, e.g. http://example.com) /// </summary> /// <example> /// // example for url token replacement /// request.Resource = "Products/{ProductId}"; /// request.AddParameter("ProductId", 123, ParameterType.UrlSegment); /// </example> string Resource { get; set; } /// <summary> /// Serializer to use when writing XML request bodies. Used if RequestFormat is Xml. /// By default XmlSerializer is used. /// </summary> DataFormat RequestFormat { get; set; } /// <summary> /// Used by the default deserializers to determine where to start deserializing from. /// Can be used to skip container or root elements that do not have corresponding deserialzation targets. /// </summary> string RootElement { get; set; } /// <summary> /// Used by the default deserializers to explicitly set which date format string to use when parsing dates. /// </summary> string DateFormat { get; set; } /// <summary> /// Used by XmlDeserializer. If not specified, XmlDeserializer will flatten response by removing namespaces from element names. /// </summary> string XmlNamespace { get; set; } /// <summary> /// In general you would not need to set this directly. Used by the NtlmAuthenticator. /// </summary> ICredentials Credentials { get; set; } /// <summary> /// Timeout in milliseconds to be used for the request. This timeout value overrides a timeout set on the RestClient. /// </summary> int Timeout { get; set; } /// <summary> /// The number of milliseconds before the writing or reading times out. This timeout value overrides a timeout set on the RestClient. /// </summary> int ReadWriteTimeout { get; set; } /// <summary> /// How many attempts were made to send this Request? /// </summary> /// <remarks> /// This Number is incremented each time the RestClient sends the request. /// Useful when using Asynchronous Execution with Callbacks /// </remarks> int Attempts { get; } /// <summary> /// Determine whether or not the "default credentials" (e.g. the user account under which the current process is running) /// will be sent along to the server. The default is false. /// </summary> bool UseDefaultCredentials { get; set; } #if FRAMEWORK /// <summary> /// Adds a file to the Files collection to be included with a POST or PUT request /// (other methods do not support file uploads). /// </summary> /// <param name="name">The parameter name to use in the request</param> /// <param name="path">Full path to file to upload</param> /// <param name="contentType">The MIME type of the file to upload</param> /// <returns>This request</returns> IRestRequest AddFile(string name, string path, string contentType = null); /// <summary> /// Adds the bytes to the Files collection with the specified file name and content type /// </summary> /// <param name="name">The parameter name to use in the request</param> /// <param name="bytes">The file data</param> /// <param name="fileName">The file name to use for the uploaded file</param> /// <param name="contentType">The MIME type of the file to upload</param> /// <returns>This request</returns> IRestRequest AddFile(string name, byte[] bytes, string fileName, string contentType = null); /// <summary> /// Adds the bytes to the Files collection with the specified file name and content type /// </summary> /// <param name="name">The parameter name to use in the request</param> /// <param name="writer">A function that writes directly to the stream. Should NOT close the stream.</param> /// <param name="fileName">The file name to use for the uploaded file</param> /// <param name="contentType">The MIME type of the file to upload</param> /// <returns>This request</returns> IRestRequest AddFile(string name, Action<Stream> writer, string fileName, string contentType = null); #endif /// <summary> /// Serializes obj to format specified by RequestFormat, but passes xmlNamespace if using the default XmlSerializer /// The default format is XML. Change RequestFormat if you wish to use a different serialization format. /// </summary> /// <param name="obj">The object to serialize</param> /// <param name="xmlNamespace">The XML namespace to use when serializing</param> /// <returns>This request</returns> IRestRequest AddBody(object obj, string xmlNamespace); /// <summary> /// Serializes obj to data format specified by RequestFormat and adds it to the request body. /// The default format is XML. Change RequestFormat if you wish to use a different serialization format. /// </summary> /// <param name="obj">The object to serialize</param> /// <returns>This request</returns> IRestRequest AddBody(object obj); /// <summary> /// Serializes obj to JSON format and adds it to the request body. /// </summary> /// <param name="obj">The object to serialize</param> /// <returns>This request</returns> IRestRequest AddJsonBody(object obj); /// <summary> /// Serializes obj to XML format and adds it to the request body. /// </summary> /// <param name="obj">The object to serialize</param> /// <returns>This request</returns> IRestRequest AddXmlBody(object obj); /// <summary> /// Serializes obj to format specified by RequestFormat, but passes xmlNamespace if using the default XmlSerializer /// Serializes obj to XML format and passes xmlNamespace then adds it to the request body. /// </summary> /// <param name="obj">The object to serialize</param> /// <param name="xmlNamespace">The XML namespace to use when serializing</param> /// <returns>This request</returns> IRestRequest AddXmlBody(object obj, string xmlNamespace); /// <summary> /// Calls AddParameter() for all public, readable properties specified in the includedProperties list /// </summary> /// <example> /// request.AddObject(product, "ProductId", "Price", ...); /// </example> /// <param name="obj">The object with properties to add as parameters</param> /// <param name="includedProperties">The names of the properties to include</param> /// <returns>This request</returns> IRestRequest AddObject(object obj, params string[] includedProperties); /// <summary> /// Calls AddParameter() for all public, readable properties of obj /// </summary> /// <param name="obj">The object with properties to add as parameters</param> /// <returns>This request</returns> IRestRequest AddObject(object obj); /// <summary> /// Add the parameter to the request /// </summary> /// <param name="p">Parameter to add</param> /// <returns></returns> IRestRequest AddParameter(Parameter p); /// <summary> /// Adds a HTTP parameter to the request (QueryString for GET, DELETE, OPTIONS and HEAD; Encoded form for POST and PUT) /// </summary> /// <param name="name">Name of the parameter</param> /// <param name="value">Value of the parameter</param> /// <returns>This request</returns> IRestRequest AddParameter(string name, object value); /// <summary> /// Adds a parameter to the request. There are five types of parameters: /// - GetOrPost: Either a QueryString value or encoded form value based on method /// - HttpHeader: Adds the name/value pair to the HTTP request's Headers collection /// - UrlSegment: Inserted into URL if there is a matching url token e.g. {AccountId} /// - Cookie: Adds the name/value pair to the HTTP request's Cookies collection /// - RequestBody: Used by AddBody() (not recommended to use directly) /// </summary> /// <param name="name">Name of the parameter</param> /// <param name="value">Value of the parameter</param> /// <param name="type">The type of parameter to add</param> /// <returns>This request</returns> IRestRequest AddParameter(string name, object value, ParameterType type); /// <summary> /// Shortcut to AddParameter(name, value, HttpHeader) overload /// </summary> /// <param name="name">Name of the header to add</param> /// <param name="value">Value of the header to add</param> /// <returns></returns> IRestRequest AddHeader(string name, string value); /// <summary> /// Shortcut to AddParameter(name, value, Cookie) overload /// </summary> /// <param name="name">Name of the cookie to add</param> /// <param name="value">Value of the cookie to add</param> /// <returns></returns> IRestRequest AddCookie(string name, string value); /// <summary> /// Shortcut to AddParameter(name, value, UrlSegment) overload /// </summary> /// <param name="name">Name of the segment to add</param> /// <param name="value">Value of the segment to add</param> /// <returns></returns> IRestRequest AddUrlSegment(string name, string value); /// <summary> /// Shortcut to AddParameter(name, value, QueryString) overload /// </summary> /// <param name="name">Name of the parameter to add</param> /// <param name="value">Value of the parameter to add</param> /// <returns></returns> IRestRequest AddQueryParameter(string name, string value); Action<IRestResponse> OnBeforeDeserialization { get; set; } void IncreaseNumAttempts(); } }
using System; using CoreFoundation; using CoreGraphics; using Foundation; using MapKit; using ObjCRuntime; #if __MACOS__ using AppKit; using BoundUIImage = global::AppKit.NSImage; #elif __IOS__ || __TVOS__ using UIKit; using BoundUIImage = global::UIKit.UIImage; #endif namespace SDWebImage { // typedef void (^SDWebImageNoParamsBlock)(); delegate void SDWebImageNoParamsHandler (); #if __IOS__ // @interface FLAnimatedImageView : UIImageView [BaseType (typeof (UIImageView))] interface FLAnimatedImageView { // @property (nonatomic, strong) FLAnimatedImage * animatedImage; [Export ("animatedImage", ArgumentSemantic.Strong)] FLAnimatedImage AnimatedImage { get; set; } // @property (copy, nonatomic) void (^loopCompletionBlock)(NSUInteger); [Export ("loopCompletionBlock", ArgumentSemantic.Copy)] Action<nuint> LoopCompletionBlock { get; set; } // @property (readonly, nonatomic, strong) UIImage * currentFrame; [Export ("currentFrame", ArgumentSemantic.Strong)] UIImage CurrentFrame { get; } // @property (readonly, assign, nonatomic) NSUInteger currentFrameIndex; [Export ("currentFrameIndex")] nuint CurrentFrameIndex { get; } // @property (copy, nonatomic) NSString * runLoopMode; [Export ("runLoopMode")] string RunLoopMode { get; set; } } // @interface FLAnimatedImage : NSObject [BaseType (typeof (NSObject))] interface FLAnimatedImage { // @property (readonly, nonatomic, strong) UIImage * posterImage; [Export ("posterImage", ArgumentSemantic.Strong)] UIImage PosterImage { get; } // @property (readonly, assign, nonatomic) CGSize size; [Export ("size", ArgumentSemantic.Assign)] CGSize Size { get; } // @property (readonly, assign, nonatomic) NSUInteger loopCount; [Export ("loopCount")] nuint LoopCount { get; } // @property (readonly, nonatomic, strong) NSDictionary * delayTimesForIndexes; [Export ("delayTimesForIndexes", ArgumentSemantic.Strong)] NSDictionary DelayTimesForIndexes { get; } // @property (readonly, assign, nonatomic) NSUInteger frameCount; [Export ("frameCount")] nuint FrameCount { get; } // @property (readonly, assign, nonatomic) NSUInteger frameCacheSizeCurrent; [Export ("frameCacheSizeCurrent")] nuint FrameCacheSizeCurrent { get; } // @property (assign, nonatomic) NSUInteger frameCacheSizeMax; [Export ("frameCacheSizeMax")] nuint FrameCacheSizeMax { get; set; } // -(UIImage *)imageLazilyCachedAtIndex:(NSUInteger)index; [Export ("imageLazilyCachedAtIndex:")] UIImage ImageLazilyCached (nuint index); // +(CGSize)sizeForImage:(id)image; [Static] [Export ("sizeForImage:")] CGSize SizeForImage (NSObject image); // -(instancetype)initWithAnimatedGIFData:(NSData *)data; [Export ("initWithAnimatedGIFData:")] IntPtr Constructor (NSData data); // -(instancetype)initWithAnimatedGIFData:(NSData *)data optimalFrameCacheSize:(NSUInteger)optimalFrameCacheSize predrawingEnabled:(BOOL)isPredrawingEnabled __attribute__((objc_designated_initializer)); [Export ("initWithAnimatedGIFData:optimalFrameCacheSize:predrawingEnabled:")] [DesignatedInitializer] IntPtr Constructor (NSData data, nuint optimalFrameCacheSize, bool isPredrawingEnabled); // +(instancetype)animatedImageWithGIFData:(NSData *)data; [Static] [Export ("animatedImageWithGIFData:")] FLAnimatedImage CreateAnimatedImage (NSData data); // @property (readonly, nonatomic, strong) NSData * data; [Export ("data", ArgumentSemantic.Strong)] NSData Data { get; } } #endif interface ISDWebImageOperation { } // @protocol SDWebImageOperation <NSObject> [Protocol, Model] [BaseType (typeof (NSObject))] interface SDWebImageOperation { // @required -(void)cancel; [Abstract] [Export ("cancel")] void Cancel (); } // typedef void (^SDWebImageDownloaderProgressBlock)(NSInteger, NSInteger, NSURL * _Nullable); delegate void SDWebImageDownloaderProgressHandler (nint receivedSize, nint expectedSize, [NullAllowed] NSUrl url); // typedef void (^SDWebImageDownloaderCompletedBlock)(UIImage * _Nullable, NSData * _Nullable, NSError * _Nullable, BOOL); delegate void SDWebImageDownloaderCompletedHandler ([NullAllowed] BoundUIImage image, [NullAllowed] NSData data, [NullAllowed] NSError error, bool finished); // typedef SDHTTPHeadersDictionary * _Nullable (^SDWebImageDownloaderHeadersFilterBlock)(NSURL * _Nullable, SDHTTPHeadersDictionary * _Nullable); delegate NSDictionary SDWebImageDownloaderHeadersFilterHandler ([NullAllowed] NSUrl url, [NullAllowed] NSDictionary<NSString, NSString> headers); // @interface SDWebImageDownloadToken : NSObject [BaseType (typeof (NSObject))] interface SDWebImageDownloadToken { // @property (nonatomic, strong) NSURL * _Nullable url; [NullAllowed, Export ("url", ArgumentSemantic.Strong)] NSUrl Url { get; set; } // @property (nonatomic, strong) id _Nullable downloadOperationCancelToken; [NullAllowed, Export ("downloadOperationCancelToken", ArgumentSemantic.Strong)] NSObject DownloadOperationCancelToken { get; set; } } // @interface SDWebImageDownloader : NSObject [DisableDefaultCtor] [BaseType (typeof (NSObject))] interface SDWebImageDownloader { // @property (assign, nonatomic) BOOL shouldDecompressImages; [Export ("shouldDecompressImages")] bool ShouldDecompressImages { get; set; } // @property (assign, nonatomic) NSInteger maxConcurrentDownloads; [Export ("maxConcurrentDownloads")] nint MaxConcurrentDownloads { get; set; } // @property (readonly, nonatomic) NSUInteger currentDownloadCount; [Export ("currentDownloadCount")] nuint CurrentDownloadCount { get; } // @property (assign, nonatomic) NSTimeInterval downloadTimeout; [Export ("downloadTimeout")] double DownloadTimeout { get; set; } // @property (assign, nonatomic) SDWebImageDownloaderExecutionOrder executionOrder; [Export ("executionOrder", ArgumentSemantic.Assign)] SDWebImageDownloaderExecutionOrder ExecutionOrder { get; set; } // +(instancetype _Nonnull)sharedDownloader; [Static] [Export ("sharedDownloader")] SDWebImageDownloader SharedDownloader { get; } // @property (nonatomic, strong) NSURLCredential * _Nullable urlCredential; [NullAllowed, Export ("urlCredential", ArgumentSemantic.Strong)] NSUrlCredential UrlCredential { get; set; } // @property (nonatomic, strong) NSString * _Nullable username; [NullAllowed, Export ("username", ArgumentSemantic.Strong)] string Username { get; set; } // @property (nonatomic, strong) NSString * _Nullable password; [NullAllowed, Export ("password", ArgumentSemantic.Strong)] string Password { get; set; } // @property (copy, nonatomic) SDWebImageDownloaderHeadersFilterBlock _Nullable headersFilter; [NullAllowed, Export ("headersFilter", ArgumentSemantic.Copy)] SDWebImageDownloaderHeadersFilterHandler HeadersFilter { get; set; } // -(instancetype _Nonnull)initWithSessionConfiguration:(NSURLSessionConfiguration * _Nullable)sessionConfiguration __attribute__((objc_designated_initializer)); [Export ("initWithSessionConfiguration:")] [DesignatedInitializer] IntPtr Constructor ([NullAllowed] NSUrlSessionConfiguration sessionConfiguration); // -(void)setValue:(NSString * _Nullable)value forHTTPHeaderField:(NSString * _Nullable)field; [Export ("setValue:forHTTPHeaderField:")] void SetHttpHeaderValue ([NullAllowed] string value, [NullAllowed] string field); // -(NSString * _Nullable)valueForHTTPHeaderField:(NSString * _Nullable)field; [Export ("valueForHTTPHeaderField:")] [return: NullAllowed] string GetHttpHeaderValue ([NullAllowed] string field); // -(void)setOperationClass:(Class _Nullable)operationClass; [Export ("setOperationClass:")] void SetOperationClass ([NullAllowed] Class operationClass); // -(SDWebImageDownloadToken * _Nullable)downloadImageWithURL:(NSURL * _Nullable)url options:(SDWebImageDownloaderOptions)options progress:(SDWebImageDownloaderProgressBlock _Nullable)progressBlock completed:(SDWebImageDownloaderCompletedBlock _Nullable)completedBlock; [Export ("downloadImageWithURL:options:progress:completed:")] [return: NullAllowed] SDWebImageDownloadToken DownloadImage ([NullAllowed] NSUrl url, SDWebImageDownloaderOptions options, [NullAllowed] SDWebImageDownloaderProgressHandler progressHandler, [NullAllowed] SDWebImageDownloaderCompletedHandler completedHandler); // -(void)cancel:(SDWebImageDownloadToken * _Nullable)token; [Export ("cancel:")] void Cancel ([NullAllowed] SDWebImageDownloadToken token); // -(void)setSuspended:(BOOL)suspended; [Export ("setSuspended:")] void SetSuspended (bool suspended); // -(void)cancelAllDownloads; [Export ("cancelAllDownloads")] void CancelAllDownloads (); } // typedef void (^SDCacheQueryCompletedBlock)(UIImage * _Nullable, NSData * _Nullable, SDImageCacheType); delegate void SDCacheQueryCompletedHandler ([NullAllowed] BoundUIImage image, [NullAllowed] NSData data, SDImageCacheType cacheType); // typedef void (^SDWebImageCheckCacheCompletionBlock)(BOOL); delegate void SDWebImageCheckCacheCompletionHandler (bool isInCache); // typedef void (^SDWebImageCalculateSizeBlock)(NSUInteger, NSUInteger); delegate void SDImageCacheCalculateSizeHandler (nuint fileCount, nuint totalSize); // @interface SDImageCache : NSObject [DisableDefaultCtor] [BaseType (typeof (NSObject))] interface SDImageCache { // @property (readonly, nonatomic) SDImageCacheConfig * _Nonnull config; [Export ("config")] SDImageCacheConfig Config { get; } // @property (assign, nonatomic) NSUInteger maxMemoryCost; [Export ("maxMemoryCost")] nuint MaxMemoryCost { get; set; } // @property (assign, nonatomic) NSUInteger maxMemoryCountLimit; [Export ("maxMemoryCountLimit")] nuint MaxMemoryCountLimit { get; set; } // +(instancetype _Nonnull)sharedImageCache; [Static] [Export ("sharedImageCache")] SDImageCache SharedImageCache { get; } // -(instancetype _Nonnull)initWithNamespace:(NSString * _Nonnull)ns; [Export ("initWithNamespace:")] IntPtr Constructor (string ns); // -(instancetype _Nonnull)initWithNamespace:(NSString * _Nonnull)ns diskCacheDirectory:(NSString * _Nonnull)directory __attribute__((objc_designated_initializer)); [Export ("initWithNamespace:diskCacheDirectory:")] [DesignatedInitializer] IntPtr Constructor (string ns, string directory); // -(NSString * _Nullable)makeDiskCachePath:(NSString * _Nonnull)fullNamespace; [Export ("makeDiskCachePath:")] [return: NullAllowed] string MakeDiskCachePath (string fullNamespace); // -(void)addReadOnlyCachePath:(NSString * _Nonnull)path; [Export ("addReadOnlyCachePath:")] void AddReadOnlyCachePath (string path); // -(void)storeImage:(UIImage * _Nullable)image forKey:(NSString * _Nullable)key completion:(SDWebImageNoParamsBlock _Nullable)completionBlock; [Export ("storeImage:forKey:completion:")] void StoreImage ([NullAllowed] BoundUIImage image, [NullAllowed] string key, [NullAllowed] SDWebImageNoParamsHandler completionHandler); // -(void)storeImage:(UIImage * _Nullable)image forKey:(NSString * _Nullable)key toDisk:(BOOL)toDisk completion:(SDWebImageNoParamsBlock _Nullable)completionBlock; [Export ("storeImage:forKey:toDisk:completion:")] void StoreImage ([NullAllowed] BoundUIImage image, [NullAllowed] string key, bool toDisk, [NullAllowed] SDWebImageNoParamsHandler completionHandler); // -(void)storeImage:(UIImage * _Nullable)image imageData:(NSData * _Nullable)imageData forKey:(NSString * _Nullable)key toDisk:(BOOL)toDisk completion:(SDWebImageNoParamsBlock _Nullable)completionBlock; [Export ("storeImage:imageData:forKey:toDisk:completion:")] void StoreImage ([NullAllowed] BoundUIImage image, [NullAllowed] NSData imageData, [NullAllowed] string key, bool toDisk, [NullAllowed] SDWebImageNoParamsHandler completionHandler); // -(void)storeImageDataToDisk:(NSData * _Nullable)imageData forKey:(NSString * _Nullable)key; [Export ("storeImageDataToDisk:forKey:")] void StoreImageDataToDisk ([NullAllowed] NSData imageData, [NullAllowed] string key); // -(void)diskImageExistsWithKey:(NSString * _Nullable)key completion:(SDWebImageCheckCacheCompletionBlock _Nullable)completionBlock; [Export ("diskImageDataExistsWithKey:completion:")] void DiskImageExists ([NullAllowed] string key, [NullAllowed] SDWebImageCheckCacheCompletionHandler completionHandler); // - (nullable NSData *)diskImageDataForKey:(nullable NSString *)key; [Export("diskImageDataForKey:")] [return: NullAllowed] NSData DiskImageData([NullAllowed] string key); // -(NSOperation * _Nullable)queryCacheOperationForKey:(NSString * _Nullable)key done:(SDCacheQueryCompletedBlock _Nullable)doneBlock; [Export ("queryCacheOperationForKey:done:")] [return: NullAllowed] NSOperation QueryCacheOperation ([NullAllowed] string key, [NullAllowed] SDCacheQueryCompletedHandler doneHandler); // -(UIImage * _Nullable)imageFromMemoryCacheForKey:(NSString * _Nullable)key; [Export ("imageFromMemoryCacheForKey:")] [return: NullAllowed] BoundUIImage ImageFromMemoryCache ([NullAllowed] string key); // -(UIImage * _Nullable)imageFromDiskCacheForKey:(NSString * _Nullable)key; [Export ("imageFromDiskCacheForKey:")] [return: NullAllowed] BoundUIImage ImageFromDiskCache ([NullAllowed] string key); // -(UIImage * _Nullable)imageFromCacheForKey:(NSString * _Nullable)key; [Export ("imageFromCacheForKey:")] [return: NullAllowed] BoundUIImage ImageFromCache ([NullAllowed] string key); // -(void)removeImageForKey:(NSString * _Nullable)key withCompletion:(SDWebImageNoParamsBlock _Nullable)completion; [Export ("removeImageForKey:withCompletion:")] void RemoveImage ([NullAllowed] string key, [NullAllowed] SDWebImageNoParamsHandler completion); // -(void)removeImageForKey:(NSString * _Nullable)key fromDisk:(BOOL)fromDisk withCompletion:(SDWebImageNoParamsBlock _Nullable)completion; [Export ("removeImageForKey:fromDisk:withCompletion:")] void RemoveImage ([NullAllowed] string key, bool fromDisk, [NullAllowed] SDWebImageNoParamsHandler completion); // -(void)clearMemory; [Export ("clearMemory")] void ClearMemory (); // -(void)clearDiskOnCompletion:(SDWebImageNoParamsBlock _Nullable)completion; [Export ("clearDiskOnCompletion:")] void ClearDisk ([NullAllowed] SDWebImageNoParamsHandler completion); // -(void)deleteOldFilesWithCompletionBlock:(SDWebImageNoParamsBlock _Nullable)completionBlock; [Export ("deleteOldFilesWithCompletionBlock:")] void DeleteOldFiles ([NullAllowed] SDWebImageNoParamsHandler completionHandler); // -(NSUInteger)getSize; [Export ("getSize")] nuint Size { get; } // -(NSUInteger)getDiskCount; [Export ("getDiskCount")] nuint DiskCount { get; } // -(void)calculateSizeWithCompletionBlock:(SDWebImageCalculateSizeBlock _Nullable)completionBlock; [Export ("calculateSizeWithCompletionBlock:")] void CalculateSize ([NullAllowed] SDImageCacheCalculateSizeHandler completionHandler); // -(NSString * _Nullable)cachePathForKey:(NSString * _Nullable)key inPath:(NSString * _Nonnull)path; [Export ("cachePathForKey:inPath:")] [return: NullAllowed] string CachePath ([NullAllowed] string key, string path); // -(NSString * _Nullable)defaultCachePathForKey:(NSString * _Nullable)key; [Export ("defaultCachePathForKey:")] [return: NullAllowed] string DefaultCachePath ([NullAllowed] string key); } // typedef void (^SDExternalCompletionBlock)(UIImage * _Nullable, NSError * _Nullable, SDImageCacheType, NSURL * _Nullable); delegate void SDExternalCompletionHandler ([NullAllowed] BoundUIImage image, [NullAllowed] NSError error, SDImageCacheType cacheType, [NullAllowed] NSUrl imageUrl); // typedef void (^SDInternalCompletionBlock)(UIImage * _Nullable, NSData * _Nullable, NSError * _Nullable, SDImageCacheType, BOOL, NSURL * _Nullable); delegate void SDInternalCompletionHandler ([NullAllowed] BoundUIImage image, [NullAllowed] NSData data, [NullAllowed] NSError error, SDImageCacheType cacheType, bool finished, [NullAllowed] NSUrl imageUrl); // typedef NSString * _Nullable (^SDWebImageCacheKeyFilterBlock)(NSURL * _Nullable); delegate string SDWebImageCacheKeyFilterHandler ([NullAllowed] NSUrl url); interface ISDWebImageManagerDelegate { } // @protocol SDWebImageManagerDelegate <NSObject> [Protocol, Model] [BaseType (typeof (NSObject))] interface SDWebImageManagerDelegate { // @optional -(BOOL)imageManager:(SDWebImageManager * _Nonnull)imageManager shouldDownloadImageForURL:(NSURL * _Nullable)imageURL; [Export ("imageManager:shouldDownloadImageForURL:"), DelegateName ("SDWebImageManagerDelegateCondition"), DefaultValue (true)] bool ShouldDownloadImage (SDWebImageManager imageManager, [NullAllowed] NSUrl imageUrl); // @optional -(UIImage * _Nullable)imageManager:(SDWebImageManager * _Nonnull)imageManager transformDownloadedImage:(UIImage * _Nullable)image withURL:(NSURL * _Nullable)imageURL; [Export ("imageManager:transformDownloadedImage:withURL:"), DelegateName ("SDWebImageManagerDelegateImage"), DefaultValueFromArgument ("image")] [return: NullAllowed] BoundUIImage TransformDownloadedImage (SDWebImageManager imageManager, [NullAllowed] BoundUIImage image, [NullAllowed] NSUrl imageUrl); } // @interface SDWebImageManager : NSObject [DisableDefaultCtor] [BaseType (typeof (NSObject), Delegates = new string[] { "Delegate" }, Events = new Type[] { typeof (SDWebImageManagerDelegate) })] interface SDWebImageManager { // @property (nonatomic, weak) id<SDWebImageManagerDelegate> _Nullable delegate; [NullAllowed, Export ("delegate", ArgumentSemantic.Weak)] ISDWebImageManagerDelegate Delegate { get; set; } // @property (readonly, nonatomic, strong) SDImageCache * _Nullable imageCache; [NullAllowed, Export ("imageCache", ArgumentSemantic.Strong)] SDImageCache ImageCache { get; } // @property (readonly, nonatomic, strong) SDWebImageDownloader * _Nullable imageDownloader; [NullAllowed, Export ("imageDownloader", ArgumentSemantic.Strong)] SDWebImageDownloader ImageDownloader { get; } // @property (copy, nonatomic) SDWebImageCacheKeyFilterBlock _Nullable cacheKeyFilter; [NullAllowed, Export ("cacheKeyFilter", ArgumentSemantic.Copy)] SDWebImageCacheKeyFilterHandler CacheKeyFilter { get; set; } // +(instancetype _Nonnull)sharedManager; [Static] [Export ("sharedManager")] SDWebImageManager SharedManager { get; } // -(instancetype _Nonnull)initWithCache:(SDImageCache * _Nonnull)cache downloader:(SDWebImageDownloader * _Nonnull)downloader __attribute__((objc_designated_initializer)); [Export ("initWithCache:downloader:")] [DesignatedInitializer] IntPtr Constructor (SDImageCache cache, SDWebImageDownloader downloader); // -(id<SDWebImageOperation> _Nullable)loadImageWithURL:(NSURL * _Nullable)url options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock _Nullable)progressBlock completed:(SDInternalCompletionBlock _Nullable)completedBlock; [Export ("loadImageWithURL:options:progress:completed:")] [return: NullAllowed] ISDWebImageOperation LoadImage ([NullAllowed] NSUrl url, SDWebImageOptions options, [NullAllowed] SDWebImageDownloaderProgressHandler progressHandler, [NullAllowed] SDInternalCompletionHandler completedHandler); // -(void)saveImageToCache:(UIImage * _Nullable)image forURL:(NSURL * _Nullable)url; [Export ("saveImageToCache:forURL:")] void SaveImage ([NullAllowed] BoundUIImage image, [NullAllowed] NSUrl url); // -(void)cancelAll; [Export ("cancelAll")] void CancelAll (); // -(BOOL)isRunning; [Export ("isRunning")] bool IsRunning { get; } // -(void)cachedImageExistsForURL:(NSURL * _Nullable)url completion:(SDWebImageCheckCacheCompletionBlock _Nullable)completionBlock; [Export ("cachedImageExistsForURL:completion:")] void CachedImageExists ([NullAllowed] NSUrl url, [NullAllowed] SDWebImageCheckCacheCompletionHandler completionHandler); // -(void)diskImageExistsForURL:(NSURL * _Nullable)url completion:(SDWebImageCheckCacheCompletionBlock _Nullable)completionBlock; [Export ("diskImageExistsForURL:completion:")] void DiskImageExists ([NullAllowed] NSUrl url, [NullAllowed] SDWebImageCheckCacheCompletionHandler completionHandler); // -(NSString * _Nullable)cacheKeyForURL:(NSURL * _Nullable)url; [Export ("cacheKeyForURL:")] [return: NullAllowed] string GetCacheKey ([NullAllowed] NSUrl url); } #if __IOS__ // @interface WebCache (FLAnimatedImageView) [Category] [BaseType (typeof (FLAnimatedImageView))] interface FLAnimatedImageView_WebCache { // -(void)sd_setImageWithURL:(NSURL * _Nullable)url; [Export ("sd_setImageWithURL:")] void SetImage ([NullAllowed] NSUrl url); // -(void)sd_setImageWithURL:(NSURL * _Nullable)url placeholderImage:(UIImage * _Nullable)placeholder; [Export ("sd_setImageWithURL:placeholderImage:")] void SetImage ([NullAllowed] NSUrl url, [NullAllowed] UIImage placeholder); // -(void)sd_setImageWithURL:(NSURL * _Nullable)url placeholderImage:(UIImage * _Nullable)placeholder options:(SDWebImageOptions)options; [Export ("sd_setImageWithURL:placeholderImage:options:")] void SetImage ([NullAllowed] NSUrl url, [NullAllowed] UIImage placeholder, SDWebImageOptions options); // -(void)sd_setImageWithURL:(NSURL * _Nullable)url completed:(SDExternalCompletionBlock _Nullable)completedBlock; [Export ("sd_setImageWithURL:completed:")] void SetImage ([NullAllowed] NSUrl url, [NullAllowed] SDExternalCompletionHandler completedHandler); // -(void)sd_setImageWithURL:(NSURL * _Nullable)url placeholderImage:(UIImage * _Nullable)placeholder completed:(SDExternalCompletionBlock _Nullable)completedBlock; [Export ("sd_setImageWithURL:placeholderImage:completed:")] void SetImage ([NullAllowed] NSUrl url, [NullAllowed] UIImage placeholder, [NullAllowed] SDExternalCompletionHandler completedHandler); // -(void)sd_setImageWithURL:(NSURL * _Nullable)url placeholderImage:(UIImage * _Nullable)placeholder options:(SDWebImageOptions)options completed:(SDExternalCompletionBlock _Nullable)completedBlock; [Export ("sd_setImageWithURL:placeholderImage:options:completed:")] void SetImage ([NullAllowed] NSUrl url, [NullAllowed] UIImage placeholder, SDWebImageOptions options, [NullAllowed] SDExternalCompletionHandler completedHandler); // -(void)sd_setImageWithURL:(NSURL * _Nullable)url placeholderImage:(UIImage * _Nullable)placeholder options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock _Nullable)progressBlock completed:(SDExternalCompletionBlock _Nullable)completedBlock; [Export ("sd_setImageWithURL:placeholderImage:options:progress:completed:")] void SetImage ([NullAllowed] NSUrl url, [NullAllowed] UIImage placeholder, SDWebImageOptions options, [NullAllowed] SDWebImageDownloaderProgressHandler progressHandler, [NullAllowed] SDExternalCompletionHandler completedHandler); } #endif // @interface WebCache (MKAnnotationView) [Category] [BaseType (typeof (MKAnnotationView))] interface MKAnnotationView_WebCache { // -(void)sd_setImageWithURL:(NSURL * _Nullable)url; [Export ("sd_setImageWithURL:")] void SetImage ([NullAllowed] NSUrl url); // -(void)sd_setImageWithURL:(NSURL * _Nullable)url placeholderImage:(UIImage * _Nullable)placeholder; [Export ("sd_setImageWithURL:placeholderImage:")] void SetImage ([NullAllowed] NSUrl url, [NullAllowed] BoundUIImage placeholder); // -(void)sd_setImageWithURL:(NSURL * _Nullable)url placeholderImage:(UIImage * _Nullable)placeholder options:(SDWebImageOptions)options; [Export ("sd_setImageWithURL:placeholderImage:options:")] void SetImage ([NullAllowed] NSUrl url, [NullAllowed] BoundUIImage placeholder, SDWebImageOptions options); // -(void)sd_setImageWithURL:(NSURL * _Nullable)url completed:(SDExternalCompletionBlock _Nullable)completedBlock; [Export ("sd_setImageWithURL:completed:")] void SetImage ([NullAllowed] NSUrl url, [NullAllowed] SDExternalCompletionHandler completedHandler); // -(void)sd_setImageWithURL:(NSURL * _Nullable)url placeholderImage:(UIImage * _Nullable)placeholder completed:(SDExternalCompletionBlock _Nullable)completedBlock; [Export ("sd_setImageWithURL:placeholderImage:completed:")] void SetImage ([NullAllowed] NSUrl url, [NullAllowed] BoundUIImage placeholder, [NullAllowed] SDExternalCompletionHandler completedHandler); // -(void)sd_setImageWithURL:(NSURL * _Nullable)url placeholderImage:(UIImage * _Nullable)placeholder options:(SDWebImageOptions)options completed:(SDExternalCompletionBlock _Nullable)completedBlock; [Export ("sd_setImageWithURL:placeholderImage:options:completed:")] void SetImage ([NullAllowed] NSUrl url, [NullAllowed] BoundUIImage placeholder, SDWebImageOptions options, [NullAllowed] SDExternalCompletionHandler completedHandler); } // @interface ImageContentType (NSData) [Category] [BaseType (typeof (NSData))] interface NSData_ImageContentType { // +(SDImageFormat)sd_imageFormatForImageData:(NSData * _Nullable)data; [Static] [Export ("sd_imageFormatForImageData:")] SDImageFormat GetImageFormat ([NullAllowed] NSData data); } // @interface SDImageCacheConfig : NSObject [BaseType (typeof (NSObject))] interface SDImageCacheConfig { // @property (assign, nonatomic) BOOL shouldDecompressImages; [Export ("shouldDecompressImages")] bool ShouldDecompressImages { get; set; } // @property (assign, nonatomic) BOOL shouldDisableiCloud; [Export ("shouldDisableiCloud")] bool ShouldDisableiCloud { get; set; } // @property (assign, nonatomic) BOOL shouldUseWeakMemoryCache; [Export("shouldUseWeakMemoryCache")] bool ShouldUseWeakMemoryCache { get; set; } // @property (assign, nonatomic) BOOL shouldCacheImagesInMemory; [Export ("shouldCacheImagesInMemory")] bool ShouldCacheImagesInMemory { get; set; } // @property (assign, nonatomic) NSInteger maxCacheAge; [Export ("maxCacheAge")] nint MaxCacheAge { get; set; } // @property (assign, nonatomic) NSUInteger maxCacheSize; [Export ("maxCacheSize")] nuint MaxCacheSize { get; set; } // @property (assign, nonatomic) SDImageCacheConfigExpireType diskCacheExpireType; [Export("diskCacheExpireType")] SDImageCacheConfigExpireType DiskCacheExpireType { get;set; } } // @interface ForceDecode (UIImage) [Category] #if __IOS__ || __TVOS__ [BaseType (typeof (UIImage))] interface UIImage_ForceDecode #else [BaseType (typeof (NSImage))] interface NSImage_ForceDecode #endif { // +(UIImage * _Nullable)decodedImageWithImage:(UIImage * _Nullable)image; [Static] [Export ("decodedImageWithImage:")] [return: NullAllowed] BoundUIImage DecodedImage ([NullAllowed] BoundUIImage image); // +(UIImage * _Nullable)decodedAndScaledDownImageWithImage:(UIImage * _Nullable)image; [Static] [Export ("decodedAndScaledDownImageWithImage:")] [return: NullAllowed] BoundUIImage DecodedAndScaledDownImage ([NullAllowed] BoundUIImage image); } interface ISDWebImageDownloaderOperationInterface { } // @protocol SDWebImageDownloaderOperationInterface <NSObject> [Protocol, Model] [BaseType (typeof (NSObject))] interface SDWebImageDownloaderOperationInterface : INSUrlSessionTaskDelegate, INSUrlSessionDataDelegate { // We can not represent a ctor on an interface. Classes will have to implement // manually //// @required -(instancetype _Nonnull)initWithRequest:(NSURLRequest * _Nullable)request inSession:(NSURLSession * _Nullable)session options:(SDWebImageDownloaderOptions)options; //[Abstract] //[Export("initWithRequest:inSession:options:")] //IntPtr Constructor([NullAllowed] NSUrlRequest request, [NullAllowed] NSUrlSession session, SDWebImageDownloaderOptions options); // @required -(id _Nullable)addHandlersForProgress:(SDWebImageDownloaderProgressBlock _Nullable)progressBlock completed:(SDWebImageDownloaderCompletedBlock _Nullable)completedBlock; [Abstract] [Export ("addHandlersForProgress:completed:")] [return: NullAllowed] NSObject AddHandlers ([NullAllowed] SDWebImageDownloaderProgressHandler progressHandler, [NullAllowed] SDWebImageDownloaderCompletedHandler completedHandler); // @required -(BOOL)shouldDecompressImages; // @required -(void)setShouldDecompressImages:(BOOL)value; [Abstract] [Export ("shouldDecompressImages")] bool ShouldDecompressImages { get; set; } // @required - (nullable NSURLCredential *)credential; // @required - (void) setCredential:(nullable NSURLCredential *)value; [Abstract] [NullAllowed, Export ("credential", ArgumentSemantic.Strong)] NSUrlCredential Credential { get; set; } // @required -(BOOL)cancel:(id _Nullable)token; [Abstract] [Export ("cancel:")] bool Cancel ([NullAllowed] NSObject token); // @optional - (nullable NSURLSessionTask *)dataTask; [Abstract] [Export ("dataTask")] NSUrlSessionTask DataTask { get; } } // @interface SDWebImageDownloaderOperation : NSOperation <SDWebImageDownloaderOperationInterface, SDWebImageOperation, NSURLSessionTaskDelegate, NSURLSessionDataDelegate> [BaseType (typeof (NSOperation))] interface SDWebImageDownloaderOperation : SDWebImageDownloaderOperationInterface, SDWebImageOperation, INSUrlSessionTaskDelegate, INSUrlSessionDataDelegate { // @property (readonly, nonatomic, strong) NSURLRequest * _Nullable request; [NullAllowed, Export ("request", ArgumentSemantic.Strong)] NSUrlRequest Request { get; } // @property (readonly, nonatomic, strong) NSURLSessionTask * _Nullable dataTask; [NullAllowed, Export ("dataTask", ArgumentSemantic.Strong)] NSUrlSessionTask DataTask { get; } // @property (assign, nonatomic) BOOL shouldDecompressImages; [Export ("shouldDecompressImages")] bool ShouldDecompressImages { get; set; } // @property (assign, nonatomic) BOOL shouldUseCredentialStorage __attribute__((deprecated("Property deprecated. Does nothing. Kept only for backwards compatibility"))); [Export ("shouldUseCredentialStorage")] bool ShouldUseCredentialStorage { get; set; } // @property (nonatomic, strong) NSURLCredential * _Nullable credential; [NullAllowed, Export ("credential", ArgumentSemantic.Strong)] NSUrlCredential Credential { get; set; } // @property (readonly, assign, nonatomic) SDWebImageDownloaderOptions options; [Export ("options", ArgumentSemantic.Assign)] SDWebImageDownloaderOptions Options { get; } // @property (assign, nonatomic) NSInteger expectedSize; [Export ("expectedSize")] nint ExpectedSize { get; set; } // @property (nonatomic, strong) NSURLResponse * _Nullable response; [NullAllowed, Export ("response", ArgumentSemantic.Strong)] NSUrlResponse Response { get; set; } // -(instancetype _Nonnull)initWithRequest:(NSURLRequest * _Nullable)request inSession:(NSURLSession * _Nullable)session options:(SDWebImageDownloaderOptions)options __attribute__((objc_designated_initializer)); [Export ("initWithRequest:inSession:options:")] [DesignatedInitializer] IntPtr Constructor ([NullAllowed] NSUrlRequest request, [NullAllowed] NSUrlSession session, SDWebImageDownloaderOptions options); // -(id _Nullable)addHandlersForProgress:(SDWebImageDownloaderProgressBlock _Nullable)progressBlock completed:(SDWebImageDownloaderCompletedBlock _Nullable)completedBlock; [Export ("addHandlersForProgress:completed:")] [return: NullAllowed] NSObject AddHandlers ([NullAllowed] SDWebImageDownloaderProgressHandler progressHandler, [NullAllowed] SDWebImageDownloaderCompletedHandler completedHandler); // -(BOOL)cancel:(id _Nullable)token; [Export ("cancel:")] bool Cancel ([NullAllowed] NSObject token); } interface ISDWebImagePrefetcherDelegate { } // @protocol SDWebImagePrefetcherDelegate <NSObject> [Protocol, Model] [BaseType (typeof (NSObject))] interface SDWebImagePrefetcherDelegate { // @optional -(void)imagePrefetcher:(SDWebImagePrefetcher * _Nonnull)imagePrefetcher didPrefetchURL:(NSURL * _Nullable)imageURL finishedCount:(NSUInteger)finishedCount totalCount:(NSUInteger)totalCount; [Export ("imagePrefetcher:didPrefetchURL:finishedCount:totalCount:"), EventArgs ("SDWebImagePrefetcherDelegatePrefech"), EventName ("PrefetchedUrl")] void DidPrefetch (SDWebImagePrefetcher imagePrefetcher, [NullAllowed] NSUrl imageUrl, nuint finishedCount, nuint totalCount); // @optional -(void)imagePrefetcher:(SDWebImagePrefetcher * _Nonnull)imagePrefetcher didFinishWithTotalCount:(NSUInteger)totalCount skippedCount:(NSUInteger)skippedCount; [Export ("imagePrefetcher:didFinishWithTotalCount:skippedCount:"), EventArgs ("SDWebImagePrefetcherDelegateFinish"), EventName ("Finished")] void DidFinish (SDWebImagePrefetcher imagePrefetcher, nuint totalCount, nuint skippedCount); } // typedef void (^SDWebImagePrefetcherProgressBlock)(NSUInteger, NSUInteger); delegate void SDWebImagePrefetcherProgressHandler (nuint finishedCount, nuint totalCount); // typedef void (^SDWebImagePrefetcherCompletionBlock)(NSUInteger, NSUInteger); delegate void SDWebImagePrefetcherCompletionHandler (nuint finishedCount, nuint skippedCount); // @interface SDWebImagePrefetcher : NSObject [DisableDefaultCtor] [BaseType (typeof (NSObject), Delegates = new string[] { "Delegate" }, Events = new Type[] { typeof (SDWebImagePrefetcherDelegate) })] interface SDWebImagePrefetcher { // @property (readonly, nonatomic, strong) SDWebImageManager * _Nonnull manager; [Export ("manager", ArgumentSemantic.Strong)] SDWebImageManager Manager { get; } // @property (assign, nonatomic) NSUInteger maxConcurrentDownloads; [Export ("maxConcurrentDownloads")] nuint MaxConcurrentDownloads { get; set; } // @property (assign, nonatomic) SDWebImageOptions options; [Export ("options", ArgumentSemantic.Assign)] SDWebImageOptions Options { get; set; } // @property (assign, nonatomic) dispatch_queue_t _Nonnull prefetcherQueue; [Export ("prefetcherQueue", ArgumentSemantic.Assign)] DispatchQueue PrefetcherQueue { get; set; } // @property (nonatomic, weak) id<SDWebImagePrefetcherDelegate> _Nullable delegate; [NullAllowed, Export ("delegate", ArgumentSemantic.Weak)] ISDWebImagePrefetcherDelegate Delegate { get; set; } // +(instancetype _Nonnull)sharedImagePrefetcher; [Static] [Export ("sharedImagePrefetcher")] SDWebImagePrefetcher SharedImagePrefetcher { get; } // -(instancetype _Nonnull)initWithImageManager:(SDWebImageManager * _Nonnull)manager __attribute__((objc_designated_initializer)); [Export ("initWithImageManager:")] [DesignatedInitializer] IntPtr Constructor (SDWebImageManager manager); // -(void)prefetchURLs:(NSArray<NSURL *> * _Nullable)urls; [Export ("prefetchURLs:")] void PrefetchUrls ([NullAllowed] NSUrl[] urls); // -(void)prefetchURLs:(NSArray<NSURL *> * _Nullable)urls progress:(SDWebImagePrefetcherProgressBlock _Nullable)progressBlock completed:(SDWebImagePrefetcherCompletionBlock _Nullable)completionBlock; [Export ("prefetchURLs:progress:completed:")] void PrefetchUrls ([NullAllowed] NSUrl[] urls, [NullAllowed] SDWebImagePrefetcherProgressHandler progressHandler, [NullAllowed] SDWebImagePrefetcherCompletionHandler completionHandler); // -(void)cancelPrefetching; [Export ("cancelPrefetching")] void CancelPrefetching (); } #if __IOS__ || __TVOS__ // @interface WebCache (UIButton) [Category] [BaseType (typeof (UIButton))] interface UIButton_WebCache { // -(NSURL * _Nullable)sd_currentImageURL; [NullAllowed, Export ("sd_currentImageURL")] NSUrl GetImage (); // -(NSURL * _Nullable)sd_imageURLForState:(UIControlState)state; [Export ("sd_imageURLForState:")] [return: NullAllowed] NSUrl ImageUrl (UIControlState state); // -(void)sd_setImageWithURL:(NSURL * _Nullable)url forState:(UIControlState)state; [Export ("sd_setImageWithURL:forState:")] void SetImage ([NullAllowed] NSUrl url, UIControlState state); // -(void)sd_setImageWithURL:(NSURL * _Nullable)url forState:(UIControlState)state placeholderImage:(UIImage * _Nullable)placeholder; [Export ("sd_setImageWithURL:forState:placeholderImage:")] void SetImage ([NullAllowed] NSUrl url, UIControlState state, [NullAllowed] UIImage placeholder); // -(void)sd_setImageWithURL:(NSURL * _Nullable)url forState:(UIControlState)state placeholderImage:(UIImage * _Nullable)placeholder options:(SDWebImageOptions)options; [Export ("sd_setImageWithURL:forState:placeholderImage:options:")] void SetImage ([NullAllowed] NSUrl url, UIControlState state, [NullAllowed] UIImage placeholder, SDWebImageOptions options); // -(void)sd_setImageWithURL:(NSURL * _Nullable)url forState:(UIControlState)state completed:(SDExternalCompletionBlock _Nullable)completedBlock; [Export ("sd_setImageWithURL:forState:completed:")] void SetImage ([NullAllowed] NSUrl url, UIControlState state, [NullAllowed] SDExternalCompletionHandler completedHandler); // -(void)sd_setImageWithURL:(NSURL * _Nullable)url forState:(UIControlState)state placeholderImage:(UIImage * _Nullable)placeholder completed:(SDExternalCompletionBlock _Nullable)completedBlock; [Export ("sd_setImageWithURL:forState:placeholderImage:completed:")] void SetImage ([NullAllowed] NSUrl url, UIControlState state, [NullAllowed] UIImage placeholder, [NullAllowed] SDExternalCompletionHandler completedHandler); // -(void)sd_setImageWithURL:(NSURL * _Nullable)url forState:(UIControlState)state placeholderImage:(UIImage * _Nullable)placeholder options:(SDWebImageOptions)options completed:(SDExternalCompletionBlock _Nullable)completedBlock; [Export ("sd_setImageWithURL:forState:placeholderImage:options:completed:")] void SetImage ([NullAllowed] NSUrl url, UIControlState state, [NullAllowed] UIImage placeholder, SDWebImageOptions options, [NullAllowed] SDExternalCompletionHandler completedHandler); // -(void)sd_setBackgroundImageWithURL:(NSURL * _Nullable)url forState:(UIControlState)state; [Export ("sd_setBackgroundImageWithURL:forState:")] void SetBackgroundImage ([NullAllowed] NSUrl url, UIControlState state); // -(void)sd_setBackgroundImageWithURL:(NSURL * _Nullable)url forState:(UIControlState)state placeholderImage:(UIImage * _Nullable)placeholder; [Export ("sd_setBackgroundImageWithURL:forState:placeholderImage:")] void SetBackgroundImage ([NullAllowed] NSUrl url, UIControlState state, [NullAllowed] UIImage placeholder); // -(void)sd_setBackgroundImageWithURL:(NSURL * _Nullable)url forState:(UIControlState)state placeholderImage:(UIImage * _Nullable)placeholder options:(SDWebImageOptions)options; [Export ("sd_setBackgroundImageWithURL:forState:placeholderImage:options:")] void SetBackgroundImage ([NullAllowed] NSUrl url, UIControlState state, [NullAllowed] UIImage placeholder, SDWebImageOptions options); // -(void)sd_setBackgroundImageWithURL:(NSURL * _Nullable)url forState:(UIControlState)state completed:(SDExternalCompletionBlock _Nullable)completedBlock; [Export ("sd_setBackgroundImageWithURL:forState:completed:")] void SetBackgroundImage ([NullAllowed] NSUrl url, UIControlState state, [NullAllowed] SDExternalCompletionHandler completedHandler); // -(void)sd_setBackgroundImageWithURL:(NSURL * _Nullable)url forState:(UIControlState)state placeholderImage:(UIImage * _Nullable)placeholder completed:(SDExternalCompletionBlock _Nullable)completedBlock; [Export ("sd_setBackgroundImageWithURL:forState:placeholderImage:completed:")] void SetBackgroundImage ([NullAllowed] NSUrl url, UIControlState state, [NullAllowed] UIImage placeholder, [NullAllowed] SDExternalCompletionHandler completedHandler); // -(void)sd_setBackgroundImageWithURL:(NSURL * _Nullable)url forState:(UIControlState)state placeholderImage:(UIImage * _Nullable)placeholder options:(SDWebImageOptions)options completed:(SDExternalCompletionBlock _Nullable)completedBlock; [Export ("sd_setBackgroundImageWithURL:forState:placeholderImage:options:completed:")] void SetBackgroundImage ([NullAllowed] NSUrl url, UIControlState state, [NullAllowed] UIImage placeholder, SDWebImageOptions options, [NullAllowed] SDExternalCompletionHandler completedHandler); // -(void)sd_cancelImageLoadForState:(UIControlState)state; [Export ("sd_cancelImageLoadForState:")] void CancelImageLoad (UIControlState state); // -(void)sd_cancelBackgroundImageLoadForState:(UIControlState)state; [Export ("sd_cancelBackgroundImageLoadForState:")] void CancelBackgroundImageLoad (UIControlState state); } #endif // @interface GIF (UIImage) [Category] #if __IOS__ || __TVOS__ [BaseType (typeof (UIImage))] interface UIImage_Gif #else [BaseType (typeof (NSImage))] interface NSImage_Gif #endif { // +(UIImage *)sd_animatedGIFWithData:(NSData *)data; [Static] [Export ("sd_animatedGIFWithData:")] BoundUIImage CreateAnimatedGif (NSData data); // -(BOOL)isGIF; [Export ("isGif")] bool IsGif (); } // @interface MultiFormat (UIImage) [Category] #if __IOS__ || __TVOS__ [BaseType (typeof (UIImage))] interface UIImage_MultiFormat #else [BaseType (typeof (NSImage))] interface NSImage_MultiFormat #endif { // +(UIImage * _Nullable)sd_imageWithData:(NSData * _Nullable)data; [Static] [Export ("sd_imageWithData:")] [return: NullAllowed] BoundUIImage CreateImage ([NullAllowed] NSData data); // -(NSData * _Nullable)sd_imageData; [NullAllowed, Export ("sd_imageData")] NSData GetImageData (); // -(NSData * _Nullable)sd_imageDataAsFormat:(SDImageFormat)imageFormat; [Export ("sd_imageDataAsFormat:")] [return: NullAllowed] NSData GetImageData (SDImageFormat imageFormat); } #if __IOS__ || __TVOS__ // @interface HighlightedWebCache (UIImageView) [Category] [BaseType (typeof (UIImageView))] interface UIImageView_HighlightedWebCache { // -(void)sd_setHighlightedImageWithURL:(NSURL * _Nullable)url; [Export ("sd_setHighlightedImageWithURL:")] void SetHighlightedImage ([NullAllowed] NSUrl url); // -(void)sd_setHighlightedImageWithURL:(NSURL * _Nullable)url options:(SDWebImageOptions)options; [Export ("sd_setHighlightedImageWithURL:options:")] void SetHighlightedImage ([NullAllowed] NSUrl url, SDWebImageOptions options); // -(void)sd_setHighlightedImageWithURL:(NSURL * _Nullable)url completed:(SDExternalCompletionBlock _Nullable)completedBlock; [Export ("sd_setHighlightedImageWithURL:completed:")] void SetHighlightedImage ([NullAllowed] NSUrl url, [NullAllowed] SDExternalCompletionHandler completedHandler); // -(void)sd_setHighlightedImageWithURL:(NSURL * _Nullable)url options:(SDWebImageOptions)options completed:(SDExternalCompletionBlock _Nullable)completedBlock; [Export ("sd_setHighlightedImageWithURL:options:completed:")] void SetHighlightedImage ([NullAllowed] NSUrl url, SDWebImageOptions options, [NullAllowed] SDExternalCompletionHandler completedHandler); // -(void)sd_setHighlightedImageWithURL:(NSURL * _Nullable)url options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock _Nullable)progressBlock completed:(SDExternalCompletionBlock _Nullable)completedBlock; [Export ("sd_setHighlightedImageWithURL:options:progress:completed:")] void SetHighlightedImage ([NullAllowed] NSUrl url, SDWebImageOptions options, [NullAllowed] SDWebImageDownloaderProgressHandler progressHandler, [NullAllowed] SDExternalCompletionHandler completedHandler); } #endif // @interface WebCache (UIImageView) [Category] #if __IOS__ || __TVOS__ [BaseType (typeof (UIImageView))] interface UIImageView_WebCache #else [BaseType (typeof (NSImageView))] interface NSImageView_WebCache #endif { // -(void)sd_setImageWithURL:(NSURL * _Nullable)url; [Export ("sd_setImageWithURL:")] void SetImage ([NullAllowed] NSUrl url); // -(void)sd_setImageWithURL:(NSURL * _Nullable)url placeholderImage:(UIImage * _Nullable)placeholder; [Export ("sd_setImageWithURL:placeholderImage:")] void SetImage ([NullAllowed] NSUrl url, [NullAllowed] BoundUIImage placeholder); // -(void)sd_setImageWithURL:(NSURL * _Nullable)url placeholderImage:(UIImage * _Nullable)placeholder options:(SDWebImageOptions)options; [Export ("sd_setImageWithURL:placeholderImage:options:")] void SetImage ([NullAllowed] NSUrl url, [NullAllowed] BoundUIImage placeholder, SDWebImageOptions options); // -(void)sd_setImageWithURL:(NSURL * _Nullable)url completed:(SDExternalCompletionBlock _Nullable)completedBlock; [Export ("sd_setImageWithURL:completed:")] void SetImage ([NullAllowed] NSUrl url, [NullAllowed] SDExternalCompletionHandler completedHandler); // -(void)sd_setImageWithURL:(NSURL * _Nullable)url placeholderImage:(UIImage * _Nullable)placeholder completed:(SDExternalCompletionBlock _Nullable)completedBlock; [Export ("sd_setImageWithURL:placeholderImage:completed:")] void SetImage ([NullAllowed] NSUrl url, [NullAllowed] BoundUIImage placeholder, [NullAllowed] SDExternalCompletionHandler completedHandler); // -(void)sd_setImageWithURL:(NSURL * _Nullable)url placeholderImage:(UIImage * _Nullable)placeholder options:(SDWebImageOptions)options completed:(SDExternalCompletionBlock _Nullable)completedBlock; [Export ("sd_setImageWithURL:placeholderImage:options:completed:")] void SetImage ([NullAllowed] NSUrl url, [NullAllowed] BoundUIImage placeholder, SDWebImageOptions options, [NullAllowed] SDExternalCompletionHandler completedHandler); // -(void)sd_setImageWithURL:(NSURL * _Nullable)url placeholderImage:(UIImage * _Nullable)placeholder options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock _Nullable)progressBlock completed:(SDExternalCompletionBlock _Nullable)completedBlock; [Export ("sd_setImageWithURL:placeholderImage:options:progress:completed:")] void SetImage ([NullAllowed] NSUrl url, [NullAllowed] BoundUIImage placeholder, SDWebImageOptions options, [NullAllowed] SDWebImageDownloaderProgressHandler progressHandler, [NullAllowed] SDExternalCompletionHandler completedHandler); // -(void)sd_setImageWithPreviousCachedImageWithURL:(NSURL * _Nullable)url placeholderImage:(UIImage * _Nullable)placeholder options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock _Nullable)progressBlock completed:(SDExternalCompletionBlock _Nullable)completedBlock; [Export ("sd_setImageWithPreviousCachedImageWithURL:placeholderImage:options:progress:completed:")] void SetImageWithPreviousCachedImage ([NullAllowed] NSUrl url, [NullAllowed] BoundUIImage placeholder, SDWebImageOptions options, [NullAllowed] SDWebImageDownloaderProgressHandler progressHandler, [NullAllowed] SDExternalCompletionHandler completedHandler); #if __IOS__ || __TVOS__ // -(void)sd_setAnimationImagesWithURLs:(NSArray<NSURL *> * _Nonnull)arrayOfURLs; [Export ("sd_setAnimationImagesWithURLs:")] void SetAnimationImages (NSUrl[] arrayOfUrls); // -(void)sd_cancelCurrentAnimationImagesLoad; [Export ("sd_cancelCurrentAnimationImagesLoad")] void CancelCurrentAnimationImagesLoad (); #endif } // typedef void (^SDSetImageBlock)(UIImage * _Nullable, NSData * _Nullable); delegate void SDSetImageHandler ([NullAllowed] BoundUIImage image, [NullAllowed] NSData data); // typedef void(^SDInternalSetImageBlock)(UIImage * _Nullable image, NSData * _Nullable imageData, SDImageCacheType cacheType, NSURL * _Nullable imageURL); delegate void SDInternalSetImageHandler ([NullAllowed] BoundUIImage image, [NullAllowed]NSData imageDate, SDImageCacheType cacheType, NSUrl imageUrl); // @interface WebCache (UIView) [Category] #if __IOS__ || __TVOS__ [BaseType (typeof (UIView))] interface UIView_WebCache #else [BaseType (typeof (NSView))] interface NSView_WebCache #endif { // -(NSURL * _Nullable)sd_imageURL; [NullAllowed, Export ("sd_imageURL")] NSUrl GetImageUrl (); // -(void)sd_internalSetImageWithURL:(NSURL * _Nullable)url placeholderImage:(UIImage * _Nullable)placeholder options:(SDWebImageOptions)options operationKey:(NSString * _Nullable)operationKey setImageBlock:(SDSetImageBlock _Nullable)setImageBlock progress:(SDWebImageDownloaderProgressBlock _Nullable)progressBlock completed:(SDExternalCompletionBlock _Nullable)completedBlock; [Export ("sd_internalSetImageWithURL:placeholderImage:options:operationKey:setImageBlock:progress:completed:")] void InternalSetImage ([NullAllowed] NSUrl url, [NullAllowed] BoundUIImage placeholder, SDWebImageOptions options, [NullAllowed] string operationKey, [NullAllowed] SDSetImageHandler setImageHandler, [NullAllowed] SDWebImageDownloaderProgressHandler progressHandler, [NullAllowed] SDExternalCompletionHandler completedHandler); // -(void)sd_cancelCurrentImageLoad; [Export ("sd_cancelCurrentImageLoad")] void CancelCurrentImageLoad (); #if __IOS__ || __TVOS__ // -(void)sd_setShowActivityIndicatorView:(BOOL)show; [Export ("sd_setShowActivityIndicatorView:")] void SetShowActivityIndicatorView (bool show); // -(void)sd_setIndicatorStyle:(UIActivityIndicatorViewStyle)style; [Export ("sd_setIndicatorStyle:")] void SetIndicatorStyle (UIActivityIndicatorViewStyle style); // -(BOOL)sd_showActivityIndicatorView; [Export ("sd_showActivityIndicatorView")] bool ShowActivityIndicatorView (); // -(void)sd_addActivityIndicator; [Export ("sd_addActivityIndicator")] void AddActivityIndicator (); // -(void)sd_removeActivityIndicator; [Export ("sd_removeActivityIndicator")] void RemoveActivityIndicator (); #endif } // @interface WebCacheOperation (UIView) [Category] #if __IOS__ || __TVOS__ [BaseType (typeof (UIView))] interface UIView_WebCacheOperation #else [BaseType (typeof (NSView))] interface NSView_WebCacheOperation #endif { // -(void)sd_setImageLoadOperation:(id _Nullable)operation forKey:(NSString * _Nullable)key; [Export ("sd_setImageLoadOperation:forKey:")] void SetImageLoadOperation ([NullAllowed] NSObject operation, [NullAllowed] string key); // -(void)sd_cancelImageLoadOperationWithKey:(NSString * _Nullable)key; [Export ("sd_cancelImageLoadOperationWithKey:")] void CancelImageLoadOperation ([NullAllowed] string key); // -(void)sd_removeImageLoadOperationWithKey:(NSString * _Nullable)key; [Export ("sd_removeImageLoadOperationWithKey:")] void RemoveImageLoadOperation ([NullAllowed] string key); } #if __MACOS__ // @interface WebCache (NSImage) [Category] [BaseType (typeof (NSImage))] interface NSImage_WebCache { // -(CGImageRef)CGImage; [Export ("CGImage")] CGImage CGImage (); // -(NSArray<NSImage *> *)images; [Export ("images")] NSImage[] Images (); // -(BOOL)isGIF; [Export ("isGIF")] bool IsGif(); } #endif [Static] partial interface SDWebImageConstants { // extern NSString *const SDWebImageErrorDomain; [Field ("SDWebImageErrorDomain", "__Internal")] NSString ErrorDomain { get; } // extern NSString *const _Nonnull SDWebImageDownloadStartNotification; [Notification] [Field ("SDWebImageDownloadStartNotification", "__Internal")] NSString DownloadStartNotification { get; } // extern NSString *const _Nonnull SDWebImageDownloadStopNotification; [Notification] [Field ("SDWebImageDownloadStopNotification", "__Internal")] NSString DownloadStopNotification { get; } // extern NSString *const _Nonnull SDWebImageDownloadReceiveResponseNotification; [Notification] [Field ("SDWebImageDownloadReceiveResponseNotification", "__Internal")] NSString DownloadReceiveResponseNotification { get; } // extern NSString *const _Nonnull SDWebImageDownloadFinishNotification; [Notification] [Field ("SDWebImageDownloadFinishNotification", "__Internal")] NSString DownloadFinishNotification { get; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System.Xml.Xsl { using System.Reflection; using System.Diagnostics; using System.IO; using System.Xml.XPath; using System.Xml.Xsl.XsltOld; using MS.Internal.Xml.XPath; using MS.Internal.Xml.Cache; using System.Collections.Generic; using System.Xml.Xsl.XsltOld.Debugger; using System.Runtime.Versioning; public sealed class XslTransform { private XmlResolver _documentResolver = null; private bool _isDocumentResolverSet = false; private XmlResolver _DocumentResolver { get { if (_isDocumentResolverSet) return _documentResolver; else { return CreateDefaultResolver(); } } } // // Compiled stylesheet state // private Stylesheet _CompiledStylesheet; private List<TheQuery> _QueryStore; private RootAction _RootAction; private IXsltDebugger _debugger; public XslTransform() { } public XmlResolver XmlResolver { set { _documentResolver = value; _isDocumentResolverSet = true; } } public void Load(XmlReader stylesheet) { Load(stylesheet, CreateDefaultResolver()); } public void Load(XmlReader stylesheet, XmlResolver resolver) { if (stylesheet == null) { throw new ArgumentNullException(nameof(stylesheet)); } Load(new XPathDocument(stylesheet, XmlSpace.Preserve), resolver); } public void Load(IXPathNavigable stylesheet) { Load(stylesheet, CreateDefaultResolver()); } public void Load(IXPathNavigable stylesheet, XmlResolver resolver) { if (stylesheet == null) { throw new ArgumentNullException(nameof(stylesheet)); } Load(stylesheet.CreateNavigator(), resolver); } public void Load(XPathNavigator stylesheet) { if (stylesheet == null) { throw new ArgumentNullException(nameof(stylesheet)); } Load(stylesheet, CreateDefaultResolver()); } public void Load(XPathNavigator stylesheet, XmlResolver resolver) { if (stylesheet == null) { throw new ArgumentNullException(nameof(stylesheet)); } Compile(stylesheet, resolver); } public void Load(string url) { XmlTextReaderImpl tr = new XmlTextReaderImpl(url); Compile(Compiler.LoadDocument(tr).CreateNavigator(), CreateDefaultResolver()); } public void Load(string url, XmlResolver resolver) { XmlTextReaderImpl tr = new XmlTextReaderImpl(url); { tr.XmlResolver = resolver; } Compile(Compiler.LoadDocument(tr).CreateNavigator(), resolver); } // ------------------------------------ Transform() ------------------------------------ // private void CheckCommand() { if (_CompiledStylesheet == null) { throw new InvalidOperationException(SR.Xslt_NoStylesheetLoaded); } } public XmlReader Transform(XPathNavigator input, XsltArgumentList args, XmlResolver resolver) { CheckCommand(); Processor processor = new Processor(input, args, resolver, _CompiledStylesheet, _QueryStore, _RootAction, _debugger); return processor.StartReader(); } public XmlReader Transform(XPathNavigator input, XsltArgumentList args) { return Transform(input, args, _DocumentResolver); } public void Transform(XPathNavigator input, XsltArgumentList args, XmlWriter output, XmlResolver resolver) { CheckCommand(); Processor processor = new Processor(input, args, resolver, _CompiledStylesheet, _QueryStore, _RootAction, _debugger); processor.Execute(output); } public void Transform(XPathNavigator input, XsltArgumentList args, XmlWriter output) { Transform(input, args, output, _DocumentResolver); } public void Transform(XPathNavigator input, XsltArgumentList args, Stream output, XmlResolver resolver) { CheckCommand(); Processor processor = new Processor(input, args, resolver, _CompiledStylesheet, _QueryStore, _RootAction, _debugger); processor.Execute(output); } public void Transform(XPathNavigator input, XsltArgumentList args, Stream output) { Transform(input, args, output, _DocumentResolver); } public void Transform(XPathNavigator input, XsltArgumentList args, TextWriter output, XmlResolver resolver) { CheckCommand(); Processor processor = new Processor(input, args, resolver, _CompiledStylesheet, _QueryStore, _RootAction, _debugger); processor.Execute(output); } public void Transform(XPathNavigator input, XsltArgumentList args, TextWriter output) { CheckCommand(); Processor processor = new Processor(input, args, _DocumentResolver, _CompiledStylesheet, _QueryStore, _RootAction, _debugger); processor.Execute(output); } public XmlReader Transform(IXPathNavigable input, XsltArgumentList args, XmlResolver resolver) { if (input == null) { throw new ArgumentNullException(nameof(input)); } return Transform(input.CreateNavigator(), args, resolver); } public XmlReader Transform(IXPathNavigable input, XsltArgumentList args) { if (input == null) { throw new ArgumentNullException(nameof(input)); } return Transform(input.CreateNavigator(), args, _DocumentResolver); } public void Transform(IXPathNavigable input, XsltArgumentList args, TextWriter output, XmlResolver resolver) { if (input == null) { throw new ArgumentNullException(nameof(input)); } Transform(input.CreateNavigator(), args, output, resolver); } public void Transform(IXPathNavigable input, XsltArgumentList args, TextWriter output) { if (input == null) { throw new ArgumentNullException(nameof(input)); } Transform(input.CreateNavigator(), args, output, _DocumentResolver); } public void Transform(IXPathNavigable input, XsltArgumentList args, Stream output, XmlResolver resolver) { if (input == null) { throw new ArgumentNullException(nameof(input)); } Transform(input.CreateNavigator(), args, output, resolver); } public void Transform(IXPathNavigable input, XsltArgumentList args, Stream output) { if (input == null) { throw new ArgumentNullException(nameof(input)); } Transform(input.CreateNavigator(), args, output, _DocumentResolver); } public void Transform(IXPathNavigable input, XsltArgumentList args, XmlWriter output, XmlResolver resolver) { if (input == null) { throw new ArgumentNullException(nameof(input)); } Transform(input.CreateNavigator(), args, output, resolver); } public void Transform(IXPathNavigable input, XsltArgumentList args, XmlWriter output) { if (input == null) { throw new ArgumentNullException(nameof(input)); } Transform(input.CreateNavigator(), args, output, _DocumentResolver); } public void Transform(String inputfile, String outputfile, XmlResolver resolver) { FileStream fs = null; try { // We should read doc before creating output file in case they are the same XPathDocument doc = new XPathDocument(inputfile); fs = new FileStream(outputfile, FileMode.Create, FileAccess.ReadWrite); Transform(doc, /*args:*/null, fs, resolver); } finally { if (fs != null) { fs.Dispose(); } } } public void Transform(String inputfile, String outputfile) { Transform(inputfile, outputfile, _DocumentResolver); } // Implementation private void Compile(XPathNavigator stylesheet, XmlResolver resolver) { Debug.Assert(stylesheet != null); Compiler compiler = (Debugger == null) ? new Compiler() : new DbgCompiler(this.Debugger); NavigatorInput input = new NavigatorInput(stylesheet); compiler.Compile(input, resolver ?? XmlNullResolver.Singleton); Debug.Assert(compiler.CompiledStylesheet != null); Debug.Assert(compiler.QueryStore != null); Debug.Assert(compiler.QueryStore != null); _CompiledStylesheet = compiler.CompiledStylesheet; _QueryStore = compiler.QueryStore; _RootAction = compiler.RootAction; } internal IXsltDebugger Debugger { get { return _debugger; } } private static XmlResolver CreateDefaultResolver() { if (LocalAppContextSwitches.AllowDefaultResolver) { return new XmlUrlResolver(); } else { return XmlNullResolver.Singleton; } } private class DebuggerAddapter : IXsltDebugger { private object _unknownDebugger; private MethodInfo _getBltIn; private MethodInfo _onCompile; private MethodInfo _onExecute; public DebuggerAddapter(object unknownDebugger) { _unknownDebugger = unknownDebugger; BindingFlags flags = BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static; Type unknownType = unknownDebugger.GetType(); _getBltIn = unknownType.GetMethod("GetBuiltInTemplatesUri", flags); _onCompile = unknownType.GetMethod("OnInstructionCompile", flags); _onExecute = unknownType.GetMethod("OnInstructionExecute", flags); } // ------------------ IXsltDebugger --------------- public string GetBuiltInTemplatesUri() { if (_getBltIn == null) { return null; } return (string)_getBltIn.Invoke(_unknownDebugger, new object[] { }); } public void OnInstructionCompile(XPathNavigator styleSheetNavigator) { if (_onCompile != null) { _onCompile.Invoke(_unknownDebugger, new object[] { styleSheetNavigator }); } } public void OnInstructionExecute(IXsltProcessor xsltProcessor) { if (_onExecute != null) { _onExecute.Invoke(_unknownDebugger, new object[] { xsltProcessor }); } } } } }
// Copyright 2017 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 // // 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. using System; using System.Collections.Generic; using System.IO; using System.Text; using UnityEditor; using UnityEngine; using PolyToolkit; using PolyToolkitInternal; namespace PolyToolkitEditor { /// <summary> /// Model and controller for the Asset Browser Window. This class holds the data and handles the actual /// work). /// </summary> public class AssetBrowserManager { private const string PRODUCT_NAME = "PolyToolkit"; private const string CLIENT_SECRET = "49385a554c3274635d6c47327d3a3c557d67793e79267852"; private const string CLIENT_ID = "3539303a373737363831393b2178617c60227d7f7b7966252a74226e296f2d29174315175" + "15716131b1c5a4d1b034f5f40421c545b5a515b5d4c495e4e5e515134242c376a26292a"; private const string API_KEY = "41487862577c4474616e3b5f4b39466e5161732a4b645d5b495752557276274673196e74496173"; private const string DOWNLOAD_PROGRESS_TITLE = "Downloading..."; private const string DOWNLOAD_PROGRESS_TEXT = "Downloading asset. Please wait..."; /// <summary> /// If true, we are currently performing a query and waiting for the query result. /// </summary> private bool querying = false; /// <summary> /// The most recent query result that we have. /// </summary> private PolyStatusOr<PolyListAssetsResult> listAssetsResult = null; /// <summary> /// List of assets that are currently being downloaded. /// </summary> private HashSet<PolyAsset> assetsBeingDownloaded = new HashSet<PolyAsset>(); private Action refreshCallback = null; /// <summary> /// The most recent query result that we have. (read only) /// </summary> private PolyRequest currentRequest = null; /// <summary> /// Result of the most recent GetAsset request. /// </summary> private PolyAsset assetResult = null; /// <summary> /// Whether the current response has at least another page of results left that haven't been loaded yet. /// </summary> public bool resultHasMorePages = false; /// <summary> /// Result of the most recent GetAsset request. (read only) /// </summary> public PolyAsset CurrentAssetResult { get { return assetResult; } } /// <summary> /// The ID of the query that we are currently expecting the answer for. /// This is incremented every time we send out a query. /// </summary> private int queryId = 0; /// <summary> /// If true, we are waiting for the initial "silent authentication" to finish. /// </summary> private bool waitingForSilentAuth = false; /// <summary> /// If this is not null, we are waiting for the authentication to finish before sending this request. /// This request will be sent as soon as we get the auth callback. /// </summary> private PolyRequest requestToSendAfterAuth = null; private PolyAuthConfig authConfig = new PolyAuthConfig( apiKey: Deobfuscate(API_KEY), clientId: Deobfuscate(CLIENT_ID), clientSecret: Deobfuscate(CLIENT_SECRET)); private PolyCacheConfig cacheConfig = new PolyCacheConfig( cacheEnabled: true, maxCacheSizeMb: 512, maxCacheEntries: 2048); /// <summary> /// Cache of thumbnail images. /// </summary> private ThumbnailCache thumbnailCache = new ThumbnailCache(); /// <summary> /// Returns whether or not we are currently running a query. /// </summary> public bool IsQuerying { get { return querying; } } /// <summary> /// The result of the latest query, or null if there were no queries. /// </summary> public PolyStatusOr<PolyListAssetsResult> CurrentResult { get { return listAssetsResult; } } /// <summary> /// If true, we're currently in the process of downloading assets. /// </summary> public bool IsDownloadingAssets { get { return assetsBeingDownloaded.Count > 0; } } /// <summary> /// Assets currently being displayed in the browser. /// </summary> private HashSet<string> assetsInUse; public AssetBrowserManager() { PtDebug.Log("ABM initializing..."); EnsurePolyIsReady(); // Initially, show the featured assets home page. StartRequest(PolyListAssetsRequest.Featured()); } public AssetBrowserManager(PolyRequest request) { PtDebug.Log("ABM initializing..."); EnsurePolyIsReady(); // If this is a request that needs authentication and we are in the process of authenticating, // wait until we're finished. bool needAuth = request is PolyListLikedAssetsRequest || request is PolyListUserAssetsRequest; if (needAuth && waitingForSilentAuth) { // Defer the request. Wait until auth is complete. PtDebug.Log("ABM: Deferring request until after auth."); requestToSendAfterAuth = request; return; } StartRequest(request); } /// <summary> /// Because Poly doesn't live in the Editor/ space (and couldn't, since it uses GameObjects and /// MonoBehaviours), it will die every time the user enters or exits play mode. This means /// that all of its state and objects will get wiped. So we have to check if it needs initialization /// every time we need to use it. /// </summary> public void EnsurePolyIsReady() { if (!PolyApi.IsInitialized) { PtDebug.Log("ABM: Initializing Poly."); // We need to set a service name for our auth config because we want to keep our auth credentials // separate in a different "silo", so they don't get confused with the runtime credentials // the user might be using in their project. Regular users would not set a service name, so they // use the default silo. authConfig.serviceName = "PolyToolkitEditor"; PolyApi.Init(authConfig, cacheConfig); waitingForSilentAuth = true; PolyApi.Authenticate(interactive: false, callback: (PolyStatus status) => { waitingForSilentAuth = false; OnSignInFinished(/* wasInteractive */ false, status); }); } } /// <summary> /// Launches the interactive sign-in flow (launches a browser to perform sign-in). /// </summary> public void LaunchSignInFlow() { PolyApi.Authenticate(interactive: true, callback: (PolyStatus status) => { OnSignInFinished(/* wasInteractive */ true, status); }); } /// <summary> /// Cancels the authentication flow. /// </summary> public void CancelSignIn() { PolyApi.CancelAuthentication(); } /// <summary> /// Sets the callback that will be called whenever there is a change in this object's /// data (search results, etc). This should be used to update any UI. /// </summary> /// <param name="refreshCallback">The callback to call, null for none.</param> public void SetRefreshCallback(Action refreshCallback) { this.refreshCallback = refreshCallback; } /// <summary> /// Returns whether or not the given asset is in the process of being downloaded. /// </summary> /// <param name="asset">The asset to check.</param> /// <returns>True if it's being downloaded, false if not.</returns> public bool IsDownloadingAsset(PolyAsset asset) { return assetsBeingDownloaded.Contains(asset); } /// <summary> /// Starts a new request. If there is already an existing request in progress, it will be cancelled. /// </summary> /// <param name="request">The request parameters; can be either a ListAssetsRequest or /// a PolyListUserAssetsRequest.</param> public void StartRequest(PolyRequest request) { StartRequest(request, OnRequestResult); } /// <summary> /// Clear the current get asset result. /// </summary> public void ClearCurrentAssetResult() { assetResult = null; } /// <summary> /// Get the next page of assets from the current request. /// </summary> public void GetNextPageRequest() { PtDebug.Log("ABM: getting next page of current request..."); if (CurrentResult == null || !CurrentResult.Ok) { Debug.LogError("Request failed, no valid current result to get next page of."); } currentRequest.pageToken = CurrentResult.Value.nextPageToken; StartRequest(currentRequest, OnNextPageRequestResult); } /// <summary> /// Starts a new request. If there is already an existing request in progress, it will be cancelled. /// </summary> /// <param name="request">The request parameters; can be either a ListAssetsRequest or /// a PolyListUserAssetsRequest.</param> /// <param name="callback"> The callback to invoke when the request finishes.</param> private void StartRequest(PolyRequest request, Action<PolyStatusOr<PolyListAssetsResult>> callback) { int thisQueryId = PrepareForNewQuery(); // for the closure below. currentRequest = request; if (request is PolyListAssetsRequest) { PolyListAssetsRequest listAssetsRequest = request as PolyListAssetsRequest; PolyApi.ListAssets(listAssetsRequest, (PolyStatusOr<PolyListAssetsResult> result) => { // Only process result if this is indeed the most recent query that we issued. // If we have issued another query since (in which case thisQueryId < queryId), // then ignore the result. if (thisQueryId == queryId && callback != null) callback(result); }); } else if (request is PolyListUserAssetsRequest) { PolyListUserAssetsRequest listUserAssetsRequest = request as PolyListUserAssetsRequest; PolyApi.ListUserAssets(listUserAssetsRequest, (PolyStatusOr<PolyListAssetsResult> result) => { if (thisQueryId == queryId && callback != null) callback(result); }); } else if (request is PolyListLikedAssetsRequest) { PolyListLikedAssetsRequest listLikedAssetsRequest = request as PolyListLikedAssetsRequest; PolyApi.ListLikedAssets(listLikedAssetsRequest, (PolyStatusOr<PolyListAssetsResult> result) => { if (thisQueryId == queryId && callback != null) callback(result); }); } else { Debug.LogError("Request failed. Must be either a PolyListAssetsRequest or PolyListUserAssetsRequest"); } } /// <summary> /// Starts a new request for a specific asset. If there is already an existing /// request in progress, it will be cancelled. /// </summary> /// <param name="assetId">Id of the asset to get.</param> public void StartRequestForSpecificAsset(string assetId) { int thisQueryId = PrepareForNewQuery(); PolyApi.GetAsset(assetId, (PolyStatusOr<PolyAsset> result) => { if (thisQueryId == queryId) OnRequestForSpecificAssetResult(result); }); } /// <summary> /// Helper method to prepare the manager for starting a new query. /// </summary> private int PrepareForNewQuery() { querying = true; queryId++; assetResult = null; return queryId; } /// <summary> /// Clears the current request. Also cancels any pending request. /// </summary> public void ClearRequest() { PtDebug.Log("ABM: clearing request..."); querying = false; // Increasing the ID will cause us to ignore the results of any pending requests // (we will know they are obsolete by their query ID). queryId++; listAssetsResult = null; resultHasMorePages = false; } /// <summary> /// Called when sign in finishes. /// </summary> /// <param name="wasInteractive">If true, this was the interactive (browser-based) sign-in flow.</param> /// <param name="status">The result of the sign in process.</param> private void OnSignInFinished(bool wasInteractive, PolyStatus status) { if (status.ok) { string tok = PolyApi.AccessToken; PtDebug.LogFormat("ABM: Sign in success. Access token: {0}", (tok != null && tok.Length > 6) ? tok.Substring(0, 6) + "..." : "INVALID"); PtAnalytics.SendEvent(PtAnalytics.Action.ACCOUNT_SIGN_IN_SUCCESS); } else if (wasInteractive) { Debug.LogErrorFormat("Failed to sign in. Please try again: " + status); PtAnalytics.SendEvent(PtAnalytics.Action.ACCOUNT_SIGN_IN_FAILURE, status.ToString()); } if (null != refreshCallback) refreshCallback(); // If we had a deferred request that was waiting for auth, send it now. if (requestToSendAfterAuth != null) { PtDebug.Log("Sending deferred request that was waiting for auth."); PolyRequest request = requestToSendAfterAuth; requestToSendAfterAuth = null; StartRequest(request); } } /// <summary> /// Callback invoked when the request for the next page of assets returns; appends /// received assets to the existing result. /// </summary> private void OnNextPageRequestResult(PolyStatusOr<PolyListAssetsResult> result) { if (result.Ok) { PtDebug.LogFormat("ABM: request results received ({0} assets).", result.Value.assets.Count); this.listAssetsResult.Value.assets.AddRange(result.Value.assets); this.listAssetsResult.Value.nextPageToken = result.Value.nextPageToken; resultHasMorePages = result.Value.nextPageToken != null; } else { Debug.LogError("Asset request failed. Try again later: " + result.Status); this.listAssetsResult = result; } querying = false; if (null != refreshCallback) refreshCallback(); assetsInUse = GetAssetsInUse(); FinishFetchingThumbnails(result); } /// <summary> /// Callback invoked when we get request results. /// </summary> private void OnRequestResult(PolyStatusOr<PolyListAssetsResult> result) { if (result.Ok) { PtDebug.LogFormat("ABM: request results received ({0} assets).", result.Value.assets.Count); this.listAssetsResult = result; resultHasMorePages = result.Value.nextPageToken != null; } else { Debug.LogError("Asset request failed. Try again later: " + result.Status); this.listAssetsResult = result; } querying = false; if (null != refreshCallback) refreshCallback(); if (result.Ok) { assetsInUse = GetAssetsInUse(); FinishFetchingThumbnails(result); } } /// <summary> /// Callback invoked when we receive the result of a request for a specific asset. /// </summary> private void OnRequestForSpecificAssetResult(PolyStatusOr<PolyAsset> result) { if (result.Ok) { PtDebug.Log("ABM: get asset request received result."); assetResult = result.Value; if (!thumbnailCache.TryGet(assetResult.name, out assetResult.thumbnailTexture)) { PolyApi.FetchThumbnail(assetResult, OnThumbnailFetched); } } else { Debug.LogError("Error: " + result.Status.errorMessage); } querying = false; if (null != refreshCallback) refreshCallback(); } /// <summary> /// Fetches thumbnails that do not yet exist in the cache. /// </summary> private void FinishFetchingThumbnails(PolyStatusOr<PolyListAssetsResult> result) { if (result.Ok) { List<PolyAsset> assetsMissingThumbnails = new List<PolyAsset>(); foreach (PolyAsset asset in listAssetsResult.Value.assets) { if (!thumbnailCache.TryGet(asset.name, out asset.thumbnailTexture)) { assetsMissingThumbnails.Add(asset); } } foreach (PolyAsset asset in assetsMissingThumbnails) { PolyApi.FetchThumbnail(asset, OnThumbnailFetched); } } } /// <summary> /// Callback invoked when an asset thumbnail is fetched. /// </summary> private void OnThumbnailFetched(PolyAsset asset, PolyStatus status) { if (status.ok) { thumbnailCache.Put(asset.name, asset.thumbnailTexture); // Preserve the texture so it survives round-trips to play mode and back. asset.thumbnailTexture.hideFlags = HideFlags.HideAndDontSave; } if (null != refreshCallback) refreshCallback(); thumbnailCache.TrimCacheWithExceptions(assetsInUse); } /// <summary> /// Returns a set of asset ids of assets currently being displayed. /// </summary> private HashSet<string> GetAssetsInUse() { HashSet<string> assetsInUse = new HashSet<string>(); if (listAssetsResult == null || !listAssetsResult.Ok) return assetsInUse; foreach (var asset in listAssetsResult.Value.assets) { assetsInUse.Add(asset.name); } return assetsInUse; } /// <summary> /// Starts downloading and importing the given asset (in the background). When done, the asset will /// be saved to the user's Assets folder. /// </summary> /// <param name="asset">The asset to download and import.</param> /// <param name="ptAssetLocalPath">Path to the PtAsset that should be created (or replaced).</param> /// <param name="options">Import options.</param> public void StartDownloadAndImport(PolyAsset asset, string ptAssetLocalPath, EditTimeImportOptions options) { if (!assetsBeingDownloaded.Add(asset)) return; PtDebug.LogFormat("ABM: starting to fetch asset {0} ({1}) -> {2}", asset.name, asset.displayName, ptAssetLocalPath); // Prefer glTF2 format. PolyFormat glTF2format = asset.GetFormatIfExists(PolyFormatType.GLTF_2); PolyFormat glTFformat = asset.GetFormatIfExists(PolyFormatType.GLTF); PolyMainInternal.FetchProgressCallback progressCallback = (PolyAsset assetBeingFetched, float progress) => { EditorUtility.DisplayProgressBar(DOWNLOAD_PROGRESS_TITLE, DOWNLOAD_PROGRESS_TEXT, progress); }; if (glTF2format != null) { EditorUtility.DisplayProgressBar(DOWNLOAD_PROGRESS_TITLE, DOWNLOAD_PROGRESS_TEXT, 0.0f); PolyMainInternal.Instance.FetchFormatFiles(asset, PolyFormatType.GLTF_2, (PolyAsset resultAsset, PolyStatus status) => { EditorUtility.ClearProgressBar(); OnFetchFinished(status, resultAsset, /*isGltf2*/ true, ptAssetLocalPath, options); }, progressCallback); } else if (glTFformat != null) { EditorUtility.DisplayProgressBar(DOWNLOAD_PROGRESS_TITLE, DOWNLOAD_PROGRESS_TEXT, 0.0f); PolyMainInternal.Instance.FetchFormatFiles(asset, PolyFormatType.GLTF, (PolyAsset resultAsset, PolyStatus status) => { EditorUtility.ClearProgressBar(); OnFetchFinished(status, resultAsset, /*isGltf2*/ false, ptAssetLocalPath, options); }, progressCallback); } else { Debug.LogError("Asset not in GLTF_2 or GLTF format. Can't import."); PtAnalytics.SendEvent(PtAnalytics.Action.IMPORT_FAILED, "Unsupported format"); } } /// <summary> /// Clears all caches (downloads and thumbnails). /// </summary> public void ClearCaches() { PolyApi.ClearCache(); thumbnailCache.Clear(); } private void OnFetchFinished(PolyStatus status, PolyAsset asset, bool isGltf2, string ptAssetLocalPath, EditTimeImportOptions options) { if (!status.ok) { Debug.LogErrorFormat("Error fetching asset {0} ({1}): {2}", asset.name, asset.displayName, status); EditorUtility.DisplayDialog("Download Error", string.Format("*** Error downloading asset '{0}'. Try again later.", asset.displayName), "OK"); PtAnalytics.SendEvent(PtAnalytics.Action.IMPORT_FAILED, "Asset fetch failed"); return; } string baseName, downloadLocalPath; if (!PrepareDownload(asset, out baseName, out downloadLocalPath)) { return; } string absPath = PtUtils.ToAbsolutePath(downloadLocalPath); string extension = isGltf2 ? ".gltf2" : ".gltf"; string fileName = baseName + extension; // We have to place an import request so that PolyImporter does the right thing when it sees the new file. PolyImporter.AddImportRequest(new PolyImporter.ImportRequest( downloadLocalPath + "/" + fileName, ptAssetLocalPath, options, asset)); // Now unpackage it. GltfProcessor will pick it up automatically. UnpackPackageToFolder(isGltf2 ? asset.GetFormatIfExists(PolyFormatType.GLTF_2) : asset.GetFormatIfExists(PolyFormatType.GLTF), absPath, fileName); PtDebug.LogFormat("ABM: Successfully downloaded {0} to {1}", asset, absPath); AssetDatabase.Refresh(); if (null != refreshCallback) refreshCallback(); } private void UnpackPackageToFolder(PolyFormat package, string destFolder, string mainFileName) { // First write the resources, then the main file, so that when the main file is imported // all the necessary resources are already in place. // Maintain a mapping of original file names to their corresponding hash. StringBuilder fileMapSb = new StringBuilder(); foreach (PolyFile file in package.resources) { // In order to avoid having to replicate the original directory structure of the // asset (which might be incompatible with our file system, or even maliciously constructed), // we replace the original path of each resource file with the MD5 hash of the path. // That maintains uniqueness of paths and flattens the structure so that every resource // can live in the same directory. string path = Path.Combine(destFolder, PolyInternalUtils.ConvertFilePathToHash(file.relativePath)); if (file.contents != null) { File.WriteAllBytes(path, file.contents); fileMapSb.AppendFormat("{0} -> {1}\n", file.relativePath, PolyInternalUtils.ConvertFilePathToHash(file.relativePath)); } } // Lastly, write the main file. File.WriteAllBytes(Path.Combine(destFolder, mainFileName), package.root.contents); // Write the file mapping. File.WriteAllText(Path.Combine(destFolder, "FileNameMapping.txt"), fileMapSb.ToString()); } private bool PrepareDownload(PolyAsset asset, out string baseName, out string downloadLocalPath) { assetsBeingDownloaded.Remove(asset); PtDebug.LogFormat("ABM: Preparing to download {0}", asset); // basePath is something like Assets/Poly/Sources. string baseLocalPath = PtUtils.NormalizeLocalPath(PtSettings.Instance.assetSourcesPath); if (!baseLocalPath.StartsWith("Assets/")) { Debug.LogErrorFormat("Invalid asset sources folder {0}. Must be under Assets folder."); baseName = downloadLocalPath = null; return false; } // basePathAbs is something like C:\Users\foo\bar\MyUnityProject\Assets\Poly\Sources string baseFullPath = PtUtils.ToAbsolutePath(baseLocalPath); if (!Directory.Exists(baseFullPath)) { Directory.CreateDirectory(baseFullPath); } baseName = PtUtils.GetPtAssetBaseName(asset); PtDebug.LogFormat("Import name: {0}", baseName); // downloadLocalPath is something like Assets/Poly/Sources/assetTitle_assetId downloadLocalPath = baseLocalPath + "/" + baseName; string downloadFullPath = PtUtils.ToAbsolutePath(downloadLocalPath); if (Directory.Exists(downloadFullPath)) { if (PtSettings.Instance.warnOnSourceOverwrite && !EditorUtility.DisplayDialog("Warning: Overwriting asset source folder", string.Format("The asset source folder '{0}' will be deleted and created again. " + "This should be safe *unless* you have manually made changes to its contents, " + "in which case you will lose those changes.\n\n" + "(You can silence this warning in Poly Toolkit settings)", asset.displayName, downloadLocalPath), "OK", "Cancel")) return false; Directory.Delete(downloadFullPath, /* recursive */ true); } // Create the download folder. // Something like C:\Users\foo\bar\MyUnityProject\Assets\Poly\Sources\assetTitle_assetId Directory.CreateDirectory(downloadFullPath); return true; } private static string Obfuscate(string input) { byte[] data = Encoding.UTF8.GetBytes(input); StringBuilder sb = new StringBuilder(); for (int i = 0; i < data.Length; i++) { byte b = (byte)(data[i] ^ i); sb.Append(b.ToString("x2")); } return sb.ToString(); } public static string Deobfuscate(string input) { byte[] data = new byte[input.Length / 2]; for (int i = 0; i < data.Length; i++) { byte b = Convert.ToByte(input.Substring(i * 2, 2), 16); data[i] = (byte)(b ^ i); } return Encoding.UTF8.GetString(data); } } }
#region Copyright (C) 2013 // Project hw.nuget // Copyright (C) 2013 - 2013 Harald Hoyer // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (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, see <http://www.gnu.org/licenses/>. // // Comments, bugs and suggestions to hahoyer at yahoo.de #endregion using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Reflection; using System.Windows.Forms; using hw.Helper; using JetBrains.Annotations; namespace hw.TreeStructure { public static class Extender { /// <summary> /// Creates a treenode.with a given title from an object /// </summary> /// <param name="nodeData"> </param> /// <param name="title"> </param> /// <param name="iconKey"> </param> /// <param name="isDefaultIcon"> </param> /// <returns> </returns> public static TreeNode CreateNode(this object nodeData, string title = "", string iconKey = null, bool isDefaultIcon = false) { var result = new TreeNode(title + nodeData.GetAdditionalInfo()) {Tag = nodeData}; if(iconKey == null) iconKey = nodeData.GetIconKey(); if(isDefaultIcon) { var defaultIcon = nodeData.GetIconKey(); if(defaultIcon != null) iconKey = defaultIcon; } if(iconKey != null) { result.ImageKey = iconKey; result.SelectedImageKey = iconKey; } return result; } /// <summary> /// Creates a treenode.with a given title from an object (format: &lt;title&gt;: &lt;nodeData.ToString()&gt;) /// </summary> /// <param name="title"> The title. </param> /// <param name="iconKey"> The icon key. </param> /// <param name="nodeData"> The node data. Can be <see cref="IIconKeyProvider" /> </param> /// <returns> </returns> public static TreeNode CreateTaggedNode(this object nodeData, string title, string iconKey) { return nodeData.CreateTaggedNode(title, iconKey, false); } /// <summary> /// Creates a treenode.with a given title from an object (format: &lt;title&gt; = &lt;nodeData.ToString()&gt;) /// </summary> /// <param name="title"> The title. </param> /// <param name="iconKey"> The icon key. </param> /// <param name="nodeData"> The node data. Can be <see cref="IIconKeyProvider" /> </param> /// <returns> </returns> public static TreeNode CreateNamedNode(this object nodeData, string title, string iconKey) { return nodeData.CreateNamedNode(title, iconKey, false); } /// <summary> /// Creates a treenode.with a given title from an object (format: &lt;title&gt; = &lt;nodeData.ToString()&gt;) /// </summary> /// <param name="title"> The title. </param> /// <param name="iconKey"> The icon key. </param> /// <param name="isDefaultIcon"> if set to <c>true</c> [is default icon]. </param> /// <param name="nodeData"> The node data. Can be <see cref="IIconKeyProvider" /> </param> /// <returns> </returns> /// created 06.02.2007 23:26 public static TreeNode CreateNamedNode(this object nodeData, string title, string iconKey, bool isDefaultIcon) { return nodeData.CreateNode(title + " = ", iconKey, isDefaultIcon); } /// <summary> /// Creates a treenode.with a given title from an object (format: &lt;title&gt;: &lt;nodeData.ToString()&gt;) /// </summary> /// <param name="title"> The title. </param> /// <param name="iconKey"> The icon key. </param> /// <param name="isDefaultIcon"> if set to <c>true</c> [is default icon]. </param> /// <param name="nodeData"> The node data. Can be <see cref="IIconKeyProvider" /> </param> /// <returns> </returns> /// created 06.02.2007 23:26 public static TreeNode CreateTaggedNode(this object nodeData, string title, string iconKey, bool isDefaultIcon) { return nodeData.CreateNode(title + ": ", iconKey, isDefaultIcon); } /// <summary> /// Creates a treenode.with a given title from an object (format: &lt;title&gt;: &lt;nodeData.ToString()&gt;) /// </summary> /// <param name="title"> The title. </param> /// <param name="nodeData"> The node data. Can be <see cref="IIconKeyProvider" /> </param> /// <returns> </returns> public static TreeNode CreateTaggedNode(this object nodeData, string title) { return nodeData.CreateTaggedNode(title, null, false); } /// <summary> /// Creates a treenode.with a given title from an object (format: &lt;title&gt; = &lt;nodeData.ToString()&gt;) /// </summary> /// <param name="title"> The title. </param> /// <param name="nodeData"> The node data. Can be <see cref="IIconKeyProvider" /> </param> /// <returns> </returns> public static TreeNode CreateNamedNode(this object nodeData, string title) { return nodeData.CreateNamedNode(title, null, false); } static TreeNode[] InternalCreateNodes(IDictionary dictionary) { var result = new List<TreeNode>(); foreach(var element in dictionary) result.Add(CreateNumberedNode(element, result.Count, "ListItem")); return result.ToArray(); } static TreeNode CreateNumberedNode(object nodeData, int i, string iconKey, bool isDefaultIcon = false) { return nodeData.CreateNode("[" + i + "] ", iconKey, isDefaultIcon); } static TreeNode[] InternalCreateNodes(IList list) { var result = new List<TreeNode>(); foreach(var o in list) result.Add(CreateNumberedNode(o, result.Count, "ListItem", true)); return result.ToArray(); } static TreeNode[] InternalCreateNodes(DictionaryEntry dictionaryEntry) { return new[] {dictionaryEntry.Key.CreateTaggedNode("key", "Key", true), dictionaryEntry.Value.CreateTaggedNode("value")}; } /// <summary> /// Gets the name of the icon. /// </summary> /// <param name="nodeData"> The node data. </param> /// <returns> </returns> static string GetIconKey(this object nodeData) { if(nodeData == null) return null; var ip = nodeData as IIconKeyProvider; if(ip != null) return ip.IconKey; if(nodeData is string) return "String"; if(nodeData is bool) return "Bool"; if(nodeData.GetType().IsPrimitive) return "Number"; if(nodeData is IDictionary) return "Dictionary"; if(nodeData is IList) return "List"; return null; } [NotNull] internal static string GetAdditionalInfo([CanBeNull] this object nodeData) { if(nodeData == null) return "<null>"; var additionalNodeInfoProvider = nodeData as IAdditionalNodeInfoProvider; if(additionalNodeInfoProvider != null) return additionalNodeInfoProvider.AdditionalNodeInfo; var attrs = nodeData.GetType().GetCustomAttributes(typeof(AdditionalNodeInfoAttribute), true); if(attrs.Length > 0) { var attr = (AdditionalNodeInfoAttribute) attrs[0]; return nodeData.GetType().GetProperty(attr.Property).GetValue(nodeData, null).ToString(); } var il = nodeData as IList; if(il != null) return il.GetType().PrettyName() + "[" + ((IList) nodeData).Count + "]"; var nameSpace = nodeData.GetType().Namespace; if(nameSpace != null && nameSpace.StartsWith("System")) return nodeData.ToString(); return ""; } static TreeNode[] InternalCreateNodes(object target) { var result = new List<TreeNode>(); result.AddRange(CreateFieldNodes(target)); result.AddRange(CreatePropertyNodes(target)); return result.ToArray(); } public static TreeNode[] CreateNodes(this object target) { if(target == null) return new TreeNode[0]; var xn = target as ITreeNodeSupport; if(xn != null) return xn.CreateNodes().ToArray(); return CreateAutomaticNodes(target); } public static TreeNode[] CreateAutomaticNodes(this object target) { var xl = target as IList; if(xl != null) return InternalCreateNodes(xl); var xd = target as IDictionary; if(xd != null) return InternalCreateNodes(xd); if(target is DictionaryEntry) return InternalCreateNodes((DictionaryEntry) target); return InternalCreateNodes(target); } static TreeNode[] CreatePropertyNodes(object nodeData) { return nodeData.GetType().GetProperties(DefaultBindingFlags).Select(propertyInfo => CreateTreeNode(nodeData, propertyInfo)).Where(treeNode => treeNode != null).ToArray(); } static TreeNode[] CreateFieldNodes(object nodeData) { return nodeData.GetType().GetFieldInfos().Select(fieldInfo => CreateTreeNode(nodeData, fieldInfo)).Where(treeNode => treeNode != null).ToArray(); } static BindingFlags DefaultBindingFlags { get { return BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.FlattenHierarchy; } } static TreeNode CreateTreeNode(object nodeData, FieldInfo fieldInfo) { return CreateTreeNode(fieldInfo, () => Value(fieldInfo, nodeData)); } static TreeNode CreateTreeNode(object nodeData, PropertyInfo propertyInfo) { return CreateTreeNode(propertyInfo, () => Value(propertyInfo, nodeData)); } static object Value(FieldInfo fieldInfo, object nodeData) { return fieldInfo.GetValue(nodeData); } static object Value(PropertyInfo propertyInfo, object nodeData) { return propertyInfo.GetValue(nodeData, null); } static TreeNode CreateTreeNode(MemberInfo memberInfo, Func<object> getValue) { var attribute = memberInfo.GetAttribute<NodeAttribute>(true); if(attribute == null) return null; var value = CatchedEval(getValue); if(value == null) return null; var result = CreateNamedNode(value, memberInfo.Name, attribute.IconKey); if(memberInfo.GetAttribute<SmartNodeAttribute>(true) == null) return result; return SmartNodeAttribute.Process(result); } static object CatchedEval(Func<object> value) { try { return value(); } catch(Exception e) { return e; } } static void CreateNodeList(TreeNodeCollection nodes, object target) { var treeNodes = CreateNodes(target); //Tracer.FlaggedLine(treeNodes.Dump()); //Tracer.ConditionalBreak(treeNodes.Length == 20,""); nodes.Clear(); nodes.AddRange(treeNodes); } public static void Connect(this TreeView treeView, object target) { Connect(target, treeView); } public static void Connect(this object target, TreeView treeView) { CreateNodeList(treeView.Nodes, target); AddSubNodes(treeView.Nodes); treeView.BeforeExpand += BeforeExpand; } static void AddSubNodesAsync(TreeNodeCollection nodes) { lock(nodes) { var backgroundWorker = new BackgroundWorker(); backgroundWorker.DoWork += ((sender, e) => AddSubNodes(nodes)); backgroundWorker.RunWorkerAsync(); } } static void AddSubNodes(TreeNodeCollection nodes) { foreach(TreeNode node in nodes) CreateNodeList(node); } internal static void CreateNodeList(this TreeNode node) { CreateNodeList(node.Nodes, node.Tag); } static void BeforeExpand(object sender, TreeViewCancelEventArgs e) { AddSubNodes(e.Node.Nodes); } } }
namespace iTin.Export.Model { using System; using System.ComponentModel; using System.Diagnostics; using System.Drawing; using System.Globalization; using System.Text; using System.Xml.Serialization; using ComponentModel; /// <summary> /// Base class for different data types supported by <strong><c>iTin Export Engine</c></strong>.<br /> /// Which acts as the base class for different data types. /// </summary> /// <remarks> /// <para>The following table shows different data types.</para> /// <list type="table"> /// <listheader> /// <term>Class</term> /// <description>Description</description> /// </listheader> /// <item> /// <term><see cref="T:iTin.Export.Model.CurrencyDataTypeModel" /></term> /// <description>Represents currency data type. The currency symbol appears right next to the first digit. You can specify the number of decimal places that you want to use and how you want to display negative numbers.</description> /// </item> /// <item> /// <term><see cref="T:iTin.Export.Model.DatetimeDataTypeModel" /></term> /// <description>Represents date time data field. Displays data field as datetime format. You can specify the output culture.</description> /// </item> /// <item> /// <term><see cref="T:iTin.Export.Model.NumberDataTypeModel" /></term> /// <description>Represents numeric data type. You can specify the number of decimal places that you want to use, whether you want to use a thousands separator, and how you want to display negative numbers.</description> /// </item> /// <item> /// <term><see cref="T:iTin.Export.Model.PercentageDataTypeModel" /></term> /// <description>Represents percentage data type. Displays the result with a percent sign (%). You can specify the number of decimal places to use.</description> /// </item> /// <item> /// <term><see cref="T:iTin.Export.Model.ScientificDataTypeModel" /></term> /// <description>Represents scientific data type. Displays a number in exponential notation, which replaces part of the number with E + n, where E (exponent) multiplies the preceding number by 10 to n. You can specify the number of decimal places you want to use.</description> /// </item> /// <item> /// <term><see cref="T:iTin.Export.Model.SpecialDataTypeModel" /></term> /// <description>Represents special data type. Displays a number as a short date or as a long date.</description> /// </item> /// <item> /// <term><see cref="T:iTin.Export.Model.TextDataTypeModel" /></term> /// <description>Represents text data type. Treats the content as text and displays the content exactly as written, even when numbers are typed.</description> /// </item> /// </list> /// </remarks> public partial class BaseDataTypeModel : ICloneable { #region field members [DebuggerBrowsable(DebuggerBrowsableState.Never)] private ContentModel _parent; #endregion #region public properties #region [public] (ContentModel) Parent: Parent: Gets the parent element of the element /// <summary> /// Gets the parent element of the element. /// </summary> /// <value> /// The element that represents the container element of the element. /// </value> [XmlIgnore] [Browsable(false)] public ContentModel Parent => _parent; #endregion #region [public] (KnownDataType) Type: Gets a value indicating data type /// <summary> /// Gets a value indicating data type. /// </summary> /// <value> /// One of the <see cref="T:iTin.Export.Model.KnownDataType" /> values. /// </value> public KnownDataType Type { get { var dataFormatType = GetType().Name; switch (dataFormatType) { case "CurrencyDataTypeModel": return KnownDataType.Currency; case "DatetimeDataTypeModel": return KnownDataType.Datetime; case "NumberDataTypeModel": return KnownDataType.Numeric; case "PercentageDataTypeModel": return KnownDataType.Percentage; case "ScientificDataTypeModel": return KnownDataType.Scientific; case "SpecialDataTypeModel": return KnownDataType.Special; default: return KnownDataType.Text; } } } #endregion #endregion #region public methods #region [public] (BaseDataTypeModel) Clone(): Clones this instance /// <summary> /// Clones this instance. /// </summary> /// <returns>A new object that is a copy of this instance.</returns> public BaseDataTypeModel Clone() { switch (Type) { case KnownDataType.Currency: return ((CurrencyDataTypeModel)this).Clone(); case KnownDataType.Datetime: return ((DatetimeDataTypeModel)this).Clone(); case KnownDataType.Numeric: return ((NumericDataTypeModel)this).Clone(); case KnownDataType.Percentage: return ((PercentageDataTypeModel)this).Clone(); case KnownDataType.Scientific: return ((ScientificDataTypeModel)this).Clone(); default: return ((TextDataTypeModel)this).Clone(); } } #endregion #region [public] (void) Combine(BaseDataTypeModel): Combines this instance with reference parameter /// <summary> /// Combines this instance with reference parameter. /// </summary> /// <param name="reference">The reference.</param> public void Combine(BaseDataTypeModel reference) { switch (Type) { case KnownDataType.Currency: ((CurrencyDataTypeModel)this).Combine((CurrencyDataTypeModel)reference); break; case KnownDataType.Datetime: ((DatetimeDataTypeModel)this).Combine((DatetimeDataTypeModel)reference); break; case KnownDataType.Numeric: ((NumericDataTypeModel)this).Combine((NumericDataTypeModel)reference); break; case KnownDataType.Percentage: ((PercentageDataTypeModel)this).Combine((PercentageDataTypeModel)reference); break; case KnownDataType.Scientific: ((ScientificDataTypeModel)this).Combine((ScientificDataTypeModel)reference); break; case KnownDataType.Text: break; } } #endregion #region [public] (string) GetDataFormat(): Returns data format for a data type. /// <summary> /// Returns data format for a data type. /// </summary> /// <returns> /// Data format. /// </returns> public string GetDataFormat() { var culture = CultureInfo.CurrentCulture; var formatBuilder = new StringBuilder(); switch (Type) { #region Type: Numeric case KnownDataType.Numeric: var number = (NumberDataTypeModel)this; var numberDecimals = number.Decimals; var numberPositivePatternArray = new[] { "n" }; var numberNegativePatternArray = new[] { "(n)", "-n", "- n", "n-", "n -" }; var currentNumberPositivePattern = numberPositivePatternArray[0]; var currentNumberNegativePattern = numberNegativePatternArray[culture.NumberFormat.NumberNegativePattern]; var numberPositivePatternBuilder = new StringBuilder(); numberPositivePatternBuilder.Append(number.Separator == YesNo.Yes ? "#,##0" : "##0"); if (numberDecimals > 0) { var digits = new string('0', numberDecimals); numberPositivePatternBuilder.Append("."); numberPositivePatternBuilder.Append(digits); } var numberPositivePattern = numberPositivePatternBuilder.ToString(); currentNumberPositivePattern = currentNumberPositivePattern.Replace("n", numberPositivePattern); var numberNegativePatternWithSignBuilder = new StringBuilder(); currentNumberNegativePattern = currentNumberNegativePattern.Replace("n", numberPositivePattern); switch (number.Negative.Sign) { case KnownNegativeSign.None: currentNumberNegativePattern = currentNumberNegativePattern.Replace("-", string.Empty) .Replace("(", string.Empty) .Replace(")", string.Empty); numberNegativePatternWithSignBuilder.Append(currentNumberNegativePattern); break; case KnownNegativeSign.Standard: if (currentNumberNegativePattern.Contains("-")) { currentNumberNegativePattern = currentNumberNegativePattern.Replace("-", culture.NumberFormat.NegativeSign); } numberNegativePatternWithSignBuilder.Append(currentNumberNegativePattern); break; case KnownNegativeSign.Parenthesis: currentNumberNegativePattern = currentNumberNegativePattern.Replace("-", string.Empty) .Replace("(", string.Empty) .Replace(")", string.Empty); numberNegativePatternWithSignBuilder.Append("("); numberNegativePatternWithSignBuilder.Append(currentNumberNegativePattern); numberNegativePatternWithSignBuilder.Append(")"); break; case KnownNegativeSign.Brackets: currentNumberNegativePattern = currentNumberNegativePattern.Replace("-", string.Empty) .Replace("(", string.Empty) .Replace(")", string.Empty); numberNegativePatternWithSignBuilder.Append("["); numberNegativePatternWithSignBuilder.Append(currentNumberNegativePattern); numberNegativePatternWithSignBuilder.Append("]"); break; } currentNumberNegativePattern = numberNegativePatternWithSignBuilder.ToString(); formatBuilder.Append(currentNumberPositivePattern); formatBuilder.Append(";"); formatBuilder.Append(currentNumberNegativePattern); return formatBuilder.ToString(); #endregion #region Type: Currency case KnownDataType.Currency: var currency = (CurrencyDataTypeModel)this; var currencyDecimals = currency.Decimals; var currencyPositivePatternArray = new[] { "$n", "n$", "$n", "n$" }; var currencyNegativePatternArray = new[] { "($n)", "-$n", "$-n", "$n-", "(n$)", "-n$", "n-$", "n$-", "-n $", "-$ n", "n $-", "$ n-", "$ -n", "n- $", "($ n)", "(n $)" }; if (currency.Locale != KnownCulture.Current) { culture = CultureInfo.GetCultureInfo(ExportsModel.GetXmlEnumAttributeFromItem(currency.Locale)); } var currentCurrencyPositivePattern = currencyPositivePatternArray[culture.NumberFormat.CurrencyPositivePattern]; var currentCurrencyNegativePattern = currencyNegativePatternArray[culture.NumberFormat.CurrencyNegativePattern]; var currencyPositivePatternBuilder = new StringBuilder(); currencyPositivePatternBuilder.Append("#,##0"); if (currencyDecimals > 0) { var digits = new string('0', currencyDecimals); currencyPositivePatternBuilder.Append("."); currencyPositivePatternBuilder.Append(digits); } var currencyPositivePattern = currencyPositivePatternBuilder.ToString(); currentCurrencyPositivePattern = currentCurrencyPositivePattern.Replace("$", culture.NumberFormat.CurrencySymbol) .Replace("n", currencyPositivePattern); var currencyNegativePatternWithSign = new StringBuilder(); currentCurrencyNegativePattern = currentCurrencyNegativePattern.Replace("$", culture.NumberFormat.CurrencySymbol) .Replace("n", currencyPositivePattern); switch (currency.Negative.Sign) { case KnownNegativeSign.None: currentCurrencyNegativePattern = currentCurrencyNegativePattern.Replace("-", string.Empty) .Replace("(", string.Empty) .Replace(")", string.Empty); currencyNegativePatternWithSign.Append(currentCurrencyNegativePattern); break; case KnownNegativeSign.Standard: if (currentCurrencyNegativePattern.Contains("-")) { currentCurrencyNegativePattern = currentCurrencyNegativePattern.Replace("-", culture.NumberFormat.NegativeSign); } currencyNegativePatternWithSign.Append(currentCurrencyNegativePattern); break; case KnownNegativeSign.Parenthesis: currentCurrencyNegativePattern = currentCurrencyNegativePattern.Replace("-", string.Empty) .Replace("(", string.Empty) .Replace(")", string.Empty); currencyNegativePatternWithSign.Append("("); currencyNegativePatternWithSign.Append(currentCurrencyNegativePattern); currencyNegativePatternWithSign.Append(")"); break; case KnownNegativeSign.Brackets: currentCurrencyNegativePattern = currentCurrencyNegativePattern.Replace("-", string.Empty) .Replace("(", string.Empty) .Replace(")", string.Empty); currencyNegativePatternWithSign.Append("["); currencyNegativePatternWithSign.Append(currentCurrencyNegativePattern); currencyNegativePatternWithSign.Append("]"); break; } currentCurrencyNegativePattern = currencyNegativePatternWithSign.ToString(); formatBuilder.Append(currentCurrencyPositivePattern); formatBuilder.Append(";"); formatBuilder.Append(currentCurrencyNegativePattern); return formatBuilder.ToString(); #endregion #region Type: Percentage case KnownDataType.Percentage: var percent = (PercentageDataTypeModel)this; formatBuilder.Append("P"); formatBuilder.Append(percent.Decimals); return formatBuilder.ToString(); #endregion #region Type: Scientific case KnownDataType.Scientific: var scientific = (ScientificDataTypeModel)this; formatBuilder.Append("E"); formatBuilder.Append(scientific.Decimals); return formatBuilder.ToString(); #endregion #region Type: DateTime case KnownDataType.Datetime: var datetime = (DatetimeDataTypeModel)this; if (datetime.Locale != KnownCulture.Current) { culture = CultureInfo.CreateSpecificCulture(ExportsModel.GetXmlEnumAttributeFromItem(datetime.Locale)); } switch (datetime.Format) { case KnownDatetimeFormat.GeneralDatePattern: formatBuilder.Append(culture.DateTimeFormat.ShortDatePattern); formatBuilder.Append(" "); formatBuilder.Append(culture.DateTimeFormat.ShortTimePattern); break; case KnownDatetimeFormat.ShortDatePattern: formatBuilder.Append(culture.DateTimeFormat.ShortDatePattern); break; case KnownDatetimeFormat.LongDatePattern: formatBuilder.Append(culture.DateTimeFormat.LongDatePattern); break; case KnownDatetimeFormat.FullDatePattern: formatBuilder.Append(culture.DateTimeFormat.FullDateTimePattern); break; case KnownDatetimeFormat.Rfc1123Pattern: formatBuilder.Append(culture.DateTimeFormat.RFC1123Pattern); break; case KnownDatetimeFormat.ShortTimePattern: formatBuilder.Append(culture.DateTimeFormat.ShortTimePattern); break; case KnownDatetimeFormat.LongTimePattern: formatBuilder.Append(culture.DateTimeFormat.LongTimePattern); break; case KnownDatetimeFormat.MonthDayPattern: formatBuilder.Append(culture.DateTimeFormat.MonthDayPattern); break; case KnownDatetimeFormat.YearMonthPattern: formatBuilder.Append(culture.DateTimeFormat.YearMonthPattern); break; } return formatBuilder.ToString(); #endregion #region Type: Special ////case KnownDataType.Special: //// var special = (SpecialDataTypeModel)this; //// var format = special.Format; //// return string.IsNullOrEmpty(format) //// ? "@" //// : format; #endregion #region Type: Text default: return "@"; #endregion } } #endregion #region [public] (FieldValueInformation) GetFormattedDataValue(string): Returns data value for a data type /// <summary> /// Returns data format for a data type. /// </summary> /// <param name="value">The value.</param> /// <returns> /// Data format. /// </returns> public FieldValueInformation GetFormattedDataValue(string value) { var result = new FieldValueInformation { Value = value, Comment = null, IsText = false, IsNumeric = true, IsDateTime = false, IsNegative = false, IsErrorValue = false, FormattedValue = value, Style = Parent.Parent, NegativeColor = Color.Empty }; var format = GetDataFormat(); var culture = CultureInfo.CreateSpecificCulture("es-ES"); switch (Type) { #region Type: Currency case KnownDataType.Currency: var currency = (CurrencyDataTypeModel)this; if (currency.Locale != KnownCulture.Current) { culture = CultureInfo.GetCultureInfo(ExportsModel.GetXmlEnumAttributeFromItem(currency.Locale)); } var isValidNumberValue = decimal.TryParse(value.Replace('.', ','), NumberStyles.Any, culture, out var currencyValue); if (isValidNumberValue) { result.Value = currencyValue; result.FormattedValue = currencyValue.ToString(format, culture); if (currencyValue < 0) { result.IsNegative = true; result.NegativeColor = currency.Negative.GetColor(); } } else { var error = currency.Error; result.IsErrorValue = true; result.Value = error.Value; result.Comment = error.Comment; result.FormattedValue = error.Value.ToString(format, culture); if (error.Value < 0) { result.IsNegative = true; result.NegativeColor = currency.Negative.GetColor(); } } break; #endregion #region Type: DateTime case KnownDataType.Datetime: var datetime = (DatetimeDataTypeModel)this; if (datetime.Locale != KnownCulture.Current) { culture = CultureInfo.CreateSpecificCulture(ExportsModel.GetXmlEnumAttributeFromItem(datetime.Locale)); } result.IsDateTime = true; result.IsNumeric = false; var isValidDateTimeValue = DateTime.TryParse(value, out var datetimeValue); if (isValidDateTimeValue) { result.Value = datetimeValue; result.FormattedValue = datetimeValue.ToString(format, culture); } else { var error = datetime.Error; result.IsErrorValue = true; result.Value = error.Value; result.Comment = error.Comment; result.FormattedValue = error.Value; } break; #endregion #region Type: Numeric case KnownDataType.Numeric: var numeric = (NumericDataTypeModel)this; var isValidNumericValue = float.TryParse(value.Replace('.', ','), NumberStyles.Any, culture, out var numericValue); if (isValidNumericValue) { result.Value = numericValue; result.FormattedValue = numericValue.ToString(format, culture); if (numericValue < 0) { result.IsNegative = true; result.NegativeColor = numeric.Negative.GetColor(); } } else { var error = numeric.Error; result.IsErrorValue = true; result.Value = error.Value; result.Comment = error.Comment; result.FormattedValue = error.Value.ToString(format, culture); if (error.Value < 0) { result.IsNegative = true; result.NegativeColor = numeric.Negative.GetColor(); } } break; #endregion #region Type: Percentage case KnownDataType.Percentage: var percentage = (PercentageDataTypeModel)this; var isValidPercentageValue = float.TryParse(value, NumberStyles.Any, culture, out var percentageValue); if (isValidPercentageValue) { result.IsNegative = percentageValue < 0; result.FormattedValue = percentageValue.ToString(format, culture); } else { var error = percentage.Error; result.IsErrorValue = true; result.Value = error.Value; result.Comment = error.Comment; result.FormattedValue = error.Value.ToString(format, culture); if (error.Value < 0) { result.IsNegative = true; ////result.NegativeColor = percentage.Negative.GetColor(); } } break; #endregion #region Type: Scientific case KnownDataType.Scientific: var scientific = (ScientificDataTypeModel)this; var isValidScientificValue = float.TryParse(value.Replace('.', ','), NumberStyles.Any, culture, out var scientificValue); if (isValidScientificValue) { result.IsNegative = scientificValue < 0; result.FormattedValue = scientificValue.ToString(format, culture); } else { var error = scientific.Error; result.IsErrorValue = true; result.Value = error.Value; result.Comment = error.Comment; result.FormattedValue = error.Value.ToString(format, culture); if (error.Value < 0) { result.IsNegative = true; ////result.NegativeColor = percentage.Negative.GetColor(); } } break; #endregion #region Type: Special ////case KnownDataType.Special: //// var special = (SpecialDataTypeModel)this; //// var isDateTimeValue = DateTime.TryParse(value, out datetimeValue); //// if (isDateTimeValue) //// { //// result.Value = datetimeValue; //// result.FormattedValue = datetimeValue.ToString(format); //// } //// else //// { //// var isNumericValue = float.TryParse(value.Replace('.', ','), NumberStyles.Any, culture, out numericValue); //// if (isNumericValue) //// { //// result.Value = numericValue; //// result.FormattedValue = numericValue.ToString(format); ////, culture); //// if (numericValue < 0) //// { //// result.IsNegative = true; //// //// result.NegativeColor = numeric.Negative.GetColor(); //// } //// } //// } //// #region old //////// var startWithYear = special.StartsWithYear == YesNo.Yes; //////// var resultBuilder = new StringBuilder(); //////// resultBuilder.Clear(); //////// resultBuilder.Append(string.Empty); //////// result.IsNumeric = false; //////// switch (specialFormat) //////// { //////// #region Format: ShortDateFormat '99/99/99' //////// case KnownSpecialFormat.ShortDateFormat: //////// if (!string.IsNullOrEmpty(value) && //////// !value.IsNullOrWhiteSpace() && //////// !value.Trim().Equals("0")) //////// { //////// var adjustedValue = string.Concat(new string('0', 6), value); //////// adjustedValue = adjustedValue.Substring(adjustedValue.Length - 6, 6); //////// if (startWithYear) //////// { //////// resultBuilder.Append(adjustedValue.Substring(0, 2)); //////// resultBuilder.Append('/'); //////// resultBuilder.Append(adjustedValue.Substring(2, 2)); //////// resultBuilder.Append('/'); //////// resultBuilder.Append(adjustedValue.Substring(4, 2)); //////// } //////// else //////// { //////// resultBuilder.Append(adjustedValue.Substring(4, 2)); //////// resultBuilder.Append('/'); //////// resultBuilder.Append(adjustedValue.Substring(0, 2)); //////// resultBuilder.Append('/'); //////// resultBuilder.Append(adjustedValue.Substring(2, 2)); //////// } //////// } //////// break; //////// #endregion //////// #region Format: LongDateFormat '99/99/9999' //////// case KnownSpecialFormat.LongDateFormat: //////// if (!string.IsNullOrEmpty(value) && //////// !value.IsNullOrWhiteSpace() && //////// !value.Trim().Equals("0")) //////// { //////// var adjustedValue = string.Concat(new string('0', 8), value); //////// adjustedValue = adjustedValue.Substring(adjustedValue.Length - 8, 8); //////// if (startWithYear) //////// { //////// resultBuilder.Append(adjustedValue.Substring(0, 4)); //////// resultBuilder.Append('/'); //////// resultBuilder.Append(adjustedValue.Substring(4, 2)); //////// resultBuilder.Append('/'); //////// resultBuilder.Append(adjustedValue.Substring(6, 2)); //////// } //////// else //////// { //////// resultBuilder.Append(adjustedValue.Substring(0, 2)); //////// resultBuilder.Append('/'); //////// resultBuilder.Append(adjustedValue.Substring(2, 2)); //////// resultBuilder.Append('/'); //////// resultBuilder.Append(adjustedValue.Substring(4, 4)); //////// } //////// } //////// break; //////// #endregion //////// } //////// result.FormattedValue = resultBuilder.ToString(); //// #endregion //// break; #endregion #region Type: Text case KnownDataType.Text: result.IsText = true; result.IsNumeric = false; break; #endregion } return result; } #endregion #endregion #region internal methods #region [internal] (void) SetParent(ContentModel): Sets the parent element of the element /// <summary> /// Sets the parent element of the element. /// </summary> /// <param name="reference">Reference to parent.</param> internal void SetParent(ContentModel reference) { _parent = reference; } #endregion #endregion #region private methods #region [private] (object) Clone(): Creates a new object that is a copy of the current instance /// <inheritdoc /> /// <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> object ICloneable.Clone() { return Clone(); } #endregion #endregion } }
// Copyright 2017 Esri. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. // You may obtain a copy of the License at: http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific // Language governing permissions and limitations under the License. using Esri.ArcGISRuntime.Data; using Esri.ArcGISRuntime.Geometry; using Esri.ArcGISRuntime.Mapping; using Esri.ArcGISRuntime.UI; using Esri.ArcGISRuntime.Tasks; using Esri.ArcGISRuntime.Tasks.Offline; using System; using System.IO; using Xamarin.Forms; using System.Threading.Tasks; #if WINDOWS_UWP using Colors = Windows.UI.Colors; #else using Colors = System.Drawing.Color; #endif namespace ArcGISRuntime.Samples.GeodatabaseTransactions { [ArcGISRuntime.Samples.Shared.Attributes.Sample( name: "Geodatabase transactions", category: "Data", description: "Use transactions to manage how changes are committed to a geodatabase.", instructions: "When the sample loads, a feature service is taken offline as a geodatabase. When the geodatabase is ready, you can add multiple types of features. To apply edits directly, uncheck the 'Require a transaction for edits' checkbox. When using transactions, use the buttons to start editing and stop editing. When you stop editing, you can choose to commit the changes or roll them back. At any point, you can synchronize the local geodatabase with the feature service.", tags: new[] { "commit", "database", "geodatabase", "transact", "transactions" })] public partial class GeodatabaseTransactions : ContentPage { // URL for the editable feature service private const string SyncServiceUrl = "https://sampleserver6.arcgisonline.com/arcgis/rest/services/Sync/SaveTheBaySync/FeatureServer/"; // Work in a small extent south of Galveston, TX private Envelope _extent = new Envelope(-95.3035, 29.0100, -95.1053, 29.1298, SpatialReferences.Wgs84); // Store the local geodatabase to edit private Geodatabase _localGeodatabase; // Store references to two tables to edit: Birds and Marine points private GeodatabaseFeatureTable _birdTable; private GeodatabaseFeatureTable _marineTable; public GeodatabaseTransactions() { InitializeComponent(); // When the spatial reference changes (the map loads) add the local geodatabase tables as feature layers MyMapView.SpatialReferenceChanged += async (s, e) => { // Call a function (and await it) to get the local geodatabase (or generate it from the feature service) await GetLocalGeodatabase(); // Once the local geodatabase is available, load the tables as layers to the map await LoadLocalGeodatabaseTables(); }; // Create a new map with the oceans basemap and add it to the map view Map map = new Map(BasemapStyle.ArcGISOceans); MyMapView.Map = map; } private async Task GetLocalGeodatabase() { // Get the path to the local geodatabase for this platform (temp directory, for example) string localGeodatabasePath = GetGdbPath(); try { // See if the geodatabase file is already present if (File.Exists(localGeodatabasePath)) { // If the geodatabase is already available, open it, hide the progress control, and update the message _localGeodatabase = await Geodatabase.OpenAsync(localGeodatabasePath); LoadingProgressBar.IsVisible = false; MessageTextBlock.Text = "Using local geodatabase from '" + _localGeodatabase.Path + "'"; } else { // Create a new GeodatabaseSyncTask with the uri of the feature server to pull from Uri uri = new Uri(SyncServiceUrl); GeodatabaseSyncTask gdbTask = await GeodatabaseSyncTask.CreateAsync(uri); // Create parameters for the task: layers and extent to include, out spatial reference, and sync model GenerateGeodatabaseParameters gdbParams = await gdbTask.CreateDefaultGenerateGeodatabaseParametersAsync(_extent); gdbParams.OutSpatialReference = MyMapView.SpatialReference; gdbParams.SyncModel = SyncModel.Layer; gdbParams.LayerOptions.Clear(); gdbParams.LayerOptions.Add(new GenerateLayerOption(0)); gdbParams.LayerOptions.Add(new GenerateLayerOption(1)); // Create a geodatabase job that generates the geodatabase GenerateGeodatabaseJob generateGdbJob = gdbTask.GenerateGeodatabase(gdbParams, localGeodatabasePath); // Handle the job changed event and check the status of the job; store the geodatabase when it's ready generateGdbJob.JobChanged += (s, e) => { // See if the job succeeded if (generateGdbJob.Status == JobStatus.Succeeded) { Device.BeginInvokeOnMainThread(() => { // Hide the progress control and update the message LoadingProgressBar.IsVisible = false; MessageTextBlock.Text = "Created local geodatabase"; }); } else if (generateGdbJob.Status == JobStatus.Failed) { Device.BeginInvokeOnMainThread(() => { // Hide the progress control and report the exception LoadingProgressBar.IsVisible = false; MessageTextBlock.Text = "Unable to create local geodatabase: " + generateGdbJob.Error.Message; }); } }; // Start the generate geodatabase job _localGeodatabase = await generateGdbJob.GetResultAsync(); } } catch (Exception ex) { // Show a message for the exception encountered Device.BeginInvokeOnMainThread(() => { Application.Current.MainPage.DisplayAlert("Generate Geodatabase", "Unable to create offline database: " + ex.Message, "OK"); }); } } // Function that loads the two point tables from the local geodatabase and displays them as feature layers private async Task LoadLocalGeodatabaseTables() { if (_localGeodatabase == null) { return; } // Read the geodatabase tables and add them as layers foreach (GeodatabaseFeatureTable table in _localGeodatabase.GeodatabaseFeatureTables) { try { // Load the table so the TableName can be read await table.LoadAsync(); // Store a reference to the Birds table if (table.TableName.ToLower().Contains("birds")) { _birdTable = table; } // Store a reference to the Marine table if (table.TableName.ToLower().Contains("marine")) { _marineTable = table; } // Create a new feature layer to show the table in the map FeatureLayer layer = new FeatureLayer(table); Device.BeginInvokeOnMainThread(() => MyMapView.Map.OperationalLayers.Add(layer)); } catch (Exception e) { await Application.Current.MainPage.DisplayAlert("Error", e.ToString(), "OK"); } } // Handle the transaction status changed event _localGeodatabase.TransactionStatusChanged += GdbTransactionStatusChanged; // Zoom the map view to the extent of the generated local datasets Device.BeginInvokeOnMainThread(() => { MyMapView.SetViewpoint(new Viewpoint(_marineTable.Extent)); StartEditingButton.IsEnabled = true; SyncEditsButton.IsEnabled = true; }); } private void GdbTransactionStatusChanged(object sender, TransactionStatusChangedEventArgs e) { // Update UI controls based on whether the geodatabase has a current transaction Device.BeginInvokeOnMainThread(() => { // These buttons should be enabled when there IS a transaction AddBirdButton.IsEnabled = e.IsInTransaction; AddMarineButton.IsEnabled = e.IsInTransaction; StopEditingButton.IsEnabled = e.IsInTransaction; // These buttons should be enabled when there is NOT a transaction StartEditingButton.IsEnabled = !e.IsInTransaction; SyncEditsButton.IsEnabled = !e.IsInTransaction; RequireTransactionCheckBox.IsEnabled = !e.IsInTransaction; }); } private string GetGdbPath() { // Set the platform-specific path for storing the geodatabase #if WINDOWS_UWP string folder = Windows.Storage.ApplicationData.Current.LocalFolder.Path; #elif __IOS__ || __ANDROID__ string folder = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); #endif // Set the final path return Path.Combine(folder, "savethebay.geodatabase"); } private void BeginTransaction(object sender, EventArgs e) { // See if there is a transaction active for the geodatabase if (!_localGeodatabase.IsInTransaction) { // If not, begin a transaction _localGeodatabase.BeginTransaction(); MessageTextBlock.Text = "Transaction started"; } } private async void AddNewFeature(object sender, EventArgs args) { // See if it was the "Birds" or "Marine" button that was clicked Button addFeatureButton = (Button)sender; try { // Cancel execution of the sketch task if it is already active if (MyMapView.SketchEditor.CancelCommand.CanExecute(null)) { MyMapView.SketchEditor.CancelCommand.Execute(null); } // Store the correct table to edit (for the button clicked) GeodatabaseFeatureTable editTable = null; if (addFeatureButton == AddBirdButton) { editTable = _birdTable; } else { editTable = _marineTable; } // Inform the user which table is being edited MessageTextBlock.Text = "Click the map to add a new feature to the geodatabase table '" + editTable.TableName + "'"; // Create a random value for the 'type' attribute (integer between 1 and 7) Random random = new Random(DateTime.Now.Millisecond); int featureType = random.Next(1, 7); // Use the sketch editor to allow the user to draw a point on the map MapPoint clickPoint = await MyMapView.SketchEditor.StartAsync(SketchCreationMode.Point, false) as MapPoint; // Create a new feature (row) in the selected table Feature newFeature = editTable.CreateFeature(); // Set the geometry with the point the user clicked and the 'type' with the random integer newFeature.Geometry = clickPoint; newFeature.SetAttributeValue("type", featureType); // Add the new feature to the table await editTable.AddFeatureAsync(newFeature); // Clear the message MessageTextBlock.Text = "New feature added to the '" + editTable.TableName + "' table"; } catch (TaskCanceledException) { // Ignore if the edit was canceled } catch (Exception ex) { // Report other exception messages MessageTextBlock.Text = ex.Message; } } private async void StopEditTransaction(object sender, EventArgs e) { // Ask the user if they want to commit or rollback the transaction (or cancel to keep working in the transaction) string choice = await ((Page)Parent).DisplayActionSheet("Transaction", "Cancel", null, "Commit", "Rollback"); if (choice == "Commit") { // See if there is a transaction active for the geodatabase if (_localGeodatabase.IsInTransaction) { // If there is, commit the transaction to store the edits (this will also end the transaction) _localGeodatabase.CommitTransaction(); MessageTextBlock.Text = "Edits were committed to the local geodatabase."; } } else if (choice == "Rollback") { // See if there is a transaction active for the geodatabase if (_localGeodatabase.IsInTransaction) { // If there is, rollback the transaction to discard the edits (this will also end the transaction) _localGeodatabase.RollbackTransaction(); MessageTextBlock.Text = "Edits were rolled back and not stored to the local geodatabase."; } } else { // For 'cancel' don't end the transaction with a commit or rollback } } // Change which controls are enabled if the user chooses to require/not require transactions for edits private void RequireTransactionChanged(object sender, EventArgs e) { // If the local geodatabase isn't created yet, return if (_localGeodatabase == null) { return; } // Get the value of the "require transactions" checkbox bool mustHaveTransaction = RequireTransactionCheckBox.IsToggled; // Warn the user if disabling transactions while a transaction is active if (!mustHaveTransaction && _localGeodatabase.IsInTransaction) { Application.Current.MainPage.DisplayAlert("Stop editing to end the current transaction.", "Current Transaction", "OK"); RequireTransactionCheckBox.IsToggled = true; return; } // Enable or disable controls according to the checkbox value StartEditingButton.IsEnabled = mustHaveTransaction; StopEditingButton.IsEnabled = mustHaveTransaction && _localGeodatabase.IsInTransaction; AddBirdButton.IsEnabled = !mustHaveTransaction; AddMarineButton.IsEnabled = !mustHaveTransaction; } // Synchronize edits in the local geodatabase with the service public async void SynchronizeEdits(object sender, EventArgs e) { // Show the progress bar while the sync is working LoadingProgressBar.IsVisible = true; try { // Create a sync task with the URL of the feature service to sync GeodatabaseSyncTask syncTask = await GeodatabaseSyncTask.CreateAsync(new Uri(SyncServiceUrl)); // Create sync parameters SyncGeodatabaseParameters taskParameters = await syncTask.CreateDefaultSyncGeodatabaseParametersAsync(_localGeodatabase); // Create a synchronize geodatabase job, pass in the parameters and the geodatabase SyncGeodatabaseJob job = syncTask.SyncGeodatabase(taskParameters, _localGeodatabase); // Handle the JobChanged event for the job job.JobChanged += (s, arg) => { // Report changes in the job status if (job.Status == JobStatus.Succeeded) { // Report success ... Device.BeginInvokeOnMainThread(() => MessageTextBlock.Text = "Synchronization is complete!"); } else if (job.Status == JobStatus.Failed) { // Report failure ... Device.BeginInvokeOnMainThread(() => MessageTextBlock.Text = job.Error.Message); } else { // Report that the job is in progress ... Device.BeginInvokeOnMainThread(() => MessageTextBlock.Text = "Sync in progress ..."); } }; // Await the completion of the job await job.GetResultAsync(); } catch (Exception ex) { // Show the message if an exception occurred MessageTextBlock.Text = "Error when synchronizing: " + ex.Message; } finally { // Hide the progress bar when the sync job is complete LoadingProgressBar.IsVisible = false; } } } }
/** * Copyright (c) 2014-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ // @Generated by gentest/gentest.rb from gentest/fixtures/YGAbsolutePositionTest.html using System; using NUnit.Framework; namespace Facebook.Yoga { [TestFixture] public class YGAbsolutePositionTest { [Test] public void Test_absolute_layout_width_height_start_top() { YogaConfig config = new YogaConfig(); YogaNode root = new YogaNode(config); root.Width = 100; root.Height = 100; YogaNode root_child0 = new YogaNode(config); root_child0.PositionType = YogaPositionType.Absolute; root_child0.Start = 10; root_child0.Top = 10; root_child0.Width = 10; root_child0.Height = 10; root.Insert(0, root_child0); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(10f, root_child0.LayoutX); Assert.AreEqual(10f, root_child0.LayoutY); Assert.AreEqual(10f, root_child0.LayoutWidth); Assert.AreEqual(10f, root_child0.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(80f, root_child0.LayoutX); Assert.AreEqual(10f, root_child0.LayoutY); Assert.AreEqual(10f, root_child0.LayoutWidth); Assert.AreEqual(10f, root_child0.LayoutHeight); } [Test] public void Test_absolute_layout_width_height_end_bottom() { YogaConfig config = new YogaConfig(); YogaNode root = new YogaNode(config); root.Width = 100; root.Height = 100; YogaNode root_child0 = new YogaNode(config); root_child0.PositionType = YogaPositionType.Absolute; root_child0.End = 10; root_child0.Bottom = 10; root_child0.Width = 10; root_child0.Height = 10; root.Insert(0, root_child0); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(80f, root_child0.LayoutX); Assert.AreEqual(80f, root_child0.LayoutY); Assert.AreEqual(10f, root_child0.LayoutWidth); Assert.AreEqual(10f, root_child0.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(10f, root_child0.LayoutX); Assert.AreEqual(80f, root_child0.LayoutY); Assert.AreEqual(10f, root_child0.LayoutWidth); Assert.AreEqual(10f, root_child0.LayoutHeight); } [Test] public void Test_absolute_layout_start_top_end_bottom() { YogaConfig config = new YogaConfig(); YogaNode root = new YogaNode(config); root.Width = 100; root.Height = 100; YogaNode root_child0 = new YogaNode(config); root_child0.PositionType = YogaPositionType.Absolute; root_child0.Start = 10; root_child0.Top = 10; root_child0.End = 10; root_child0.Bottom = 10; root.Insert(0, root_child0); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(10f, root_child0.LayoutX); Assert.AreEqual(10f, root_child0.LayoutY); Assert.AreEqual(80f, root_child0.LayoutWidth); Assert.AreEqual(80f, root_child0.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(10f, root_child0.LayoutX); Assert.AreEqual(10f, root_child0.LayoutY); Assert.AreEqual(80f, root_child0.LayoutWidth); Assert.AreEqual(80f, root_child0.LayoutHeight); } [Test] public void Test_absolute_layout_width_height_start_top_end_bottom() { YogaConfig config = new YogaConfig(); YogaNode root = new YogaNode(config); root.Width = 100; root.Height = 100; YogaNode root_child0 = new YogaNode(config); root_child0.PositionType = YogaPositionType.Absolute; root_child0.Start = 10; root_child0.Top = 10; root_child0.End = 10; root_child0.Bottom = 10; root_child0.Width = 10; root_child0.Height = 10; root.Insert(0, root_child0); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(10f, root_child0.LayoutX); Assert.AreEqual(10f, root_child0.LayoutY); Assert.AreEqual(10f, root_child0.LayoutWidth); Assert.AreEqual(10f, root_child0.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(80f, root_child0.LayoutX); Assert.AreEqual(10f, root_child0.LayoutY); Assert.AreEqual(10f, root_child0.LayoutWidth); Assert.AreEqual(10f, root_child0.LayoutHeight); } [Test] public void Test_do_not_clamp_height_of_absolute_node_to_height_of_its_overflow_hidden_parent() { YogaConfig config = new YogaConfig(); YogaNode root = new YogaNode(config); root.FlexDirection = YogaFlexDirection.Row; root.Overflow = YogaOverflow.Hidden; root.Width = 50; root.Height = 50; YogaNode root_child0 = new YogaNode(config); root_child0.PositionType = YogaPositionType.Absolute; root_child0.Start = 0; root_child0.Top = 0; root.Insert(0, root_child0); YogaNode root_child0_child0 = new YogaNode(config); root_child0_child0.Width = 100; root_child0_child0.Height = 100; root_child0.Insert(0, root_child0_child0); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(50f, root.LayoutWidth); Assert.AreEqual(50f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(100f, root_child0.LayoutWidth); Assert.AreEqual(100f, root_child0.LayoutHeight); Assert.AreEqual(0f, root_child0_child0.LayoutX); Assert.AreEqual(0f, root_child0_child0.LayoutY); Assert.AreEqual(100f, root_child0_child0.LayoutWidth); Assert.AreEqual(100f, root_child0_child0.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(50f, root.LayoutWidth); Assert.AreEqual(50f, root.LayoutHeight); Assert.AreEqual(-50f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(100f, root_child0.LayoutWidth); Assert.AreEqual(100f, root_child0.LayoutHeight); Assert.AreEqual(0f, root_child0_child0.LayoutX); Assert.AreEqual(0f, root_child0_child0.LayoutY); Assert.AreEqual(100f, root_child0_child0.LayoutWidth); Assert.AreEqual(100f, root_child0_child0.LayoutHeight); } [Test] public void Test_absolute_layout_within_border() { YogaConfig config = new YogaConfig(); YogaNode root = new YogaNode(config); root.MarginLeft = 10; root.MarginTop = 10; root.MarginRight = 10; root.MarginBottom = 10; root.PaddingLeft = 10; root.PaddingTop = 10; root.PaddingRight = 10; root.PaddingBottom = 10; root.BorderLeftWidth = 10; root.BorderTopWidth = 10; root.BorderRightWidth = 10; root.BorderBottomWidth = 10; root.Width = 100; root.Height = 100; YogaNode root_child0 = new YogaNode(config); root_child0.PositionType = YogaPositionType.Absolute; root_child0.Left = 0; root_child0.Top = 0; root_child0.Width = 50; root_child0.Height = 50; root.Insert(0, root_child0); YogaNode root_child1 = new YogaNode(config); root_child1.PositionType = YogaPositionType.Absolute; root_child1.Right = 0; root_child1.Bottom = 0; root_child1.Width = 50; root_child1.Height = 50; root.Insert(1, root_child1); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(10f, root.LayoutX); Assert.AreEqual(10f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(10f, root_child0.LayoutX); Assert.AreEqual(10f, root_child0.LayoutY); Assert.AreEqual(50f, root_child0.LayoutWidth); Assert.AreEqual(50f, root_child0.LayoutHeight); Assert.AreEqual(40f, root_child1.LayoutX); Assert.AreEqual(40f, root_child1.LayoutY); Assert.AreEqual(50f, root_child1.LayoutWidth); Assert.AreEqual(50f, root_child1.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(10f, root.LayoutX); Assert.AreEqual(10f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(10f, root_child0.LayoutX); Assert.AreEqual(10f, root_child0.LayoutY); Assert.AreEqual(50f, root_child0.LayoutWidth); Assert.AreEqual(50f, root_child0.LayoutHeight); Assert.AreEqual(40f, root_child1.LayoutX); Assert.AreEqual(40f, root_child1.LayoutY); Assert.AreEqual(50f, root_child1.LayoutWidth); Assert.AreEqual(50f, root_child1.LayoutHeight); } [Test] public void Test_absolute_layout_align_items_and_justify_content_center() { YogaConfig config = new YogaConfig(); YogaNode root = new YogaNode(config); root.JustifyContent = YogaJustify.Center; root.AlignItems = YogaAlign.Center; root.FlexGrow = 1; root.Width = 110; root.Height = 100; YogaNode root_child0 = new YogaNode(config); root_child0.PositionType = YogaPositionType.Absolute; root_child0.Width = 60; root_child0.Height = 40; root.Insert(0, root_child0); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(110f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(25f, root_child0.LayoutX); Assert.AreEqual(30f, root_child0.LayoutY); Assert.AreEqual(60f, root_child0.LayoutWidth); Assert.AreEqual(40f, root_child0.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(110f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(25f, root_child0.LayoutX); Assert.AreEqual(30f, root_child0.LayoutY); Assert.AreEqual(60f, root_child0.LayoutWidth); Assert.AreEqual(40f, root_child0.LayoutHeight); } [Test] public void Test_absolute_layout_align_items_and_justify_content_flex_end() { YogaConfig config = new YogaConfig(); YogaNode root = new YogaNode(config); root.JustifyContent = YogaJustify.FlexEnd; root.AlignItems = YogaAlign.FlexEnd; root.FlexGrow = 1; root.Width = 110; root.Height = 100; YogaNode root_child0 = new YogaNode(config); root_child0.PositionType = YogaPositionType.Absolute; root_child0.Width = 60; root_child0.Height = 40; root.Insert(0, root_child0); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(110f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(50f, root_child0.LayoutX); Assert.AreEqual(60f, root_child0.LayoutY); Assert.AreEqual(60f, root_child0.LayoutWidth); Assert.AreEqual(40f, root_child0.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(110f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(60f, root_child0.LayoutY); Assert.AreEqual(60f, root_child0.LayoutWidth); Assert.AreEqual(40f, root_child0.LayoutHeight); } [Test] public void Test_absolute_layout_justify_content_center() { YogaConfig config = new YogaConfig(); YogaNode root = new YogaNode(config); root.JustifyContent = YogaJustify.Center; root.FlexGrow = 1; root.Width = 110; root.Height = 100; YogaNode root_child0 = new YogaNode(config); root_child0.PositionType = YogaPositionType.Absolute; root_child0.Width = 60; root_child0.Height = 40; root.Insert(0, root_child0); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(110f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(30f, root_child0.LayoutY); Assert.AreEqual(60f, root_child0.LayoutWidth); Assert.AreEqual(40f, root_child0.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(110f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(50f, root_child0.LayoutX); Assert.AreEqual(30f, root_child0.LayoutY); Assert.AreEqual(60f, root_child0.LayoutWidth); Assert.AreEqual(40f, root_child0.LayoutHeight); } [Test] public void Test_absolute_layout_align_items_center() { YogaConfig config = new YogaConfig(); YogaNode root = new YogaNode(config); root.AlignItems = YogaAlign.Center; root.FlexGrow = 1; root.Width = 110; root.Height = 100; YogaNode root_child0 = new YogaNode(config); root_child0.PositionType = YogaPositionType.Absolute; root_child0.Width = 60; root_child0.Height = 40; root.Insert(0, root_child0); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(110f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(25f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(60f, root_child0.LayoutWidth); Assert.AreEqual(40f, root_child0.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(110f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(25f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(60f, root_child0.LayoutWidth); Assert.AreEqual(40f, root_child0.LayoutHeight); } [Test] public void Test_absolute_layout_align_items_center_on_child_only() { YogaConfig config = new YogaConfig(); YogaNode root = new YogaNode(config); root.FlexGrow = 1; root.Width = 110; root.Height = 100; YogaNode root_child0 = new YogaNode(config); root_child0.AlignSelf = YogaAlign.Center; root_child0.PositionType = YogaPositionType.Absolute; root_child0.Width = 60; root_child0.Height = 40; root.Insert(0, root_child0); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(110f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(25f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(60f, root_child0.LayoutWidth); Assert.AreEqual(40f, root_child0.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(110f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(25f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(60f, root_child0.LayoutWidth); Assert.AreEqual(40f, root_child0.LayoutHeight); } [Test] public void Test_absolute_layout_align_items_and_justify_content_center_and_top_position() { YogaConfig config = new YogaConfig(); YogaNode root = new YogaNode(config); root.JustifyContent = YogaJustify.Center; root.AlignItems = YogaAlign.Center; root.FlexGrow = 1; root.Width = 110; root.Height = 100; YogaNode root_child0 = new YogaNode(config); root_child0.PositionType = YogaPositionType.Absolute; root_child0.Top = 10; root_child0.Width = 60; root_child0.Height = 40; root.Insert(0, root_child0); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(110f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(25f, root_child0.LayoutX); Assert.AreEqual(10f, root_child0.LayoutY); Assert.AreEqual(60f, root_child0.LayoutWidth); Assert.AreEqual(40f, root_child0.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(110f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(25f, root_child0.LayoutX); Assert.AreEqual(10f, root_child0.LayoutY); Assert.AreEqual(60f, root_child0.LayoutWidth); Assert.AreEqual(40f, root_child0.LayoutHeight); } [Test] public void Test_absolute_layout_align_items_and_justify_content_center_and_bottom_position() { YogaConfig config = new YogaConfig(); YogaNode root = new YogaNode(config); root.JustifyContent = YogaJustify.Center; root.AlignItems = YogaAlign.Center; root.FlexGrow = 1; root.Width = 110; root.Height = 100; YogaNode root_child0 = new YogaNode(config); root_child0.PositionType = YogaPositionType.Absolute; root_child0.Bottom = 10; root_child0.Width = 60; root_child0.Height = 40; root.Insert(0, root_child0); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(110f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(25f, root_child0.LayoutX); Assert.AreEqual(50f, root_child0.LayoutY); Assert.AreEqual(60f, root_child0.LayoutWidth); Assert.AreEqual(40f, root_child0.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(110f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(25f, root_child0.LayoutX); Assert.AreEqual(50f, root_child0.LayoutY); Assert.AreEqual(60f, root_child0.LayoutWidth); Assert.AreEqual(40f, root_child0.LayoutHeight); } [Test] public void Test_absolute_layout_align_items_and_justify_content_center_and_left_position() { YogaConfig config = new YogaConfig(); YogaNode root = new YogaNode(config); root.JustifyContent = YogaJustify.Center; root.AlignItems = YogaAlign.Center; root.FlexGrow = 1; root.Width = 110; root.Height = 100; YogaNode root_child0 = new YogaNode(config); root_child0.PositionType = YogaPositionType.Absolute; root_child0.Left = 5; root_child0.Width = 60; root_child0.Height = 40; root.Insert(0, root_child0); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(110f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(5f, root_child0.LayoutX); Assert.AreEqual(30f, root_child0.LayoutY); Assert.AreEqual(60f, root_child0.LayoutWidth); Assert.AreEqual(40f, root_child0.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(110f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(5f, root_child0.LayoutX); Assert.AreEqual(30f, root_child0.LayoutY); Assert.AreEqual(60f, root_child0.LayoutWidth); Assert.AreEqual(40f, root_child0.LayoutHeight); } [Test] public void Test_absolute_layout_align_items_and_justify_content_center_and_right_position() { YogaConfig config = new YogaConfig(); YogaNode root = new YogaNode(config); root.JustifyContent = YogaJustify.Center; root.AlignItems = YogaAlign.Center; root.FlexGrow = 1; root.Width = 110; root.Height = 100; YogaNode root_child0 = new YogaNode(config); root_child0.PositionType = YogaPositionType.Absolute; root_child0.Right = 5; root_child0.Width = 60; root_child0.Height = 40; root.Insert(0, root_child0); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(110f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(45f, root_child0.LayoutX); Assert.AreEqual(30f, root_child0.LayoutY); Assert.AreEqual(60f, root_child0.LayoutWidth); Assert.AreEqual(40f, root_child0.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(110f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(45f, root_child0.LayoutX); Assert.AreEqual(30f, root_child0.LayoutY); Assert.AreEqual(60f, root_child0.LayoutWidth); Assert.AreEqual(40f, root_child0.LayoutHeight); } [Test] public void Test_position_root_with_rtl_should_position_withoutdirection() { YogaConfig config = new YogaConfig(); YogaNode root = new YogaNode(config); root.Left = 72; root.Width = 52; root.Height = 52; root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(72f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(52f, root.LayoutWidth); Assert.AreEqual(52f, root.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(72f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(52f, root.LayoutWidth); Assert.AreEqual(52f, root.LayoutHeight); } } }
// // Copyright 2014-2015 Amazon.com, // Inc. or its affiliates. All Rights Reserved. // // Licensed under the Amazon Software License (the "License"). // You may not use this file except in compliance with the // License. A copy of the License is located at // // http://aws.amazon.com/asl/ // // or in the "license" file accompanying this file. This file is // distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, express or implied. See the License // for the specific language governing permissions and // limitations under the License. // using System; using System.Collections.Generic; using System.IO; using System.Linq; using Amazon.DynamoDBv2.Model; using Amazon.Runtime; using Amazon.Runtime.Internal.Util; namespace Amazon.DynamoDBv2.DocumentModel { /// <summary> /// A DynamoDBEntry that represents a DynamoDB list (L) type. /// </summary> public class DynamoDBList : DynamoDBEntry { private static DynamoDBEntryConversion conversion = CreateConversion(); private static DynamoDBEntryConversion CreateConversion() { var conversion = DynamoDBEntryConversion.V2.Clone(); var supportedMemberTypes = new Type[] { typeof(String), typeof(MemoryStream), typeof(byte[]) }; conversion.AddConverter(new DynamoDBListConverter(supportedMemberTypes)); return conversion; } #region Constructors/static initializers /// <summary> /// Constructs an empty DynamoDBList. /// </summary> public DynamoDBList() { Entries = new List<DynamoDBEntry>(); } public DynamoDBList(IEnumerable<DynamoDBEntry> entries) : this() { Entries.AddRange(entries); } public static DynamoDBList Create<T>(IEnumerable<T> items) { var list = new DynamoDBList(); foreach (var item in items) { var entry = new UnconvertedDynamoDBEntry(item); list.Entries.Add(entry); } return list; } #endregion #region Properties/Accessors /// <summary> /// Collection of DynamoDB entries /// </summary> public List<DynamoDBEntry> Entries { get; private set; } /// <summary> /// Gets or sets DynamoDB at a specific location in the list. /// </summary> /// <param name="i">Index of the DynamoDB in question.</param> /// <returns>DynamoDB in question.</returns> public DynamoDBEntry this[int i] { get { return Entries[i]; } set { if (i < Entries.Count && i >= 0) { Entries[i] = value; } else { throw new ArgumentOutOfRangeException("i"); } } } /// <summary> /// Adds a DynamoDB to the end of the list. /// </summary> /// <param name="value">DynamoDB to add.</param> public void Add(DynamoDBEntry value) { this.Entries.Add(value); } /// <summary> /// Returns a new instance of Document where all unconverted .NET types /// are converted to DynamoDBEntry types using a specific conversion. /// </summary> /// <param name="conversion"></param> /// <returns></returns> public DynamoDBList ForceConversion(DynamoDBEntryConversion conversion) { DynamoDBList newList = new DynamoDBList(); for (int i = 0; i < Entries.Count; i++) { var entry = Entries[i]; var unconvertedEntry = entry as UnconvertedDynamoDBEntry; if (unconvertedEntry != null) entry = unconvertedEntry.Convert(conversion); var doc = entry as Document; if (doc != null) entry = doc.ForceConversion(conversion); var list = entry as DynamoDBList; if (list != null) entry = list.ForceConversion(conversion); newList.Add(entry); } return newList; } #endregion #region Overrides internal override AttributeValue ConvertToAttributeValue(AttributeConversionConfig conversionConfig) { if (Entries == null) return null; AttributeValue attribute = new AttributeValue(); var items = new List<AttributeValue>(); foreach (var entry in Entries) { AttributeValue entryAttributeValue; using (conversionConfig.CRT.Track(entry)) { entryAttributeValue = entry.ConvertToAttributeValue(conversionConfig); } items.Add(entryAttributeValue); } attribute.L = items; attribute.IsLSet = true; return attribute; } public override object Clone() { DynamoDBList list = new DynamoDBList(); foreach (DynamoDBEntry entry in this.Entries) { list.Add(entry.Clone() as DynamoDBEntry); } return list; } public override bool Equals(object obj) { var otherList = obj as DynamoDBList; if (otherList == null) return false; var entries = Entries; var otherEntries = otherList.Entries; if (entries.Count != otherEntries.Count) return false; for(int i=0;i<entries.Count;i++) { var a = entries[i]; var b = otherEntries[i]; if (a == null || b == null) if (a != b) return false; if (!a.Equals(b)) return false; } return true; } public override int GetHashCode() { var entriesHashCode = 0; foreach (var entry in this.Entries) { entriesHashCode = Hashing.CombineHashes(entriesHashCode, entry.GetHashCode()); } return entriesHashCode; } #endregion #region Explicit and Implicit conversions #region DynamoDBEntry-DynamoDBList conversions /// <summary> /// Explicitly convert DynamoDBList to DynamoDBEntry[] /// </summary> /// <returns>DynamoDBEntry[] value of this object</returns> public override DynamoDBEntry[] AsArrayOfDynamoDBEntry() { return AsListOfDynamoDBEntry().ToArray(); } /// <summary> /// Implicitly convert DynamoDBEntry[] to DynamoDBList /// </summary> /// <param name="data">DynamoDBEntry[] data to convert</param> /// <returns>DynamoDBList representing the data</returns> public static implicit operator DynamoDBList(DynamoDBEntry[] data) { return new DynamoDBList(data); } /// <summary> /// Explicitly convert DynamoDBList to DynamoDBEntry[] /// </summary> /// <param name="p">DynamoDBList to convert</param> /// <returns>DynamoDBEntry[] value of DynamoDBList</returns> public static explicit operator DynamoDBEntry[](DynamoDBList p) { return p.AsArrayOfDynamoDBEntry(); } /// <summary> /// Explicitly convert DynamoDBList to List&lt;DynamoDBEntry&gt; /// </summary> /// <returns>List&lt;DynamoDBEntry&gt; value of this object</returns> public override List<DynamoDBEntry> AsListOfDynamoDBEntry() { return Entries; } /// <summary> /// Implicitly convert List&lt;DynamoDBEntry&gt; to DynamoDBList /// </summary> /// <param name="data">List&lt;DynamoDBEntry&gt; data to convert</param> /// <returns>DynamoDBList representing the data</returns> public static implicit operator DynamoDBList(List<DynamoDBEntry> data) { return new DynamoDBList(data); } /// <summary> /// Explicitly convert DynamoDBList to List&lt;DynamoDBEntry&gt; /// </summary> /// <param name="p">DynamoDBList to convert</param> /// <returns>List&lt;DynamoDBEntry&gt; value of DynamoDBList</returns> public static explicit operator List<DynamoDBEntry>(DynamoDBList p) { return p.AsListOfDynamoDBEntry(); } #endregion /// <summary> /// Explicitly convert DynamoDBList to List&lt;Document&gt; /// </summary> /// <returns>List&lt;Document&gt; value of this object</returns> public override List<Document> AsListOfDocument() { return Entries.Select(e => e.ToDocument()).ToList(); } /// <summary> /// Implicitly convert List&lt;Document&gt; to DynamoDBEntry /// </summary> /// <param name="data">List&lt;Document&gt; data to convert</param> /// <returns>DynamoDBEntry representing the data</returns> public static implicit operator DynamoDBList(List<Document> data) { return new DynamoDBList(data.Cast<DynamoDBEntry>()); } /// <summary> /// Explicitly convert DynamoDBEntry to List&lt;Document&gt; /// </summary> /// <param name="p">DynamoDBEntry to convert</param> /// <returns>List&lt;Document&gt; value of DynamoDBEntry</returns> public static explicit operator List<Document>(DynamoDBList p) { return p.AsListOfDocument(); } /// <summary> /// Explicitly convert DynamoDBEntry to String[] /// </summary> /// <returns>String[] value of this object</returns> public override String[] AsArrayOfString() { return AsListOfString().ToArray(); } /// <summary> /// Implicitly convert String[] to DynamoDBEntry /// </summary> /// <param name="data">String[] data to convert</param> /// <returns>DynamoDBEntry representing the data</returns> public static implicit operator DynamoDBList(String[] data) { return conversion.ConvertToEntry<String[]>(data).ToDynamoDBList(); } /// <summary> /// Explicitly convert DynamoDBEntry to String[] /// </summary> /// <param name="p">DynamoDBEntry to convert</param> /// <returns>String[] value of DynamoDBEntry</returns> public static explicit operator String[](DynamoDBList p) { return p.AsArrayOfString(); } /// <summary> /// Explicitly convert DynamoDBList to List&lt;String&gt; /// </summary> /// <returns>List&lt;String&gt; value of this object</returns> public override List<String> AsListOfString() { return conversion.ConvertFromEntry<List<String>>(this); } /// <summary> /// Implicitly convert List&lt;String&gt; to DynamoDBList /// </summary> /// <param name="data">List&lt;String&gt; data to convert</param> /// <returns>DynamoDBList representing the data</returns> public static implicit operator DynamoDBList(List<String> data) { return conversion.ConvertToEntry<List<String>>(data).ToDynamoDBList(); } /// <summary> /// Explicitly convert DynamoDBList to List&lt;String&gt; /// </summary> /// <param name="p">DynamoDBList to convert</param> /// <returns>List&lt;String&gt; value of DynamoDBList</returns> public static explicit operator List<String>(DynamoDBList p) { return p.AsListOfString(); } /// <summary> /// Explicitly convert DynamoDBEntry to HashSet&lt;String&gt; /// </summary> /// <returns>List&lt;String&gt; value of this object</returns> public override HashSet<String> AsHashSetOfString() { return conversion.ConvertFromEntry<HashSet<String>>(this); } /// <summary> /// Implicitly convert HashSet&lt;String&gt; to DynamoDBList /// </summary> /// <param name="data">HashSet&lt;String&gt; data to convert</param> /// <returns>DynamoDBList representing the data</returns> public static implicit operator DynamoDBList(HashSet<String> data) { return conversion.ConvertToEntry<HashSet<String>>(data).ToDynamoDBList(); } /// <summary> /// Explicitly convert DynamoDBList to HashSet&lt;String&gt; /// </summary> /// <param name="p">DynamoDBList to convert</param> /// <returns>HashSet&lt;String&gt; value of DynamoDBList</returns> public static explicit operator HashSet<String>(DynamoDBList p) { return p.AsHashSetOfString(); } /// <summary> /// Explicitly convert DynamoDBList to byte[] /// </summary> /// <returns>List&lt;byte[]&gt; value of this object</returns> public override List<byte[]> AsListOfByteArray() { return conversion.ConvertFromEntry<List<byte[]>>(this); } /// <summary> /// Implicitly convert List&lt;byte[]&gt; to DynamoDBList /// </summary> /// <param name="data">List&lt;byte[]&gt; data to convert</param> /// <returns>DynamoDBList representing the data</returns> public static implicit operator DynamoDBList(List<byte[]> data) { return conversion.ConvertToEntry<List<byte[]>>(data).ToDynamoDBList(); } /// <summary> /// Explicitly convert DynamoDBList to List&lt;byte[]&gt; /// </summary> /// <param name="p">DynamoDBList to convert</param> /// <returns>List&lt;byte[]&gt; value of DynamoDBList</returns> public static explicit operator List<byte[]>(DynamoDBList p) { return p.AsListOfByteArray(); } /// <summary> /// Explicitly convert DynamoDBList to HashSet&lt;byte[]&gt; /// </summary> /// <returns>HashSet&lt;byte[]&gt; value of this object</returns> public override HashSet<byte[]> AsHashSetOfByteArray() { return conversion.ConvertFromEntry<HashSet<byte[]>>(this); } /// <summary> /// Implicitly convert HashSet&lt;byte[]&gt; to DynamoDBList /// </summary> /// <param name="data">HashSet&lt;byte[]&gt; data to convert</param> /// <returns>DynamoDBList representing the data</returns> public static implicit operator DynamoDBList(HashSet<byte[]> data) { return conversion.ConvertToEntry<HashSet<byte[]>>(data).ToDynamoDBList(); } /// <summary> /// Explicitly convert DynamoDBList to HashSet&lt;byte[]&gt; /// </summary> /// <param name="p">DynamoDBList to convert</param> /// <returns>HashSet&lt;byte[]&gt; value of DynamoDBList</returns> public static explicit operator HashSet<byte[]>(DynamoDBList p) { return conversion.ConvertFromEntry<HashSet<byte[]>>(p); } /// <summary> /// Explicitly convert DynamoDBList to List&lt;MemoryStream&gt; /// </summary> /// <returns>List&lt;MemoryStream&gt; value of this object</returns> public override List<MemoryStream> AsListOfMemoryStream() { return conversion.ConvertFromEntry<List<MemoryStream>>(this); } /// <summary> /// Implicitly convert List&lt;MemoryStream&gt; to DynamoDBList /// </summary> /// <param name="data">List&lt;MemoryStream&gt; data to convert</param> /// <returns>DynamoDBList representing the data</returns> public static implicit operator DynamoDBList(List<MemoryStream> data) { return conversion.ConvertToEntry<List<MemoryStream>>(data).ToDynamoDBList(); } /// <summary> /// Explicitly convert DynamoDBList to List&lt;MemoryStream&gt; /// </summary> /// <param name="p">DynamoDBList to convert</param> /// <returns>List&lt;MemoryStream&gt; value of DynamoDBList</returns> public static explicit operator List<MemoryStream>(DynamoDBList p) { return p.AsListOfMemoryStream(); } #endregion } }
using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Linq.Expressions; using System.Runtime.Versioning; namespace NuGet { public static class PackageRepositoryExtensions { public static bool Exists(this IPackageRepository repository, IPackageMetadata package) { return repository.Exists(package.Id, package.Version); } public static bool Exists(this IPackageRepository repository, string packageId) { return Exists(repository, packageId, version: null); } public static bool Exists(this IPackageRepository repository, string packageId, SemanticVersion version) { IPackageLookup packageLookup = repository as IPackageLookup; if ((packageLookup != null) && !String.IsNullOrEmpty(packageId) && (version != null)) { return packageLookup.Exists(packageId, version); } return repository.FindPackage(packageId, version) != null; } public static bool TryFindPackage(this IPackageRepository repository, string packageId, SemanticVersion version, out IPackage package) { package = repository.FindPackage(packageId, version); return package != null; } public static IPackage FindPackage(this IPackageRepository repository, string packageId) { return repository.FindPackage(packageId, version: null); } public static IPackage FindPackage(this IPackageRepository repository, string packageId, SemanticVersion version) { // Default allow pre release versions to true here because the caller typically wants to find all packages in this scenario for e.g when checking if a // a package is already installed in the local repository. The same applies to allowUnlisted. return FindPackage(repository, packageId, version, NullConstraintProvider.Instance, allowPrereleaseVersions: true, allowUnlisted: true); } public static IPackage FindPackage(this IPackageRepository repository, string packageId, SemanticVersion version, bool allowPrereleaseVersions, bool allowUnlisted) { return FindPackage(repository, packageId, version, NullConstraintProvider.Instance, allowPrereleaseVersions, allowUnlisted); } public static IPackage FindPackage( this IPackageRepository repository, string packageId, SemanticVersion version, IPackageConstraintProvider constraintProvider, bool allowPrereleaseVersions, bool allowUnlisted) { if (repository == null) { throw new ArgumentNullException("repository"); } if (packageId == null) { throw new ArgumentNullException("packageId"); } // if an explicit version is specified, disregard the 'allowUnlisted' argument // and always allow unlisted packages. if (version != null) { allowUnlisted = true; } // If the repository implements it's own lookup then use that instead. // This is an optimization that we use so we don't have to enumerate packages for // sources that don't need to. var packageLookup = repository as IPackageLookup; if (packageLookup != null && version != null) { return packageLookup.FindPackage(packageId, version); } IEnumerable<IPackage> packages = repository.FindPackagesById(packageId); packages = packages.ToList() .OrderByDescending(p => p.Version); if (!allowUnlisted) { packages = packages.Where(PackageExtensions.IsListed); } if (version != null) { packages = packages.Where(p => p.Version == version); } else if (constraintProvider != null) { packages = FilterPackagesByConstraints(constraintProvider, packages, packageId, allowPrereleaseVersions); } return packages.FirstOrDefault(); } public static IPackage FindPackage(this IPackageRepository repository, string packageId, IVersionSpec versionSpec, IPackageConstraintProvider constraintProvider, bool allowPrereleaseVersions, bool allowUnlisted) { var packages = repository.FindPackages(packageId, versionSpec, allowPrereleaseVersions, allowUnlisted); if (constraintProvider != null) { packages = FilterPackagesByConstraints(constraintProvider, packages, packageId, allowPrereleaseVersions); } return packages.FirstOrDefault(); } public static IEnumerable<IPackage> FindPackages(this IPackageRepository repository, IEnumerable<string> packageIds) { if (packageIds == null) { throw new ArgumentNullException("packageIds"); } return FindPackages(repository, packageIds, GetFilterExpression); } public static IEnumerable<IPackage> FindPackagesById(this IPackageRepository repository, string packageId) { var serviceBasedRepository = repository as IServiceBasedRepository; if (serviceBasedRepository != null) { return serviceBasedRepository.FindPackagesById(packageId).ToList(); } else { return FindPackagesByIdCore(repository, packageId); } } internal static IEnumerable<IPackage> FindPackagesByIdCore(IPackageRepository repository, string packageId) { var cultureRepository = repository as ICultureAwareRepository; if (cultureRepository != null) { packageId = packageId.ToLower(cultureRepository.Culture); } else { packageId = packageId.ToLower(CultureInfo.CurrentCulture); } return (from p in repository.GetPackages() where p.Id.ToLower() == packageId orderby p.Id select p).ToList(); } /// <summary> /// Since Odata dies when our query for updates is too big. We query for updates 10 packages at a time /// and return the full list of packages. /// </summary> private static IEnumerable<IPackage> FindPackages<T>(this IPackageRepository repository, IEnumerable<T> items, Func<IEnumerable<T>, Expression<Func<IPackage, bool>>> filterSelector) { const int batchSize = 10; while (items.Any()) { IEnumerable<T> currentItems = items.Take(batchSize); Expression<Func<IPackage, bool>> filterExpression = filterSelector(currentItems); var query = repository.GetPackages().Where(filterExpression).OrderBy(p => p.Id); foreach (var package in query) { yield return package; } items = items.Skip(batchSize); } } public static IEnumerable<IPackage> FindPackages( this IPackageRepository repository, string packageId, IVersionSpec versionSpec, bool allowPrereleaseVersions, bool allowUnlisted) { if (repository == null) { throw new ArgumentNullException("repository"); } if (packageId == null) { throw new ArgumentNullException("packageId"); } IEnumerable<IPackage> packages = repository.FindPackagesById(packageId) .OrderByDescending(p => p.Version); if (!allowUnlisted) { packages = packages.Where(PackageExtensions.IsListed); } if (versionSpec != null) { packages = packages.FindByVersion(versionSpec); } packages = FilterPackagesByConstraints(NullConstraintProvider.Instance, packages, packageId, allowPrereleaseVersions); return packages; } public static IPackage FindPackage( this IPackageRepository repository, string packageId, IVersionSpec versionSpec, bool allowPrereleaseVersions, bool allowUnlisted) { return repository.FindPackages(packageId, versionSpec, allowPrereleaseVersions, allowUnlisted).FirstOrDefault(); } public static IEnumerable<IPackage> FindCompatiblePackages(this IPackageRepository repository, IPackageConstraintProvider constraintProvider, IEnumerable<string> packageIds, IPackage package, bool allowPrereleaseVersions) { return (from p in repository.FindPackages(packageIds) where allowPrereleaseVersions || p.IsReleaseVersion() let dependency = p.FindDependency(package.Id) let otherConstaint = constraintProvider.GetConstraint(p.Id) where dependency != null && dependency.VersionSpec.Satisfies(package.Version) && (otherConstaint == null || otherConstaint.Satisfies(package.Version)) select p); } public static PackageDependency FindDependency(this IPackageMetadata package, string packageId) { return (from dependency in package.Dependencies where dependency.Id.Equals(packageId, StringComparison.OrdinalIgnoreCase) select dependency).FirstOrDefault(); } public static IQueryable<IPackage> Search(this IPackageRepository repository, string searchTerm, bool allowPrereleaseVersions) { return Search(repository, searchTerm, targetFrameworks: Enumerable.Empty<string>(), allowPrereleaseVersions: allowPrereleaseVersions); } public static IQueryable<IPackage> Search(this IPackageRepository repository, string searchTerm, IEnumerable<string> targetFrameworks, bool allowPrereleaseVersions) { if (targetFrameworks == null) { throw new ArgumentNullException("targetFrameworks"); } var serviceBasedRepository = repository as IServiceBasedRepository; if (serviceBasedRepository != null) { return serviceBasedRepository.Search(searchTerm, targetFrameworks, allowPrereleaseVersions); } // Ignore the target framework if the repository doesn't support searching return repository.GetPackages().Find(searchTerm) .FilterByPrerelease(allowPrereleaseVersions) .AsQueryable(); } public static IPackage ResolveDependency(this IPackageRepository repository, PackageDependency dependency, bool allowPrereleaseVersions, bool preferListedPackages) { return ResolveDependency(repository, dependency, constraintProvider: null, allowPrereleaseVersions: allowPrereleaseVersions, preferListedPackages: preferListedPackages); } public static IPackage ResolveDependency(this IPackageRepository repository, PackageDependency dependency, IPackageConstraintProvider constraintProvider, bool allowPrereleaseVersions, bool preferListedPackages) { IDependencyResolver dependencyResolver = repository as IDependencyResolver; if (dependencyResolver != null) { return dependencyResolver.ResolveDependency(dependency, constraintProvider, allowPrereleaseVersions, preferListedPackages); } return ResolveDependencyCore(repository, dependency, constraintProvider, allowPrereleaseVersions, preferListedPackages); } internal static IPackage ResolveDependencyCore( this IPackageRepository repository, PackageDependency dependency, IPackageConstraintProvider constraintProvider, bool allowPrereleaseVersions, bool preferListedPackages) { if (repository == null) { throw new ArgumentNullException("repository"); } if (dependency == null) { throw new ArgumentNullException("dependency"); } IEnumerable<IPackage> packages = repository.FindPackagesById(dependency.Id).ToList(); // Always filter by constraints when looking for dependencies packages = FilterPackagesByConstraints(constraintProvider, packages, dependency.Id, allowPrereleaseVersions); IList<IPackage> candidates = packages.ToList(); if (preferListedPackages) { // pick among Listed packages first IPackage listedSelectedPackage = ResolveDependencyCore(candidates.Where(PackageExtensions.IsListed), dependency); if (listedSelectedPackage != null) { return listedSelectedPackage; } } return ResolveDependencyCore(candidates, dependency); } private static IPackage ResolveDependencyCore(IEnumerable<IPackage> packages, PackageDependency dependency) { // If version info was specified then use it if (dependency.VersionSpec != null) { packages = packages.FindByVersion(dependency.VersionSpec); return packages.ResolveSafeVersion(); } else { // BUG 840: If no version info was specified then pick the latest return packages.OrderByDescending(p => p.Version) .FirstOrDefault(); } } /// <summary> /// Returns updates for packages from the repository /// </summary> /// <param name="repository">The repository to search for updates</param> /// <param name="packages">Packages to look for updates</param> /// <param name="includePrerelease">Indicates whether to consider prerelease updates.</param> /// <param name="includeAllVersions">Indicates whether to include all versions of an update as opposed to only including the latest version.</param> public static IEnumerable<IPackage> GetUpdates( this IPackageRepository repository, IEnumerable<IPackage> packages, bool includePrerelease, bool includeAllVersions, IEnumerable<FrameworkName> targetFramework = null) { var serviceBasedRepository = repository as IServiceBasedRepository; return serviceBasedRepository != null ? serviceBasedRepository.GetUpdates(packages, includePrerelease, includeAllVersions, targetFramework) : repository.GetUpdatesCore(packages, includePrerelease, includeAllVersions, targetFramework); } public static IEnumerable<IPackage> GetUpdatesCore(this IPackageRepository repository, IEnumerable<IPackageMetadata> packages, bool includePrerelease, bool includeAllVersions, IEnumerable<FrameworkName> targetFramework) { List<IPackageMetadata> packageList = packages.ToList(); if (!packageList.Any()) { return Enumerable.Empty<IPackage>(); } // These are the packages that we need to look at for potential updates. ILookup<string, IPackage> sourcePackages = GetUpdateCandidates(repository, packageList, includePrerelease) .ToList() .ToLookup(package => package.Id, StringComparer.OrdinalIgnoreCase); var updates = from package in packageList from candidate in sourcePackages[package.Id] where (candidate.Version > package.Version) && SupportsTargetFrameworks(targetFramework, candidate) select candidate; if (!includeAllVersions) { return updates.CollapseById(); } return updates; } private static bool SupportsTargetFrameworks(IEnumerable<FrameworkName> targetFramework, IPackage package) { return targetFramework.IsEmpty() || targetFramework.Any(t => VersionUtility.IsCompatible(t, package.GetSupportedFrameworks())); } public static IPackageRepository Clone(this IPackageRepository repository) { var cloneableRepository = repository as ICloneableRepository; if (cloneableRepository != null) { return cloneableRepository.Clone(); } return repository; } /// <summary> /// Since odata dies when our query for updates is too big. We query for updates 10 packages at a time /// and return the full list of candidates for updates. /// </summary> private static IEnumerable<IPackage> GetUpdateCandidates( IPackageRepository repository, IEnumerable<IPackageMetadata> packages, bool includePrerelease) { var query = FindPackages(repository, packages, GetFilterExpression); if (!includePrerelease) { query = query.Where(p => p.IsReleaseVersion()); } // for updates, we never consider unlisted packages query = query.Where(PackageExtensions.IsListed); return query; } /// <summary> /// For the list of input packages generate an expression like: /// p => p.Id == 'package1id' or p.Id == 'package2id' or p.Id == 'package3id'... up to package n /// </summary> private static Expression<Func<IPackage, bool>> GetFilterExpression(IEnumerable<IPackageMetadata> packages) { return GetFilterExpression(packages.Select(p => p.Id)); } [SuppressMessage("Microsoft.Globalization", "CA1304:SpecifyCultureInfo", MessageId = "System.String.ToLower", Justification = "This is for a linq query")] private static Expression<Func<IPackage, bool>> GetFilterExpression(IEnumerable<string> ids) { ParameterExpression parameterExpression = Expression.Parameter(typeof(IPackageMetadata)); Expression expressionBody = ids.Select(id => GetCompareExpression(parameterExpression, id.ToLower())) .Aggregate(Expression.OrElse); return Expression.Lambda<Func<IPackage, bool>>(expressionBody, parameterExpression); } /// <summary> /// Builds the expression: package.Id.ToLower() == "somepackageid" /// </summary> private static Expression GetCompareExpression(Expression parameterExpression, object value) { // package.Id Expression propertyExpression = Expression.Property(parameterExpression, "Id"); // .ToLower() Expression toLowerExpression = Expression.Call(propertyExpression, typeof(string).GetMethod("ToLower", Type.EmptyTypes)); // == localPackage.Id return Expression.Equal(toLowerExpression, Expression.Constant(value)); } private static IEnumerable<IPackage> FilterPackagesByConstraints( IPackageConstraintProvider constraintProvider, IEnumerable<IPackage> packages, string packageId, bool allowPrereleaseVersions) { constraintProvider = constraintProvider ?? NullConstraintProvider.Instance; // Filter packages by this constraint IVersionSpec constraint = constraintProvider.GetConstraint(packageId); if (constraint != null) { packages = packages.FindByVersion(constraint); } if (!allowPrereleaseVersions) { packages = packages.Where(p => p.IsReleaseVersion()); } return packages; } internal static IPackage ResolveSafeVersion(this IEnumerable<IPackage> packages) { // Return null if there's no packages if (packages == null || !packages.Any()) { return null; } // We want to take the biggest build and revision number for the smallest // major and minor combination (we want to make some versioning assumptions that the 3rd number is a non-breaking bug fix). This is so that we get the closest version // to the dependency, but also get bug fixes without requiring people to manually update the nuspec. // For example, if A -> B 1.0.0 and the feed has B 1.0.0 and B 1.0.1 then the more correct choice is B 1.0.1. // If we don't do this, A will always end up getting the 'buggy' 1.0.0, // unless someone explicitly changes it to ask for 1.0.1, which is very painful if many packages are using B 1.0.0. var groups = from p in packages group p by new { p.Version.Version.Major, p.Version.Version.Minor } into g orderby g.Key.Major, g.Key.Minor select g; return (from p in groups.First() orderby p.Version descending select p).FirstOrDefault(); } } }
/* * Copyright (c) 2006-2016, openmetaverse.co * All rights reserved. * * - Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * - Neither the name of the Second Life Reverse Engineering Team nor the names * of its contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Text; using OpenMetaverse; namespace OpenMetaverse { /// <summary> /// /// </summary> public enum PacketFrequency : byte { /// <summary></summary> Low, /// <summary></summary> Medium, /// <summary></summary> High } } namespace OpenMetaverse.Packets { /// <summary> /// Thrown when a packet could not be successfully deserialized /// </summary> public class MalformedDataException : ApplicationException { /// <summary> /// Default constructor /// </summary> public MalformedDataException() { } /// <summary> /// Constructor that takes an additional error message /// </summary> /// <param name="Message">An error message to attach to this exception</param> public MalformedDataException(string Message) : base(Message) { this.Source = "Packet decoding"; } } /// <summary> /// The header of a message template packet. Holds packet flags, sequence /// number, packet ID, and any ACKs that will be appended at the end of /// the packet /// </summary> public struct Header { public bool Reliable; public bool Resent; public bool Zerocoded; public bool AppendedAcks; public uint Sequence; public ushort ID; public PacketFrequency Frequency; public uint[] AckList; public void ToBytes(byte[] bytes, ref int i) { byte flags = 0; if (Reliable) flags |= Helpers.MSG_RELIABLE; if (Resent) flags |= Helpers.MSG_RESENT; if (Zerocoded) flags |= Helpers.MSG_ZEROCODED; if (AppendedAcks) flags |= Helpers.MSG_APPENDED_ACKS; // Flags bytes[i++] = flags; // Sequence number Utils.UIntToBytesBig(Sequence, bytes, i); i += 4; // Extra byte bytes[i++] = 0; // Packet ID switch (Frequency) { case PacketFrequency.High: // 1 byte ID bytes[i++] = (byte)ID; break; case PacketFrequency.Medium: // 2 byte ID bytes[i++] = 0xFF; bytes[i++] = (byte)ID; break; case PacketFrequency.Low: // 4 byte ID bytes[i++] = 0xFF; bytes[i++] = 0xFF; Utils.UInt16ToBytesBig(ID, bytes, i); i += 2; break; } } public void FromBytes(byte[] bytes, ref int pos, ref int packetEnd) { this = BuildHeader(bytes, ref pos, ref packetEnd); } /// <summary> /// Convert the AckList to a byte array, used for packet serializing /// </summary> /// <param name="bytes">Reference to the target byte array</param> /// <param name="i">Beginning position to start writing to in the byte /// array, will be updated with the ending position of the ACK list</param> public void AcksToBytes(byte[] bytes, ref int i) { foreach (uint ack in AckList) { Utils.UIntToBytesBig(ack, bytes, i); i += 4; } if (AckList.Length > 0) { bytes[i++] = (byte)AckList.Length; } } /// <summary> /// /// </summary> /// <param name="bytes"></param> /// <param name="pos"></param> /// <param name="packetEnd"></param> /// <returns></returns> public static Header BuildHeader(byte[] bytes, ref int pos, ref int packetEnd) { Header header; byte flags = bytes[pos]; header.AppendedAcks = (flags & Helpers.MSG_APPENDED_ACKS) != 0; header.Reliable = (flags & Helpers.MSG_RELIABLE) != 0; header.Resent = (flags & Helpers.MSG_RESENT) != 0; header.Zerocoded = (flags & Helpers.MSG_ZEROCODED) != 0; header.Sequence = (uint)((bytes[pos + 1] << 24) + (bytes[pos + 2] << 16) + (bytes[pos + 3] << 8) + bytes[pos + 4]); // Set the frequency and packet ID number if (bytes[pos + 6] == 0xFF) { if (bytes[pos + 7] == 0xFF) { header.Frequency = PacketFrequency.Low; if (header.Zerocoded && bytes[pos + 8] == 0) header.ID = bytes[pos + 10]; else header.ID = (ushort)((bytes[pos + 8] << 8) + bytes[pos + 9]); pos += 10; } else { header.Frequency = PacketFrequency.Medium; header.ID = bytes[pos + 7]; pos += 8; } } else { header.Frequency = PacketFrequency.High; header.ID = bytes[pos + 6]; pos += 7; } header.AckList = null; CreateAckList(ref header, bytes, ref packetEnd); return header; } /// <summary> /// /// </summary> /// <param name="header"></param> /// <param name="bytes"></param> /// <param name="packetEnd"></param> static void CreateAckList(ref Header header, byte[] bytes, ref int packetEnd) { if (header.AppendedAcks) { int count = bytes[packetEnd--]; header.AckList = new uint[count]; for (int i = 0; i < count; i++) { header.AckList[i] = (uint)( (bytes[(packetEnd - i * 4) - 3] << 24) | (bytes[(packetEnd - i * 4) - 2] << 16) | (bytes[(packetEnd - i * 4) - 1] << 8) | (bytes[(packetEnd - i * 4) ])); } packetEnd -= (count * 4); } } } /// <summary> /// A block of data in a packet. Packets are composed of one or more blocks, /// each block containing one or more fields /// </summary> public abstract class PacketBlock { /// <summary>Current length of the data in this packet</summary> public abstract int Length { get; } /// <summary> /// Create a block from a byte array /// </summary> /// <param name="bytes">Byte array containing the serialized block</param> /// <param name="i">Starting position of the block in the byte array. /// This will point to the data after the end of the block when the /// call returns</param> public abstract void FromBytes(byte[] bytes, ref int i); /// <summary> /// Serialize this block into a byte array /// </summary> /// <param name="bytes">Byte array to serialize this block into</param> /// <param name="i">Starting position in the byte array to serialize to. /// This will point to the position directly after the end of the /// serialized block when the call returns</param> public abstract void ToBytes(byte[] bytes, ref int i); }
using System; using System.Collections.Generic; using System.Linq; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.GamerServices; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Media; using Microsoft.Xna.Framework.Net; using Microsoft.Xna.Framework.Storage; namespace ZombieSmash{ public class TitleScreen : Microsoft.Xna.Framework.DrawableGameComponent { private ContentManager Content; private Rectangle window; private bool beginGame = false; private bool goToInstructions = false; private MouseState prevMS; private SpriteBatch spriteBatch; private MousePointer crosshair; private SpriteFont headlineFont; private Sprite instructionText; private Sprite startText; private Texture2D soldier; private Texture2D zombie; private Texture2D road; private Texture2D buildings; private Texture2D clouds; private Texture2D debris; public TitleScreen(Game game) : base (game) { Content = Game.Content; window = Game.Window.ClientBounds; } public override void Initialize() { // TODO: Add your initialization logic here base.Initialize(); } protected override void LoadContent() { // TODO: use this.Content to load your game content here prevMS = Mouse.GetState(); spriteBatch = new SpriteBatch(Game.GraphicsDevice); soldier = Content.Load<Texture2D>("images/cartoonSoldier"); zombie = Content.Load<Texture2D>("images/zombie"); road = Content.Load<Texture2D>("images/side_road"); buildings = Content.Load<Texture2D>("images/ruined_buildings"); clouds = Content.Load<Texture2D>("images/clouds"); debris = Content.Load<Texture2D>("images/debris"); headlineFont = Content.Load<SpriteFont>("Fonts/SpriteFont1"); instructionText = new Sprite(Content.Load<Texture2D>("images/instructions"), new Point(200, 40), 0, new Vector2(500, 450)); startText = new Sprite(Content.Load<Texture2D>("images/start_game"), new Point(200, 40), 0, new Vector2(500, 530)); crosshair = new MousePointer(Content.Load<Texture2D>("images/crosshair"), new Point(40, 40), 5, new Vector2(0, 0)); } public override void Update(GameTime gameTime) { MouseState ms = Mouse.GetState(); crosshair.Update(gameTime, window); if (crosshair.getCollisionArea().Intersects(instructionText.getCollisionArea())) { if (ms.LeftButton == ButtonState.Released && prevMS.LeftButton == ButtonState.Pressed) { goToInstructions = true; } } else if (crosshair.getCollisionArea().Intersects(startText.getCollisionArea())) { if (ms.LeftButton == ButtonState.Released && prevMS.LeftButton == ButtonState.Pressed) { beginGame = true; } } prevMS = ms; base.Update(gameTime); } public bool showInstructions() { return goToInstructions; } public void resetTitleScreen() { goToInstructions = false; beginGame = false; } public bool startGame() { return beginGame; } public override void Draw(GameTime gameTime) { Game.GraphicsDevice.Clear(Color.Black); // TODO: Add your drawing code here spriteBatch.Begin(); spriteBatch.Draw(clouds, new Vector2(-10, 0), null, Color.White, 0, new Vector2(0, 0), 0.5f, SpriteEffects.None, 0); spriteBatch.Draw(buildings, new Vector2(0, -225), null, Color.White, 0, new Vector2(0, 0), 1.4f, SpriteEffects.None, 0); spriteBatch.Draw(road, new Vector2(0, -250), null, Color.White, 0, new Vector2(0, 0), 0.5f, SpriteEffects.None, 0); spriteBatch.Draw(debris, new Vector2(0, 290), null, Color.White, 0, new Vector2(0, 0), 2f, SpriteEffects.None, 0); spriteBatch.Draw(soldier, new Vector2(0, 375), null, Color.White, 0, new Vector2(0, 0), 1.0f, SpriteEffects.None, 0); spriteBatch.Draw(zombie, new Vector2(700, 150), null, Color.White, 0, new Vector2(0, 0), 0.15f, SpriteEffects.None, 0); spriteBatch.Draw(zombie, new Vector2(500, 150), null, Color.White, 0, new Vector2(0, 0), 0.15f, SpriteEffects.None, 0); spriteBatch.Draw(zombie, new Vector2(300, 150), null, Color.White, 0, new Vector2(0, 0), 0.15f, SpriteEffects.None, 0); spriteBatch.Draw(zombie, new Vector2(100, 150), null, Color.White, 0, new Vector2(0, 0), 0.15f, SpriteEffects.None, 0); spriteBatch.Draw(zombie, new Vector2(-100, 150), null, Color.White, 0, new Vector2(0, 0), 0.15f, SpriteEffects.None, 0); if (crosshair.getCollisionArea().Intersects(startText.getCollisionArea())) { startText.Draw(gameTime, spriteBatch, Color.Green); } else { startText.Draw(gameTime, spriteBatch); } if (crosshair.getCollisionArea().Intersects(instructionText.getCollisionArea())) { instructionText.Draw(gameTime, spriteBatch, Color.Green); } else { instructionText.Draw(gameTime, spriteBatch); } spriteBatch.DrawString(headlineFont, "Zombie Smash", new Vector2(100, 10), Color.Yellow); crosshair.Draw(gameTime, spriteBatch); spriteBatch.End(); base.Draw(gameTime); } } }
using System; using System.Reactive.Concurrency; using System.Reactive.Subjects; namespace System.Reactive { [SerializableAttribute] public abstract class Notification<T> : IEquatable<Notification<T>> { internal Notification () { } public abstract Exception Exception { get; } public abstract bool HasValue { get; } public abstract NotificationKind Kind { get; } public abstract T Value { get; } public abstract void Accept (IObserver<T> observer); public abstract void Accept (Action<T> onNext, Action<Exception> onError, Action onCompleted); public abstract TResult Accept<TResult> (Func<T, TResult> onNext, Func<Exception, TResult> onError, Func<TResult> onCompleted); public override bool Equals (object obj) { var n = obj as Notification<T>; return n != null && Equals (n); } public abstract bool Equals (Notification<T> other); public static bool operator == (Notification<T> left, Notification<T> right) { return (object) left == null ? (object) right == null : left.Equals (right); } public static bool operator != (Notification<T> left, Notification<T> right) { return (object) left == null ? (object) right != null : !left.Equals (right); } // These were added against the documentation (they lack but they should exist) public override int GetHashCode () { return (int) Kind + ((Exception != null ? Exception.GetHashCode () : 0) << 9) + (HasValue ? Value.GetHashCode () : 0); } public IObservable<T> ToObservable () { #if REACTIVE_2_0 throw new NotImplementedException (); #else var sub = new ReplaySubject<T> (); ApplyToSubject (sub); return sub; #endif } public IObservable<T> ToObservable (IScheduler scheduler) { #if REACTIVE_2_0 throw new NotImplementedException (); #else var sub = new ReplaySubject<T> (scheduler); ApplyToSubject (sub); return sub; #endif } void ApplyToSubject (ISubject<T> sub) { switch (Kind) { case NotificationKind.OnNext: sub.OnNext (Value); break; case NotificationKind.OnError: sub.OnError (Exception); break; case NotificationKind.OnCompleted: sub.OnCompleted (); break; } } // It is public in Microsoft.Phone.Reactive internal class OnCompleted : Notification<T> { public override Exception Exception { get { return null; } } public override bool HasValue { get { return false; } } public override NotificationKind Kind { get { return NotificationKind.OnCompleted; } } public override T Value { get { return default (T); } } public override void Accept (IObserver<T> observer) { if (observer == null) throw new ArgumentNullException ("observer"); observer.OnCompleted (); } public override void Accept (Action<T> onNext, Action<Exception> onError, Action onCompleted) { onCompleted (); } public override TResult Accept<TResult> (Func<T, TResult> onNext, Func<Exception, TResult> onError, Func<TResult> onCompleted) { return onCompleted (); } public override bool Equals (Notification<T> other) { return other is OnCompleted; } public override string ToString () { return "OnCompleted()"; } } // It is public in Microsoft.Phone.Reactive internal class OnError : Notification<T> { Exception error; public OnError (Exception error) { this.error = error; } public override Exception Exception { get { return error; } } public override bool HasValue { get { return false; } } public override NotificationKind Kind { get { return NotificationKind.OnError; } } public override T Value { get { return default (T); } } public override void Accept (IObserver<T> observer) { if (observer == null) throw new ArgumentNullException ("observer"); observer.OnError (error); } public override void Accept (Action<T> onNext, Action<Exception> onError, Action onCompleted) { onError (error); } public override TResult Accept<TResult> (Func<T, TResult> onNext, Func<Exception, TResult> onError, Func<TResult> onCompleted) { return onError (error); } public override bool Equals (Notification<T> other) { var e = other as OnError; return (object) e != null && error.Equals (e.error); } public override string ToString () { return "OnError(" + error + ")"; } } // It is public in Microsoft.Phone.Reactive internal class OnNext : Notification<T> { T value; public OnNext (T value) { this.value = value; } public override Exception Exception { get { return null; } } public override bool HasValue { get { return true; } } public override NotificationKind Kind { get { return NotificationKind.OnNext; } } public override T Value { get { return value; } } public override void Accept (IObserver<T> observer) { if (observer == null) throw new ArgumentNullException ("observer"); observer.OnNext (value); } public override void Accept (Action<T> onNext, Action<Exception> onError, Action onCompleted) { onNext (value); } public override TResult Accept<TResult> (Func<T, TResult> onNext, Func<Exception, TResult> onError, Func<TResult> onCompleted) { return onNext (value); } public override bool Equals (Notification<T> other) { var n = other as OnNext; return (object) n != null && value.Equals (n.value); } public override string ToString () { return "OnNext(" + value + ")"; } } } }
// // Tweener.cs // // Author: // Jason Smith <[email protected]> // // Copyright (c) 2012 Xamarin Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using System.Collections.Generic; using System.Diagnostics; namespace Xwt.Motion { static class AnimationExtensions { class Info { public Easing Easing { get; set; } public uint Rate { get; set; } public uint Length { get; set; } public IAnimatable Owner { get; set; } public Action<double> callback; public Action<double, bool> finished; public Func<bool> repeat; public Tweener tweener; } static Dictionary<string, Info> animations; static Dictionary<string, int> kinetics; static AnimationExtensions () { animations = new Dictionary<string, Info> (); kinetics = new Dictionary<string, int> (); } public static void AnimateKinetic (this IAnimatable self, string name, Func<double, double, bool> callback, double velocity, double drag, Action finished = null) { self.AbortAnimation (name); name += self.GetHashCode ().ToString (); double sign = velocity / Math.Abs (velocity); velocity = Math.Abs (velocity); var tick = Ticker.Default.Insert (step => { var ms = step; velocity -= drag * ms; velocity = Math.Max (0, velocity); bool result = false; if (velocity > 0) { result = callback (sign * velocity * ms, velocity); } if (!result) { if (finished != null) finished (); kinetics.Remove (name); } return result; }); kinetics [name] = tick; } public static void Animate (this IAnimatable self, string name, Animation animation, uint rate = 16, uint length = 250, Easing easing = null, Action<double, bool> finished = null, Func<bool> repeat = null) { self.Animate (name, animation.GetCallback (), rate, length, easing, finished, repeat); } public static Func<double, double> Interpolate (double start, double end = 1.0f, double reverseVal = 0.0f, bool reverse = false) { double target = (reverse ? reverseVal : end); return x => start + (target - start) * x; } public static void Animate (this IAnimatable self, string name, Action<double> callback, double start, double end, uint rate = 16, uint length = 250, Easing easing = null, Action<double, bool> finished = null, Func<bool> repeat = null) { self.Animate<double> (name, Interpolate (start, end), callback, rate, length, easing, finished, repeat); } public static void Animate (this IAnimatable self, string name, Action<double> callback, uint rate = 16, uint length = 250, Easing easing = null, Action<double, bool> finished = null, Func<bool> repeat = null) { self.Animate<double> (name, x => x, callback, rate, length, easing, finished, repeat); } public static void Animate<T> (this IAnimatable self, string name, Func<double, T> transform, Action<T> callback, uint rate = 16, uint length = 250, Easing easing = null, Action<T, bool> finished = null, Func<bool> repeat = null) { if (transform == null) throw new ArgumentNullException ("transform"); if (callback == null) throw new ArgumentNullException ("callback"); if (self == null) throw new ArgumentNullException ("widget"); self.AbortAnimation (name); name += self.GetHashCode ().ToString (); Action<double> step = f => callback (transform(f)); Action<double, bool> final = null; if (finished != null) final = (f, b) => finished (transform(f), b); var info = new Info { Rate = rate, Length = length, Easing = easing ?? Easing.Linear }; Tweener tweener = new Tweener (info.Length, info.Rate); tweener.Easing = info.Easing; tweener.Handle = name; tweener.ValueUpdated += HandleTweenerUpdated; tweener.Finished += HandleTweenerFinished; info.tweener = tweener; info.callback = step; info.finished = final; info.repeat = repeat; info.Owner = self; animations[name] = info; info.callback (0.0f); tweener.Start (); } public static bool AbortAnimation (this IAnimatable self, string handle) { handle += self.GetHashCode ().ToString (); if (animations.ContainsKey (handle)) { Info info = animations [handle]; info.tweener.ValueUpdated -= HandleTweenerUpdated; info.tweener.Finished -= HandleTweenerFinished; info.tweener.Stop (); animations.Remove (handle); if (info.finished != null) info.finished (1.0f, true); return true; } else if (kinetics.ContainsKey (handle)) { Ticker.Default.Remove (kinetics[handle]); kinetics.Remove (handle); } return false; } public static bool AnimationIsRunning (this IAnimatable self, string handle) { handle += self.GetHashCode ().ToString (); return animations.ContainsKey (handle); } static void HandleTweenerUpdated (object o, EventArgs args) { Tweener tweener = o as Tweener; Info info = animations[tweener.Handle]; info.Owner.BatchBegin (); info.callback (tweener.Value); info.Owner.BatchCommit (); } static void HandleTweenerFinished (object o, EventArgs args) { Tweener tweener = o as Tweener; Info info = animations[tweener.Handle]; bool repeat = false; if (info.repeat != null) repeat = info.repeat (); info.Owner.BatchBegin (); info.callback (tweener.Value); if (!repeat) { animations.Remove (tweener.Handle); tweener.ValueUpdated -= HandleTweenerUpdated; tweener.Finished -= HandleTweenerFinished; } if (info.finished != null) info.finished (tweener.Value, false); info.Owner.BatchCommit (); if (repeat) { tweener.Start (); } } } }
// Copyright 2016 Esri. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. // You may obtain a copy of the License at: http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific // language governing permissions and limitations under the License. using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Threading.Tasks; using Esri.ArcGISRuntime.Data; using Esri.ArcGISRuntime.Geometry; using Esri.ArcGISRuntime.Mapping; using Esri.ArcGISRuntime.Symbology; using Esri.ArcGISRuntime.UI.Controls; using Foundation; using UIKit; namespace ArcGISRuntime.Samples.FeatureLayerQuery { [Register("FeatureLayerQuery")] [ArcGISRuntime.Samples.Shared.Attributes.Sample( name: "Feature layer query", category: "Data", description: "Find features in a feature table which match an SQL query.", instructions: "Input the name of a U.S. state into the text field. When you tap the button, a query is performed and the matching features are highlighted or an error is returned.", tags: new[] { "query", "search" })] public class FeatureLayerQuery : UIViewController { // Hold references to UI controls. private MapView _myMapView; private UIBarButtonItem _queryButton; // Create reference to service of US States private const string StatesUrl = "https://sampleserver6.arcgisonline.com/arcgis/rest/services/USA/MapServer/2"; // Create globally available feature table for easy referencing private ServiceFeatureTable _featureTable; // Create globally available feature layer for easy referencing private FeatureLayer _featureLayer; public FeatureLayerQuery() { Title = "Feature layer query"; } private void Initialize() { // Create new Map with basemap. Map map = new Map(BasemapStyle.ArcGISTopographic); // Create and set initial map location. MapPoint initialLocation = new MapPoint(-11000000, 5000000, SpatialReferences.WebMercator); map.InitialViewpoint = new Viewpoint(initialLocation, 100000000); // Create feature table using a URL. _featureTable = new ServiceFeatureTable(new Uri(StatesUrl)); // Create feature layer using this feature table. _featureLayer = new FeatureLayer(_featureTable) { // Set the Opacity of the Feature Layer. Opacity = 0.6, // Work around service setting MaxScale = 10 }; // Create a new renderer for the States Feature Layer. SimpleLineSymbol lineSymbol = new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, Color.Black, 1); SimpleFillSymbol fillSymbol = new SimpleFillSymbol(SimpleFillSymbolStyle.Solid, Color.Transparent, lineSymbol); // Set States feature layer renderer. _featureLayer.Renderer = new SimpleRenderer(fillSymbol); // Add feature layer to the map. map.OperationalLayers.Add(_featureLayer); // Assign the map to the MapView. _myMapView.Map = map; // Set the selection color. _myMapView.SelectionProperties.Color = Color.Cyan; } private void OnQueryClicked(object sender, EventArgs e) { // Prompt for the type of convex hull to create. UIAlertController unionAlert = UIAlertController.Create("Query features", "Enter a state name.", UIAlertControllerStyle.Alert); unionAlert.AddTextField(field => field.Placeholder = "State name"); unionAlert.AddAction(UIAlertAction.Create("Submit query", UIAlertActionStyle.Default, async action => await QueryStateFeature(unionAlert.TextFields[0].Text))); unionAlert.AddAction(UIAlertAction.Create("Cancel", UIAlertActionStyle.Cancel, null)); // Show the alert. PresentViewController(unionAlert, true, null); } private async Task QueryStateFeature(string stateName) { try { // Clear the existing selection. _featureLayer.ClearSelection(); // Create a query parameters that will be used to Query the feature table. QueryParameters queryParams = new QueryParameters(); // Trim whitespace on the state name to prevent broken queries. string formattedStateName = stateName.Trim().ToUpper(); // Construct and assign the where clause that will be used to query the feature table. queryParams.WhereClause = "upper(STATE_NAME) LIKE '%" + formattedStateName + "%'"; // Query the feature table. FeatureQueryResult queryResult = await _featureTable.QueryFeaturesAsync(queryParams); // Cast the QueryResult to a List so the results can be interrogated. List<Feature> features = queryResult.ToList(); if (features.Any()) { // Create an envelope. EnvelopeBuilder envBuilder = new EnvelopeBuilder(SpatialReferences.WebMercator); // Loop over each feature from the query result. foreach (Feature feature in features) { // Add the extent of each matching feature to the envelope. envBuilder.UnionOf(feature.Geometry.Extent); // Select each feature. _featureLayer.SelectFeature(feature); } // Zoom to the extent of the selected feature(s). await _myMapView.SetViewpointGeometryAsync(envBuilder.ToGeometry(), 50); } else { UIAlertView alert = new UIAlertView("State Not Found!", "Add a valid state name.", (IUIAlertViewDelegate) null, "OK", null); alert.Show(); } } catch (Exception ex) { UIAlertView alert = new UIAlertView("Sample error", ex.ToString(), (IUIAlertViewDelegate) null, "OK", null); alert.Show(); } } public override void ViewDidLoad() { base.ViewDidLoad(); Initialize(); } public override void LoadView() { // Create the views. View = new UIView {BackgroundColor = ApplicationTheme.BackgroundColor}; _myMapView = new MapView(); _myMapView.TranslatesAutoresizingMaskIntoConstraints = false; _queryButton = new UIBarButtonItem(); _queryButton.Title = "Query features"; UIToolbar toolbar = new UIToolbar(); toolbar.TranslatesAutoresizingMaskIntoConstraints = false; toolbar.Items = new[] { new UIBarButtonItem(UIBarButtonSystemItem.FlexibleSpace), _queryButton, new UIBarButtonItem(UIBarButtonSystemItem.FlexibleSpace) }; // Add the views. View.AddSubviews(_myMapView, toolbar); // Lay out the views. NSLayoutConstraint.ActivateConstraints(new[] { _myMapView.TopAnchor.ConstraintEqualTo(View.SafeAreaLayoutGuide.TopAnchor), _myMapView.LeadingAnchor.ConstraintEqualTo(View.LeadingAnchor), _myMapView.TrailingAnchor.ConstraintEqualTo(View.TrailingAnchor), _myMapView.BottomAnchor.ConstraintEqualTo(toolbar.TopAnchor), toolbar.BottomAnchor.ConstraintEqualTo(View.SafeAreaLayoutGuide.BottomAnchor), toolbar.LeadingAnchor.ConstraintEqualTo(View.LeadingAnchor), toolbar.TrailingAnchor.ConstraintEqualTo(View.TrailingAnchor), }); } public override void ViewWillAppear(bool animated) { base.ViewWillAppear(animated); // Subscribe to events. _queryButton.Clicked += OnQueryClicked; } public override void ViewDidDisappear(bool animated) { base.ViewDidDisappear(animated); // Unsubscribe from events, per best practice. _queryButton.Clicked -= OnQueryClicked; } } }
// 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.Threading; using System.Threading.Tasks; using Xunit; using Xunit.Abstractions; namespace System.IO.Tests { public class FileSystemWatcher_Multiple_Test : FileSystemWatcherTest { private readonly ITestOutputHelper _output; private void OnError(object source, ErrorEventArgs e) { string msg = $"Watcher failed: {e.GetException()} source={source} {source.GetHashCode()}"; _output.WriteLine(msg); // Repeat on Console so it easier to triage in CI. Console.WriteLine(msg); } public FileSystemWatcher_Multiple_Test(ITestOutputHelper output) { _output = output; } [OuterLoop] [Fact] public void FileSystemWatcher_File_Create_ExecutionContextFlowed() { using (var watcher1 = new FileSystemWatcher(TestDirectory)) using (var watcher2 = new FileSystemWatcher(TestDirectory)) { string fileName = Path.Combine(TestDirectory, "file"); watcher1.Filter = Path.GetFileName(fileName); watcher2.Filter = Path.GetFileName(fileName); var local = new AsyncLocal<int>(); var tcs1 = new TaskCompletionSource<int>(); var tcs2 = new TaskCompletionSource<int>(); watcher1.Created += (s, e) => tcs1.SetResult(local.Value); watcher2.Created += (s, e) => tcs2.SetResult(local.Value); watcher1.Error += OnError; watcher2.Error += OnError; local.Value = 42; watcher1.EnableRaisingEvents = true; local.Value = 84; watcher2.EnableRaisingEvents = true; local.Value = 168; File.Create(fileName).Dispose(); Task.WaitAll(new[] { tcs1.Task, tcs2.Task }, WaitForExpectedEventTimeout); Assert.Equal(42, tcs1.Task.Result); Assert.Equal(84, tcs2.Task.Result); } } [OuterLoop] [Fact] public void FileSystemWatcher_File_Create_SuppressedExecutionContextHandled() { using (var watcher1 = new FileSystemWatcher(TestDirectory)) { string fileName = Path.Combine(TestDirectory, "FileSystemWatcher_File_Create_SuppressedExecutionContextHandled"); watcher1.Filter = Path.GetFileName(fileName); watcher1.Error += OnError; var local = new AsyncLocal<int>(); var tcs1 = new TaskCompletionSource<int>(); watcher1.Created += (s, e) => tcs1.SetResult(local.Value); local.Value = 42; ExecutionContext.SuppressFlow(); try { watcher1.EnableRaisingEvents = true; } finally { ExecutionContext.RestoreFlow(); } File.Create(fileName).Dispose(); tcs1.Task.Wait(WaitForExpectedEventTimeout); Assert.Equal(0, tcs1.Task.Result); } } [OuterLoop] [Fact] public void FileSystemWatcher_File_Create_NotAffectEachOther() { using (var watcher1 = new FileSystemWatcher(TestDirectory)) using (var watcher2 = new FileSystemWatcher(TestDirectory)) using (var watcher3 = new FileSystemWatcher(TestDirectory)) { string fileName = Path.Combine(TestDirectory, "FileSystemWatcher_File_Create_NotAffectEachOther"); watcher1.Filter = Path.GetFileName(fileName); watcher2.Filter = Path.GetFileName(fileName); watcher3.Filter = Path.GetFileName(fileName); watcher1.Error += OnError; watcher2.Error += OnError; watcher3.Error += OnError; AutoResetEvent autoResetEvent1 = WatchCreated(watcher1, new[] { fileName }).EventOccured; AutoResetEvent autoResetEvent2 = WatchCreated(watcher2, new[] { fileName }).EventOccured; AutoResetEvent autoResetEvent3 = WatchCreated(watcher3, new[] { fileName }).EventOccured; watcher1.EnableRaisingEvents = true; watcher2.EnableRaisingEvents = true; watcher3.EnableRaisingEvents = true; File.Create(fileName).Dispose(); Assert.True(WaitHandle.WaitAll(new[] { autoResetEvent1, autoResetEvent2, autoResetEvent3 }, WaitForExpectedEventTimeout_NoRetry)); File.Delete(fileName); watcher1.EnableRaisingEvents = false; File.Create(fileName).Dispose(); Assert.False(autoResetEvent1.WaitOne(WaitForUnexpectedEventTimeout)); Assert.True(WaitHandle.WaitAll(new[] { autoResetEvent2, autoResetEvent3 }, WaitForExpectedEventTimeout_NoRetry)); } } [OuterLoop] [Fact] public void FileSystemWatcher_File_Create_WatchOwnPath() { using (var dir = new TempDirectory(GetTestFilePath())) using (var dir1 = new TempDirectory(Path.Combine(dir.Path, "dir1"))) using (var dir2 = new TempDirectory(Path.Combine(dir.Path, "dir2"))) using (var watcher1 = new FileSystemWatcher(dir1.Path, "*")) using (var watcher2 = new FileSystemWatcher(dir2.Path, "*")) { watcher1.Error += OnError; watcher2.Error += OnError; string fileName1 = Path.Combine(dir1.Path, "file"); string fileName2 = Path.Combine(dir2.Path, "file"); AutoResetEvent autoResetEvent1 = WatchCreated(watcher1, new[] { fileName1 }).EventOccured; AutoResetEvent autoResetEvent2 = WatchCreated(watcher2, new[] { fileName2 }).EventOccured; watcher1.EnableRaisingEvents = true; watcher2.EnableRaisingEvents = true; File.Create(fileName1).Dispose(); Assert.True(autoResetEvent1.WaitOne(WaitForExpectedEventTimeout_NoRetry)); Assert.False(autoResetEvent2.WaitOne(WaitForUnexpectedEventTimeout)); File.Create(fileName2).Dispose(); Assert.True(autoResetEvent2.WaitOne(WaitForExpectedEventTimeout_NoRetry)); Assert.False(autoResetEvent1.WaitOne(WaitForUnexpectedEventTimeout)); } } [OuterLoop] [Theory] [InlineData(true)] [InlineData(false)] public void FileSystemWatcher_File_Create_ForceLoopRestart(bool useExistingWatchers) { FileSystemWatcher[] watchers = new FileSystemWatcher[64]; FileSystemWatcher[] watchers1 = new FileSystemWatcher[64]; try { string fileName = Path.Combine(TestDirectory, "FileSystemWatcher_File_Create_ForceLoopRestart"); AutoResetEvent[] autoResetEvents = new AutoResetEvent[64]; for (var i = 0; i < watchers.Length; i++) { watchers[i] = new FileSystemWatcher(TestDirectory); watchers[i].Filter = Path.GetFileName(fileName); autoResetEvents[i] = WatchCreated(watchers[i], new[] { fileName }).EventOccured; watchers[i].EnableRaisingEvents = true; } File.Create(fileName).Dispose(); Assert.True(WaitHandle.WaitAll(autoResetEvents, WaitForExpectedEventTimeout_NoRetry)); File.Delete(fileName); for (var i = 0; i < watchers.Length; i++) { watchers[i].EnableRaisingEvents = false; } File.Create(fileName).Dispose(); Assert.False(WaitHandle.WaitAll(autoResetEvents, WaitForUnexpectedEventTimeout)); File.Delete(fileName); if (useExistingWatchers) { for (var i = 0; i < watchers.Length; i++) { watchers[i].EnableRaisingEvents = true; } File.Create(fileName).Dispose(); Assert.True(WaitHandle.WaitAll(autoResetEvents, WaitForExpectedEventTimeout_NoRetry)); } else { AutoResetEvent[] autoResetEvents1 = new AutoResetEvent[64]; for (var i = 0; i < watchers1.Length; i++) { watchers1[i] = new FileSystemWatcher(TestDirectory); watchers1[i].Filter = Path.GetFileName(fileName); autoResetEvents1[i] = WatchCreated(watchers1[i], new[] { fileName }).EventOccured; watchers1[i].EnableRaisingEvents = true; } File.Create(fileName).Dispose(); Assert.True(WaitHandle.WaitAll(autoResetEvents1, WaitForExpectedEventTimeout_NoRetry)); } } finally { for (var i = 0; i < watchers.Length; i++) { watchers[i]?.Dispose(); watchers1[i]?.Dispose(); } } } [OuterLoop] [Fact] public void FileSystemWatcher_File_Changed_NotAffectEachOther() { using (var testDirectory = new TempDirectory(GetTestFilePath())) using (var file = new TempFile(Path.Combine(testDirectory.Path, "file"))) using (var otherFile = new TempFile(Path.Combine(testDirectory.Path, "otherfile"))) using (var watcher1 = new FileSystemWatcher(testDirectory.Path, Path.GetFileName(file.Path))) using (var watcher2 = new FileSystemWatcher(testDirectory.Path, Path.GetFileName(file.Path))) using (var watcher3 = new FileSystemWatcher(testDirectory.Path, Path.GetFileName(otherFile.Path))) { AutoResetEvent autoResetEvent1 = WatchChanged(watcher1, new[] { Path.Combine(testDirectory.Path, "file") }).EventOccured; AutoResetEvent autoResetEvent2 = WatchChanged(watcher2, new[] { Path.Combine(testDirectory.Path, "file") }).EventOccured; AutoResetEvent autoResetEvent3 = WatchChanged(watcher3, new[] { Path.Combine(testDirectory.Path, "otherfile") }).EventOccured; watcher1.Error += OnError; watcher2.Error += OnError; watcher3.Error += OnError; watcher1.EnableRaisingEvents = true; watcher2.EnableRaisingEvents = true; watcher3.EnableRaisingEvents = true; Directory.SetLastWriteTime(file.Path, DateTime.Now + TimeSpan.FromSeconds(10)); Assert.True(WaitHandle.WaitAll(new[] { autoResetEvent1, autoResetEvent2 }, WaitForExpectedEventTimeout_NoRetry)); Assert.False(autoResetEvent3.WaitOne(WaitForUnexpectedEventTimeout)); Directory.SetLastWriteTime(otherFile.Path, DateTime.Now + TimeSpan.FromSeconds(10)); Assert.False(WaitHandle.WaitAll(new[] { autoResetEvent1, autoResetEvent2 }, WaitForUnexpectedEventTimeout)); Assert.True(autoResetEvent3.WaitOne(WaitForExpectedEventTimeout_NoRetry)); watcher1.EnableRaisingEvents = false; Directory.SetLastWriteTime(file.Path, DateTime.Now + TimeSpan.FromSeconds(10)); Assert.False(WaitHandle.WaitAll(new[] { autoResetEvent1, autoResetEvent3 }, WaitForUnexpectedEventTimeout)); Assert.True(autoResetEvent2.WaitOne(WaitForExpectedEventTimeout_NoRetry)); Directory.SetLastWriteTime(otherFile.Path, DateTime.Now + TimeSpan.FromSeconds(10)); Assert.False(WaitHandle.WaitAll(new[] { autoResetEvent1, autoResetEvent2 }, WaitForUnexpectedEventTimeout)); Assert.True(autoResetEvent3.WaitOne(WaitForExpectedEventTimeout_NoRetry)); } } [OuterLoop] [Fact] public void FileSystemWatcher_File_Delet_NotAffectEachOther() { using (var watcher1 = new FileSystemWatcher(TestDirectory)) using (var watcher2 = new FileSystemWatcher(TestDirectory)) using (var watcher3 = new FileSystemWatcher(TestDirectory)) { string fileName = Path.Combine(TestDirectory, "file"); File.Create(fileName).Dispose(); watcher1.Filter = Path.GetFileName(fileName); watcher2.Filter = Path.GetFileName(fileName); watcher3.Filter = Path.GetFileName(fileName); watcher1.Error += OnError; watcher2.Error += OnError; watcher3.Error += OnError; AutoResetEvent autoResetEvent1 = WatchDeleted(watcher1, new[] { fileName }).EventOccured; AutoResetEvent autoResetEvent2 = WatchDeleted(watcher2, new[] { fileName }).EventOccured; AutoResetEvent autoResetEvent3 = WatchDeleted(watcher3, new[] { fileName }).EventOccured; watcher1.EnableRaisingEvents = true; watcher2.EnableRaisingEvents = true; watcher3.EnableRaisingEvents = true; File.Delete(fileName); Assert.True(WaitHandle.WaitAll(new[] { autoResetEvent1, autoResetEvent2, autoResetEvent3 }, WaitForExpectedEventTimeout_NoRetry)); File.Create(fileName).Dispose(); watcher1.EnableRaisingEvents = false; File.Delete(fileName); Assert.False(autoResetEvent1.WaitOne(WaitForUnexpectedEventTimeout)); Assert.True(WaitHandle.WaitAll(new[] { autoResetEvent2, autoResetEvent3 }, WaitForExpectedEventTimeout_NoRetry)); } } [OuterLoop] [Fact] [PlatformSpecific(TestPlatforms.OSX)] public void FileSystemWatcher_File_Rename_NotAffectEachOther() { using (var testDirectory = new TempDirectory(GetTestFilePath())) using (var file = new TempFile(Path.Combine(testDirectory.Path, "file"))) using (var watcher1 = new FileSystemWatcher(testDirectory.Path, Path.GetFileName(file.Path))) using (var watcher2 = new FileSystemWatcher(testDirectory.Path, Path.GetFileName(file.Path))) { AutoResetEvent autoResetEvent1_created = WatchCreated(watcher1, new[] { Path.Combine(testDirectory.Path, "file") }).EventOccured; AutoResetEvent autoResetEvent1_deleted = WatchDeleted(watcher1, new[] { Path.Combine(testDirectory.Path, "file") }).EventOccured; AutoResetEvent autoResetEvent2_created = WatchCreated(watcher2, new[] { Path.Combine(testDirectory.Path, "file") }).EventOccured; AutoResetEvent autoResetEvent2_deleted = WatchDeleted(watcher2, new[] { Path.Combine(testDirectory.Path, "file") }).EventOccured; watcher1.Error += OnError; watcher2.Error += OnError; watcher1.EnableRaisingEvents = true; watcher2.EnableRaisingEvents = true; string filePath = file.Path; string filePathRenamed = file.Path + "_renamed"; File.Move(filePath, filePathRenamed); Assert.True(WaitHandle.WaitAll( new[] { autoResetEvent1_created, autoResetEvent1_deleted, autoResetEvent2_created, autoResetEvent2_deleted }, WaitForExpectedEventTimeout_NoRetry)); File.Move(filePathRenamed, filePath); watcher1.EnableRaisingEvents = false; File.Move(filePath, filePathRenamed); Assert.False(WaitHandle.WaitAll( new[] { autoResetEvent1_created, autoResetEvent1_deleted }, WaitForUnexpectedEventTimeout)); Assert.True(WaitHandle.WaitAll( new[] { autoResetEvent2_created, autoResetEvent2_deleted }, WaitForExpectedEventTimeout_NoRetry)); } } } }
// Copyright (c) The Avalonia Project. All rights reserved. // Licensed under the MIT license. See licence.md file in the project root for full license information. using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using Avalonia.Platform; namespace Avalonia.Shared.PlatformSupport { /// <summary> /// Loads assets compiled into the application binary. /// </summary> public class AssetLoader : IAssetLoader { private static readonly Dictionary<string, AssemblyDescriptor> AssemblyNameCache = new Dictionary<string, AssemblyDescriptor>(); private AssemblyDescriptor _defaultAssembly; /// <summary> /// Initializes a new instance of the <see cref="AssetLoader"/> class. /// </summary> /// <param name="assembly"> /// The default assembly from which to load assets for which no assembly is specified. /// </param> public AssetLoader(Assembly assembly = null) { if (assembly == null) assembly = Assembly.GetEntryAssembly(); if (assembly != null) _defaultAssembly = new AssemblyDescriptor(assembly); } /// <summary> /// Sets the default assembly from which to load assets for which no assembly is specified. /// </summary> /// <param name="assembly">The default assembly.</param> public void SetDefaultAssembly(Assembly assembly) { _defaultAssembly = new AssemblyDescriptor(assembly); } /// <summary> /// Checks if an asset with the specified URI exists. /// </summary> /// <param name="uri">The URI.</param> /// <param name="baseUri"> /// A base URI to use if <paramref name="uri"/> is relative. /// </param> /// <returns>True if the asset could be found; otherwise false.</returns> public bool Exists(Uri uri, Uri baseUri = null) { return GetAsset(uri, baseUri) != null; } /// <summary> /// Opens the resource with the requested URI. /// </summary> /// <param name="uri">The URI.</param> /// <param name="baseUri"> /// A base URI to use if <paramref name="uri"/> is relative. /// </param> /// <returns>A stream containing the resource contents.</returns> /// <exception cref="FileNotFoundException"> /// The resource was not found. /// </exception> public Stream Open(Uri uri, Uri baseUri = null) { var asset = GetAsset(uri, baseUri); if (asset == null) { throw new FileNotFoundException($"The resource {uri} could not be found."); } return asset.GetStream(); } private IAssetDescriptor GetAsset(Uri uri, Uri baseUri) { if (!uri.IsAbsoluteUri || uri.Scheme == "resm") { var asm = GetAssembly(uri) ?? GetAssembly(baseUri) ?? _defaultAssembly; if (asm == null && _defaultAssembly == null) { throw new ArgumentException( "No default assembly, entry assembly or explicit assembly specified; " + "don't know where to look up for the resource, try specifiyng assembly explicitly."); } IAssetDescriptor rv; var resourceKey = uri.AbsolutePath; #if __IOS__ // TODO: HACK: to get iOS up and running. Using Shared projects for resources // is flawed as this alters the reource key locations across platforms // I think we need to use Portable libraries from now on to avoid that. if(asm.Name.Contains("iOS")) { resourceKey = resourceKey.Replace("TestApplication", "Avalonia.iOSTestApplication"); } #endif asm.Resources.TryGetValue(resourceKey, out rv); return rv; } throw new ArgumentException($"Invalid uri, see https://github.com/AvaloniaUI/Avalonia/issues/282#issuecomment-166982104", nameof(uri)); } private AssemblyDescriptor GetAssembly(Uri uri) { if (uri != null) { var qs = ParseQueryString(uri); string assemblyName; if (qs.TryGetValue("assembly", out assemblyName)) { return GetAssembly(assemblyName); } } return null; } private AssemblyDescriptor GetAssembly(string name) { if (name == null) { return _defaultAssembly; } AssemblyDescriptor rv; if (!AssemblyNameCache.TryGetValue(name, out rv)) { var loadedAssemblies = AppDomain.CurrentDomain.GetAssemblies(); var match = loadedAssemblies.FirstOrDefault(a => a.GetName().Name == name); if (match != null) { AssemblyNameCache[name] = rv = new AssemblyDescriptor(match); } else { // iOS does not support loading assemblies dynamically! // #if !__IOS__ AssemblyNameCache[name] = rv = new AssemblyDescriptor(Assembly.Load(name)); #endif } } return rv; } private Dictionary<string, string> ParseQueryString(Uri uri) { return uri.Query.TrimStart('?') .Split(new[] { '&' }, StringSplitOptions.RemoveEmptyEntries) .Select(p => p.Split('=')) .ToDictionary(p => p[0], p => p[1]); } private interface IAssetDescriptor { Stream GetStream(); } private class AssemblyResourceDescriptor : IAssetDescriptor { private readonly Assembly _asm; private readonly string _name; public AssemblyResourceDescriptor(Assembly asm, string name) { _asm = asm; _name = name; } public Stream GetStream() { return _asm.GetManifestResourceStream(_name); } } private class AssemblyDescriptor { public AssemblyDescriptor(Assembly assembly) { Assembly = assembly; if (assembly != null) { Resources = assembly.GetManifestResourceNames() .ToDictionary(n => n, n => (IAssetDescriptor)new AssemblyResourceDescriptor(assembly, n)); Name = assembly.GetName().Name; } } public Assembly Assembly { get; } public Dictionary<string, IAssetDescriptor> Resources { get; } public string Name { get; } } } }
// // (C) Copyright 2003-2011 by Autodesk, Inc. // // Permission to use, copy, modify, and distribute this software in // object code form for any purpose and without fee is hereby granted, // provided that the above copyright notice appears in all copies and // that both that copyright notice and the limited warranty and // restricted rights notice below appear in all supporting // documentation. // // AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS. // AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF // MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC. // DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE // UNINTERRUPTED OR ERROR FREE. // // Use, duplication, or disclosure by the U.S. Government is subject to // restrictions set forth in FAR 52.227-19 (Commercial Computer // Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii) // (Rights in Technical Data and Computer Software), as applicable. // using System; using System.Collections.Generic; using System.Text; using System.Collections; using Autodesk.Revit.DB; using Autodesk.Revit.UI; using System.Drawing; using Autodesk.Revit; using System.Windows.Forms; namespace Revit.SDK.Samples.SlabShapeEditing.CS { /// <summary> /// SlabProfile class contains Geometry information of Slab, /// and contains methods used to edit slab's Shape. /// </summary> class SlabProfile { #region class member variables ExternalCommandData m_commandData; //contains reference of Revit Application Autodesk.Revit.DB.Floor m_floor; //object of truss in Revit EdgeArray m_edges; // store all the edges of floor PointF[] m_boundPoints; // store array store bound point of Slab Matrix4 m_to2DMatrix = null; // store the Matrix used to transform 3D points to 2D Matrix4 m_moveToCenterMatrix = null; // store the Matrix used to move points to center Matrix4 m_scaleMatrix = null; // store the Matrix used to scale profile fit to pictureBox Matrix4 m_MoveToPictureBoxCenter = null; // store the Matrix used to move profile to center of pictureBox Matrix4 m_transformMatrix = null; // store the Matrix used to transform Revit coordinate to window UI Matrix4 m_restoreMatrix = null; // store the Matrix used to transform window UI coordinate to Revit Matrix4 m_rotateMatrix = null; //store the matrix which rotate object const int m_sizeXPictureBox = 354; //save picture box's size.X const int m_sizeYPictureBox = 280; //save picture box's size.Y SlabShapeEditor m_slabShapeEditor; //SlabShapeEditor which use to editor shape of slab double m_rotateAngleX = 0; //rotate angle in X direction double m_rotateAngleY = 0; //rotate angle in Y direction #endregion /// <summary> /// constructor /// </summary> /// <param name="floor">Floor object in Revit</param> /// <param name="commandData">contains reference of Revit Application</param> public SlabProfile(Autodesk.Revit.DB.Floor floor, ExternalCommandData commandData) { m_floor = floor; m_commandData = commandData; m_slabShapeEditor = floor.SlabShapeEditor; GetSlabProfileInfo(); } /// <summary> /// Calculate geometry info for Slab /// </summary> public void GetSlabProfileInfo() { // get all the edges of the Slab m_edges = GetFloorEdges(); // Get a matrix which can transform points to 2D m_to2DMatrix = GetTo2DMatrix(); // get the boundary of all the points m_boundPoints = GetBoundsPoints(); // get a matrix which can keep all the points in the center of the canvas m_moveToCenterMatrix = GetMoveToCenterMatrix(); // get a matrix for scaling all the points and lines within the canvas m_scaleMatrix = GetScaleMatrix(); // get a matrix for moving all point in the middle of PictureBox m_MoveToPictureBoxCenter = GetMoveToCenterOfPictureBox(); // transform 3D points to 2D m_transformMatrix = Get3DTo2DMatrix(); // transform from 2D to 3D m_restoreMatrix = Get2DTo3DMatrix(); } /// <summary> /// Get all points of the Slab /// </summary> /// <returns>points array stores all the points on slab</returns> public EdgeArray GetFloorEdges() { EdgeArray edges = new EdgeArray(); Options options = m_commandData.Application.Application.Create.NewGeometryOptions(); options.DetailLevel = DetailLevels.Medium; //make sure references to geometric objects are computed. options.ComputeReferences = true; Autodesk.Revit.DB.GeometryElement geoElem = m_floor.get_Geometry(options); GeometryObjectArray gObjects = geoElem.Objects; //get all the edges in the Geometry object foreach (GeometryObject geo in gObjects) { Solid solid = geo as Solid; if (solid != null) { FaceArray faces = solid.Faces; foreach (Face face in faces) { EdgeArrayArray edgeArrarr = face.EdgeLoops; foreach (EdgeArray edgeArr in edgeArrarr) { foreach (Edge edge in edgeArr) { edges.Append(edge); } } } } } return edges; } /// <summary> /// Get a matrix which can transform points to 2D /// </summary> /// <returns>matrix which can transform points to 2D</returns> public Matrix4 GetTo2DMatrix() { Vector4 xAxis = new Vector4(1, 0 ,0); //Because Y axis in windows UI is downward, so we should Multiply(-1) here Vector4 yAxis = new Vector4(0, -1, 0); Vector4 zAxis = new Vector4(0, 0, 1); Matrix4 result = new Matrix4(xAxis, yAxis, zAxis); return result; } /// <summary> /// calculate the matrix use to scale /// </summary> /// <returns>maxtrix is use to scale the profile</returns> public Matrix4 GetScaleMatrix() { float xScale = 384 / (m_boundPoints[1].X - m_boundPoints[0].X); float yScale = 275 / (m_boundPoints[1].Y - m_boundPoints[0].Y); float factor = xScale <= yScale ? xScale : yScale; return new Matrix4((float)(factor * 0.85)); } /// <summary> /// Get a matrix which can move points to center of itself /// </summary> /// <returns>matrix used to move point to center of itself</returns> public Matrix4 GetMoveToCenterMatrix() { //translate the origin to bound center PointF[] bounds = GetBoundsPoints(); PointF min = bounds[0]; PointF max = bounds[1]; PointF center = new PointF((min.X + max.X) / 2, (min.Y + max.Y) / 2); return new Matrix4(new Vector4(center.X, center.Y, 0)); } /// <summary> /// Get a matrix which can move points to center of picture box /// </summary> /// <returns>matrix used to move point to center of picture box</returns> private Matrix4 GetMoveToCenterOfPictureBox() { return new Matrix4(new Vector4(m_sizeXPictureBox / 2, m_sizeYPictureBox/2, 0)); } /// <summary> /// calculate the matrix used to transform 3D to 2D /// </summary> /// <returns>maxtrix is use to transform 3d points to 2d</returns> public Matrix4 Get3DTo2DMatrix() { Matrix4 result = Matrix4.Multiply( m_to2DMatrix.Inverse(), m_moveToCenterMatrix.Inverse()); result = Matrix4.Multiply(result, m_scaleMatrix); return Matrix4.Multiply(result, m_MoveToPictureBoxCenter); } /// <summary> /// calculate the matrix used to transform 2D to 3D /// </summary> /// <returns>maxtrix is use to transform 2d points to 3d</returns> public Matrix4 Get2DTo3DMatrix() { Matrix4 matrix = Matrix4.Multiply( m_MoveToPictureBoxCenter.Inverse(), m_scaleMatrix.Inverse()); matrix = Matrix4.Multiply( matrix, m_moveToCenterMatrix); return Matrix4.Multiply(matrix, m_to2DMatrix); } /// <summary> /// Get max and min coordinates of all points /// </summary> /// <returns>points array stores the bound of all points</returns> public PointF[] GetBoundsPoints() { Matrix4 matrix = m_to2DMatrix; Matrix4 inverseMatrix = matrix.Inverse(); double minX = 0, maxX = 0, minY = 0, maxY = 0; bool bFirstPoint = true; //get all points on slab List<XYZ> points = new List<XYZ>(); foreach (Edge edge in m_edges) { List<XYZ> edgexyzs = edge.Tessellate() as List<XYZ>; foreach (Autodesk.Revit.DB.XYZ xyz in edgexyzs) { points.Add(xyz); } } //get the max and min point on the face foreach (Autodesk.Revit.DB.XYZ point in points) { Vector4 v = new Vector4(point); Vector4 v1 = inverseMatrix.Transform(v); if (bFirstPoint) { minX = maxX = v1.X; minY = maxY = v1.Y; bFirstPoint = false; } else { if (v1.X < minX) { minX = v1.X; } else if (v1.X > maxX) { maxX = v1.X; } if (v1.Y < minY) { minY = v1.Y; } else if (v1.Y > maxY) { maxY = v1.Y; } } } //return an array with max and min value of all points PointF[] resultPoints = new PointF[2] { new PointF((float)minX, (float)minY), new PointF((float)maxX, (float)maxY) }; return resultPoints; } /// <summary> /// draw profile of Slab in pictureBox /// </summary> /// <param name="graphics">form graphic</param> /// <param name="pen">pen used to draw line in pictureBox</param> public void Draw2D(Graphics graphics, Pen pen) { foreach (Edge edge in m_edges) { List<XYZ> edgexyzs = edge.Tessellate() as List<XYZ>; DrawCurve(graphics, pen, edgexyzs); } } /// <summary> /// draw specific points in pictureBox /// </summary> /// <param name="graphics">form graphic</param> /// <param name="pen">pen used to draw line in pictureBox</param> /// <param name="points">points which need to be drawn</param> public void DrawCurve(Graphics graphics, Pen pen, List<XYZ> points) { //draw slab curves for (int i = 0; i < points.Count - 1; i += 1) { Autodesk.Revit.DB.XYZ point1 = points[i]; Autodesk.Revit.DB.XYZ point2 = points[i + 1]; Vector4 v1 = new Vector4(point1); Vector4 v2 = new Vector4(point2); v1 = m_transformMatrix.Transform(v1); v2 = m_transformMatrix.Transform(v2); if (m_rotateMatrix != null) { v1 = m_rotateMatrix.Transform(v1); v2 = m_rotateMatrix.Transform(v2); } graphics.DrawLine(pen, new PointF((int)v1.X, (int)v1.Y), new PointF((int)v2.X, (int)v2.Y)); } } /// <summary> /// rotate slab with specific angle /// </summary> /// <param name="xAngle">rotate angle in X direction</param> /// <param name="yAngle">rotate angle in Y direction</param> public void RotateFloor(double xAngle, double yAngle) { if (0 == xAngle && 0 == yAngle) { return; } m_rotateAngleX += xAngle; m_rotateAngleY += yAngle; Matrix4 rotateX = Matrix4.RotateX(m_rotateAngleX); Matrix4 rotateY = Matrix4.RotateY(m_rotateAngleY); Matrix4 rotateMatrix = Matrix4.Multiply(rotateX, rotateY); m_rotateMatrix = Matrix4.Multiply(m_MoveToPictureBoxCenter.Inverse(), rotateMatrix); m_rotateMatrix = Matrix4.Multiply(m_rotateMatrix, m_MoveToPictureBoxCenter); } /// <summary> /// make rotate matrix null /// </summary> public void ClearRotateMatrix() { m_rotateMatrix = null; } /// <summary> /// Reset index and clear line tool /// </summary> public void ResetSlabShape() { Transaction transaction = new Transaction( m_commandData.Application.ActiveUIDocument.Document, "ResetSlabShape"); transaction.Start(); m_slabShapeEditor.ResetSlabShape(); transaction.Commit(); //re-calculate geometry info GetSlabProfileInfo(); } /// <summary> /// Add vertex on specific location /// </summary> /// <param name="point">location where vertex add on</param> /// <returns>new created vertex</returns> public SlabShapeVertex AddVertex(PointF point) { Transaction transaction = new Transaction( m_commandData.Application.ActiveUIDocument.Document, "AddVertex"); transaction.Start(); Vector4 v1 = new Vector4(new Autodesk.Revit.DB.XYZ (point.X, point.Y, 0)); v1 = m_restoreMatrix.Transform(v1); SlabShapeVertex vertex = m_slabShapeEditor.DrawPoint(new Autodesk.Revit.DB.XYZ (v1.X, v1.Y, v1.Z)); transaction.Commit(); //re-calculate geometry info GetSlabProfileInfo(); return vertex; } /// <summary> /// Add Crease on specific location /// </summary> /// <param name="point1">first point of location where Crease add on</param> /// <param name="point2">second point of location where Crease add on</param> /// <returns>new created Crease</returns> public SlabShapeCrease AddCrease(PointF point1, PointF point2) { //create first vertex Transaction transaction = new Transaction( m_commandData.Application.ActiveUIDocument.Document, "AddCrease"); transaction.Start(); Vector4 v1 = new Vector4(new Autodesk.Revit.DB.XYZ(point1.X, point1.Y, 0)); v1 = m_restoreMatrix.Transform(v1); SlabShapeVertex vertex1 = m_slabShapeEditor.DrawPoint(new Autodesk.Revit.DB.XYZ(v1.X, v1.Y, v1.Z)); //create second vertex Vector4 v2 = new Vector4(new Autodesk.Revit.DB.XYZ(point2.X, point2.Y, 0)); v2 = m_restoreMatrix.Transform(v2); SlabShapeVertex vertex2 = m_slabShapeEditor.DrawPoint(new Autodesk.Revit.DB.XYZ(v2.X, v2.Y, v2.Z)); //create crease SlabShapeCreaseArray creases = m_slabShapeEditor.DrawSplitLine(vertex1, vertex2); SlabShapeCrease crease = creases.get_Item(0); transaction.Commit(); //re-calculate geometry info GetSlabProfileInfo(); return crease; } /// <summary> /// judge whether point can use to create vertex on slab /// </summary> /// <param name="point1">location where vertex add on</param> /// <returns>whether point can use to create vertex on slab</returns> public bool CanCreateVertex(PointF pointF) { bool createSuccess = false; Transaction transaction = new Transaction( m_commandData.Application.ActiveUIDocument.Document, "CanCreateVertex"); transaction.Start(); Vector4 v1 = new Vector4(new Autodesk.Revit.DB.XYZ (pointF.X, pointF.Y, 0)); v1 = m_restoreMatrix.Transform(v1); SlabShapeVertex vertex = m_slabShapeEditor.DrawPoint(new Autodesk.Revit.DB.XYZ (v1.X, v1.Y, v1.Z)); if (null != vertex) { createSuccess = true; } transaction.RollBack(); //re-calculate geometry info GetSlabProfileInfo(); return createSuccess; } } }
/* * Copyright 2008-2013 the GAP developers. See the NOTICE file at the * top-level directory of this distribution, and at * https://gapwiki.chiro.be/copyright * Verfijnen gebruikersrechten Copyright 2015 Chirojeugd-Vlaanderen vzw * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.Linq; using Chiro.Gap.Domain; using Chiro.Gap.Poco.Model; using Chiro.Gap.WorkerInterfaces; namespace Chiro.Gap.Dummies { /// <summary> /// Autorisatiemanager die altijd alle rechten toekent, /// BEHALVE supergav. /// (nuttig voor testen van niet-autorisatiegebonden /// business logica.) /// </summary> public class AutMgrAltijdGav : IAutorisatieManager { public IList<int> EnkelMijnGelieerdePersonen(IEnumerable<int> gelieerdePersonenIDs) { return gelieerdePersonenIDs.ToList(); } public IList<int> EnkelMijnPersonen(IEnumerable<int> personenIDs) { return personenIDs.ToList(); } public string GebruikersNaamGet() { throw new NotImplementedException(); } public bool IsSuperGav() { return false; } public bool IsGav(Groep groep) { return true; } public bool IsGav(CommunicatieVorm communicatieVorm) { return true; } public bool IsGav(GroepsWerkJaar groepsWerkJaar) { return true; } public bool IsGav(GelieerdePersoon gelieerdePersoon) { return true; } public bool IsGav(Deelnemer gelieerdePersoon) { return true; } public bool IsGav(Plaats gelieerdePersoon) { return true; } public bool IsGav(Uitstap gelieerdePersoon) { return true; } public bool IsGav(GebruikersRechtV2 gelieerdePersoon) { return true; } public bool IsGav(Lid gelieerdePersoon) { return true; } public bool IsGav(Afdeling gelieerdePersoon) { return true; } public bool IsGav(Categorie gelieerdePersoon) { return true; } public bool IsGav(IList<GelieerdePersoon> gelieerdePersonen) { return true; } public List<GelieerdePersoon> MijnGelieerdePersonen(IList<Persoon> personen) { return personen.SelectMany(p => p.GelieerdePersoon).ToList(); } public bool IsGav(IList<PersoonsAdres> persoonsAdressen) { return true; } public bool IsGav(IList<Persoon> personen) { return true; } public bool IsGav(IList<Lid> leden) { return true; } public bool IsGav(Abonnement abonnement) { return true; } public bool IsGav(IList<Groep> groepen) { return true; } public bool IsGav(Persoon p) { return true; } public bool HeeftPermissies(Groep groep, Domain.Permissies permissies) { return true; } public Permissies PermissiesOphalen(Lid lid) { return Permissies.Bewerken; } public Permissies PermissiesOphalen(Functie functie) { return functie.IsNationaal ? Permissies.Lezen : Permissies.Bewerken; } public bool MagLezen(Persoon ik, Persoon persoon2) { return true; } public Permissies PermissiesOphalen(Groep groep, SecurityAspect aspecten) { return Permissies.Bewerken; } public bool MagZichzelfLezen(Persoon persoon) { return true; } public Permissies PermissiesOphalen(GelieerdePersoon gelieerdePersoon) { return Permissies.Bewerken; } public Permissies EigenPermissies(Persoon persoon) { return Permissies.Bewerken; } public GebruikersRechtV2 GebruikersRechtOpEigenGroep(GelieerdePersoon gp) { return new GebruikersRechtV2 { Persoon = gp.Persoon, Groep = gp.Groep, PersoonsPermissies = Permissies.Bewerken, GroepsPermissies = Permissies.Bewerken, AfdelingsPermissies = Permissies.Bewerken, IedereenPermissies = Permissies.Bewerken, VervalDatum = DateTime.Now.AddDays(1) }; } } }
//--------------------------------------------------------------------------- // // Copyright (C) Microsoft Corporation. All rights reserved. // // File: LineProperties.cs // // Description: Text line properties provider. // // History: // 04/25/2003 : [....] - moving from Avalon branch. // //--------------------------------------------------------------------------- using System; using System.Diagnostics; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Media; using System.Windows.Media.TextFormatting; using MS.Internal.Documents; using MS.Internal.PtsHost; // TextParagraph namespace MS.Internal.Text { // ---------------------------------------------------------------------- // Text line properties provider. // ---------------------------------------------------------------------- internal class LineProperties : TextParagraphProperties { // ------------------------------------------------------------------ // // TextParagraphProperties Implementation // // ------------------------------------------------------------------ #region TextParagraphProperties Implementation /// <summary> /// This property specifies whether the primary text advance /// direction shall be left-to-right, right-to-left, or top-to-bottom. /// </summary> public override FlowDirection FlowDirection { get { return _flowDirection; } } /// <summary> /// This property describes how inline content of a block is aligned. /// </summary> public override TextAlignment TextAlignment { get { return IgnoreTextAlignment ? TextAlignment.Left : _textAlignment; } } /// <summary> /// Paragraph's line height /// </summary> /// <remarks> /// TextFormatter does not do appropriate line height handling, so /// report always 0 as line height. /// Line height is handled by TextFormatter host. /// </remarks> public override double LineHeight { get { if (LineStackingStrategy == LineStackingStrategy.BlockLineHeight && !Double.IsNaN(_lineHeight)) { return _lineHeight; } return 0.0; } } /// <summary> /// Indicates the first line of the paragraph. /// </summary> public override bool FirstLineInParagraph { get { return false; } } /// <summary> /// Paragraph's default run properties /// </summary> public override TextRunProperties DefaultTextRunProperties { get { return _defaultTextProperties; } } /// <summary> /// Text decorations specified at the paragraph level. /// </summary> public override TextDecorationCollection TextDecorations { get { return _defaultTextProperties.TextDecorations; } } /// <summary> /// This property controls whether or not text wraps when it reaches the flow edge /// of its containing block box /// </summary> public override TextWrapping TextWrapping { get { return _textWrapping; } } /// <summary> /// This property specifies marker characteristics of the first line in paragraph /// </summary> public override TextMarkerProperties TextMarkerProperties { get { return _markerProperties; } } /// <summary> /// Line indentation /// </summary> /// <remarks> /// Line indentation. Line indent by default is always 0. /// Use FirstLineProperties class to return real value of this property. /// </remarks> public override double Indent { get { return 0.0; } } #endregion TextParagraphProperties Implementation /// <summary> /// Constructor. /// </summary> internal LineProperties( DependencyObject element, DependencyObject contentHost, TextProperties defaultTextProperties, MarkerProperties markerProperties) : this(element, contentHost, defaultTextProperties, markerProperties, (TextAlignment)element.GetValue(Block.TextAlignmentProperty)) { } /// <summary> /// Constructor. /// </summary> internal LineProperties( DependencyObject element, DependencyObject contentHost, TextProperties defaultTextProperties, MarkerProperties markerProperties, TextAlignment textAlignment) { _defaultTextProperties = defaultTextProperties; _markerProperties = (markerProperties != null) ? markerProperties.GetTextMarkerProperties(this) : null; _flowDirection = (FlowDirection)element.GetValue(Block.FlowDirectionProperty); _textAlignment = textAlignment; _lineHeight = (double)element.GetValue(Block.LineHeightProperty); _textIndent = (double)element.GetValue(Paragraph.TextIndentProperty); _lineStackingStrategy = (LineStackingStrategy)element.GetValue(Block.LineStackingStrategyProperty); _textWrapping = TextWrapping.Wrap; _textTrimming = TextTrimming.None; if (contentHost is TextBlock || contentHost is ITextBoxViewHost) { // NB: we intentially don't try to find the "PropertyOwner" of // a FlowDocument here. TextWrapping has a hard-coded // value SetValue'd when a FlowDocument is hosted by a TextBoxBase. _textWrapping = (TextWrapping)contentHost.GetValue(TextBlock.TextWrappingProperty); _textTrimming = (TextTrimming)contentHost.GetValue(TextBlock.TextTrimmingProperty); } else if (contentHost is FlowDocument) { _textWrapping = ((FlowDocument)contentHost).TextWrapping; } } /// <summary> /// Calculate line advance for TextParagraphs - this method has special casing in case the LineHeight property on the Paragraph element /// needs to be respected /// </summary> /// <param name="textParagraph"> /// TextParagraph that owns the line /// </param> /// <param name="dcp"> /// Dcp of the line /// </param> /// <param name="lineAdvance"> /// Calculated height of the line /// </param> internal double CalcLineAdvanceForTextParagraph(TextParagraph textParagraph, int dcp, double lineAdvance) { if (!DoubleUtil.IsNaN(_lineHeight)) { switch (LineStackingStrategy) { case LineStackingStrategy.BlockLineHeight: lineAdvance = _lineHeight; break; case LineStackingStrategy.MaxHeight: default: if (dcp == 0 && textParagraph.HasFiguresOrFloaters() && ((textParagraph.GetLastDcpAttachedObjectBeforeLine(0) + textParagraph.ParagraphStartCharacterPosition) == textParagraph.ParagraphEndCharacterPosition)) { // The Paragraph element contains only figures and floaters and has LineHeight set. In this case LineHeight // should be respected lineAdvance = _lineHeight; } else { lineAdvance = Math.Max(lineAdvance, _lineHeight); } break; // case LineStackingStrategy.InlineLineHeight: // // Inline uses the height of the line just processed. // break; // case LineStackingStrategy.GridHeight: // lineAdvance = (((TextDpi.ToTextDpi(lineAdvance) - 1) / TextDpi.ToTextDpi(_lineHeight)) + 1) * _lineHeight; // break; //} } } return lineAdvance; } /// <summary> /// Calculate line advance from actual line height and the line stacking strategy. /// </summary> internal double CalcLineAdvance(double lineAdvance) { // We support MaxHeight and BlockLineHeight stacking strategies if (!DoubleUtil.IsNaN(_lineHeight)) { switch (LineStackingStrategy) { case LineStackingStrategy.BlockLineHeight: lineAdvance = _lineHeight; break; case LineStackingStrategy.MaxHeight: default: lineAdvance = Math.Max(lineAdvance, _lineHeight); break; // case LineStackingStrategy.InlineLineHeight: // // Inline uses the height of the line just processed. // break; // case LineStackingStrategy.GridHeight: // lineAdvance = (((TextDpi.ToTextDpi(lineAdvance) - 1) / TextDpi.ToTextDpi(_lineHeight)) + 1) * _lineHeight; // break; //} } } return lineAdvance; } /// <summary> /// Raw TextAlignment, without considering IgnoreTextAlignment. /// </summary> internal TextAlignment TextAlignmentInternal { get { return _textAlignment; } } /// <summary> /// Ignore text alignment? /// </summary> internal bool IgnoreTextAlignment { get { return _ignoreTextAlignment; } set { _ignoreTextAlignment = value; } } ///// <summary> ///// Line stacking strategy. ///// </summary> internal LineStackingStrategy LineStackingStrategy { get { return _lineStackingStrategy; } } /// <summary> /// Text trimming. /// </summary> internal TextTrimming TextTrimming { get { return _textTrimming; } } /// <summary> /// Does it have first line specific properties? /// </summary> internal bool HasFirstLineProperties { get { return (_markerProperties != null || !DoubleUtil.IsZero(_textIndent)); } } /// <summary> /// Local cache for first line properties. /// </summary> internal TextParagraphProperties FirstLineProps { get { if (_firstLineProperties == null) { _firstLineProperties = new FirstLineProperties(this); } return _firstLineProperties; } } // ------------------------------------------------------------------ // Local cache for line properties with paragraph ellipsis. // ------------------------------------------------------------------ /// <summary> /// Local cache for line properties with paragraph ellipsis. /// </summary> internal TextParagraphProperties GetParaEllipsisLineProps(bool firstLine) { return new ParaEllipsisLineProperties(firstLine ? FirstLineProps : this); } private TextRunProperties _defaultTextProperties; // Line's default text properties. private TextMarkerProperties _markerProperties; // Marker properties private FirstLineProperties _firstLineProperties; // Local cache for first line properties. private bool _ignoreTextAlignment; // Ignore horizontal alignment? private FlowDirection _flowDirection; private TextAlignment _textAlignment; private TextWrapping _textWrapping; private TextTrimming _textTrimming; private double _lineHeight; private double _textIndent; private LineStackingStrategy _lineStackingStrategy; // ---------------------------------------------------------------------- // First text line properties provider. // ---------------------------------------------------------------------- private sealed class FirstLineProperties : TextParagraphProperties { // ------------------------------------------------------------------ // // TextParagraphProperties Implementation // // ------------------------------------------------------------------ #region TextParagraphProperties Implementation // ------------------------------------------------------------------ // Text flow direction (text advance + block advance direction). // ------------------------------------------------------------------ public override FlowDirection FlowDirection { get { return _lp.FlowDirection; } } // ------------------------------------------------------------------ // Alignment of the line's content. // ------------------------------------------------------------------ public override TextAlignment TextAlignment { get { return _lp.TextAlignment; } } // ------------------------------------------------------------------ // Line's height. // ------------------------------------------------------------------ public override double LineHeight { get { return _lp.LineHeight; } } // ------------------------------------------------------------------ // An instance of this class is always the first line in a paragraph. // ------------------------------------------------------------------ public override bool FirstLineInParagraph { get { return true; } } // ------------------------------------------------------------------ // Line's default text properties. // ------------------------------------------------------------------ public override TextRunProperties DefaultTextRunProperties { get { return _lp.DefaultTextRunProperties; } } // ------------------------------------------------------------------ // Line's text decorations (in addition to any run-level text decorations). // ------------------------------------------------------------------ public override TextDecorationCollection TextDecorations { get { return _lp.TextDecorations; } } // ------------------------------------------------------------------ // Text wrap control. // ------------------------------------------------------------------ public override TextWrapping TextWrapping { get { return _lp.TextWrapping; } } // ------------------------------------------------------------------ // Marker characteristics of the first line in paragraph. // ------------------------------------------------------------------ public override TextMarkerProperties TextMarkerProperties { get { return _lp.TextMarkerProperties; } } // ------------------------------------------------------------------ // Line indentation. // ------------------------------------------------------------------ public override double Indent { get { return _lp._textIndent; } } #endregion TextParagraphProperties Implementation // ------------------------------------------------------------------ // Constructor. // ------------------------------------------------------------------ internal FirstLineProperties(LineProperties lp) { _lp = lp; // properly set the local copy of hyphenator accordingly. Hyphenator = lp.Hyphenator; } // ------------------------------------------------------------------ // LineProperties object reference. // ------------------------------------------------------------------ private LineProperties _lp; } // ---------------------------------------------------------------------- // Line properties provider for line with paragraph ellipsis. // ---------------------------------------------------------------------- private sealed class ParaEllipsisLineProperties : TextParagraphProperties { // ------------------------------------------------------------------ // // TextParagraphProperties Implementation // // ------------------------------------------------------------------ #region TextParagraphProperties Implementation // ------------------------------------------------------------------ // Text flow direction (text advance + block advance direction). // ------------------------------------------------------------------ public override FlowDirection FlowDirection { get { return _lp.FlowDirection; } } // ------------------------------------------------------------------ // Alignment of the line's content. // ------------------------------------------------------------------ public override TextAlignment TextAlignment { get { return _lp.TextAlignment; } } // ------------------------------------------------------------------ // Line's height. // ------------------------------------------------------------------ public override double LineHeight { get { return _lp.LineHeight; } } // ------------------------------------------------------------------ // First line in paragraph option. // ------------------------------------------------------------------ public override bool FirstLineInParagraph { get { return _lp.FirstLineInParagraph; } } // ------------------------------------------------------------------ // Always collapsible option. // ------------------------------------------------------------------ public override bool AlwaysCollapsible { get { return _lp.AlwaysCollapsible; } } // ------------------------------------------------------------------ // Line's default text properties. // ------------------------------------------------------------------ public override TextRunProperties DefaultTextRunProperties { get { return _lp.DefaultTextRunProperties; } } // ------------------------------------------------------------------ // Line's text decorations (in addition to any run-level text decorations). // ------------------------------------------------------------------ public override TextDecorationCollection TextDecorations { get { return _lp.TextDecorations; } } // ------------------------------------------------------------------ // Text wrap control. // If paragraph ellipsis are enabled, force this line not to wrap. // ------------------------------------------------------------------ public override TextWrapping TextWrapping { get { return TextWrapping.NoWrap; } } // ------------------------------------------------------------------ // Marker characteristics of the first line in paragraph. // ------------------------------------------------------------------ public override TextMarkerProperties TextMarkerProperties { get { return _lp.TextMarkerProperties; } } // ------------------------------------------------------------------ // Line indentation. // ------------------------------------------------------------------ public override double Indent { get { return _lp.Indent; } } #endregion TextParagraphProperties Implementation // ------------------------------------------------------------------ // Constructor. // ------------------------------------------------------------------ internal ParaEllipsisLineProperties(TextParagraphProperties lp) { _lp = lp; } // ------------------------------------------------------------------ // LineProperties object reference. // ------------------------------------------------------------------ private TextParagraphProperties _lp; } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Apache.Ignite.Core { using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Xml; using System.Xml.Serialization; using Apache.Ignite.Core.Binary; using Apache.Ignite.Core.Cache; using Apache.Ignite.Core.Cache.Configuration; using Apache.Ignite.Core.Cluster; using Apache.Ignite.Core.Common; using Apache.Ignite.Core.Communication; using Apache.Ignite.Core.Communication.Tcp; using Apache.Ignite.Core.Compute; using Apache.Ignite.Core.Configuration; using Apache.Ignite.Core.DataStructures.Configuration; using Apache.Ignite.Core.Deployment; using Apache.Ignite.Core.Discovery; using Apache.Ignite.Core.Discovery.Tcp; using Apache.Ignite.Core.Events; using Apache.Ignite.Core.Impl; using Apache.Ignite.Core.Impl.Binary; using Apache.Ignite.Core.Impl.Common; using Apache.Ignite.Core.Lifecycle; using Apache.Ignite.Core.Log; using Apache.Ignite.Core.PersistentStore; using Apache.Ignite.Core.Plugin; using Apache.Ignite.Core.Transactions; using BinaryReader = Apache.Ignite.Core.Impl.Binary.BinaryReader; using BinaryWriter = Apache.Ignite.Core.Impl.Binary.BinaryWriter; /// <summary> /// Grid configuration. /// </summary> public class IgniteConfiguration { /// <summary> /// Default initial JVM memory in megabytes. /// </summary> public const int DefaultJvmInitMem = -1; /// <summary> /// Default maximum JVM memory in megabytes. /// </summary> public const int DefaultJvmMaxMem = -1; /// <summary> /// Default metrics expire time. /// </summary> public static readonly TimeSpan DefaultMetricsExpireTime = TimeSpan.MaxValue; /// <summary> /// Default metrics history size. /// </summary> public const int DefaultMetricsHistorySize = 10000; /// <summary> /// Default metrics log frequency. /// </summary> public static readonly TimeSpan DefaultMetricsLogFrequency = TimeSpan.FromMilliseconds(60000); /// <summary> /// Default metrics update frequency. /// </summary> public static readonly TimeSpan DefaultMetricsUpdateFrequency = TimeSpan.FromMilliseconds(2000); /// <summary> /// Default network timeout. /// </summary> public static readonly TimeSpan DefaultNetworkTimeout = TimeSpan.FromMilliseconds(5000); /// <summary> /// Default network retry delay. /// </summary> public static readonly TimeSpan DefaultNetworkSendRetryDelay = TimeSpan.FromMilliseconds(1000); /// <summary> /// Default failure detection timeout. /// </summary> public static readonly TimeSpan DefaultFailureDetectionTimeout = TimeSpan.FromSeconds(10); /// <summary> /// Default failure detection timeout. /// </summary> public static readonly TimeSpan DefaultClientFailureDetectionTimeout = TimeSpan.FromSeconds(30); /// <summary> /// Default thread pool size. /// </summary> public static readonly int DefaultThreadPoolSize = Math.Max(8, Environment.ProcessorCount); /// <summary> /// Default management thread pool size. /// </summary> public const int DefaultManagementThreadPoolSize = 4; /// <summary> /// Default timeout after which long query warning will be printed. /// </summary> public static readonly TimeSpan DefaultLongQueryWarningTimeout = TimeSpan.FromMilliseconds(3000); /// <summary> /// Default value for <see cref="ClientConnectorConfigurationEnabled"/>. /// </summary> public const bool DefaultClientConnectorConfigurationEnabled = true; /** */ private TimeSpan? _metricsExpireTime; /** */ private int? _metricsHistorySize; /** */ private TimeSpan? _metricsLogFrequency; /** */ private TimeSpan? _metricsUpdateFrequency; /** */ private int? _networkSendRetryCount; /** */ private TimeSpan? _networkSendRetryDelay; /** */ private TimeSpan? _networkTimeout; /** */ private bool? _isDaemon; /** */ private bool? _clientMode; /** */ private TimeSpan? _failureDetectionTimeout; /** */ private TimeSpan? _clientFailureDetectionTimeout; /** */ private int? _publicThreadPoolSize; /** */ private int? _stripedThreadPoolSize; /** */ private int? _serviceThreadPoolSize; /** */ private int? _systemThreadPoolSize; /** */ private int? _asyncCallbackThreadPoolSize; /** */ private int? _managementThreadPoolSize; /** */ private int? _dataStreamerThreadPoolSize; /** */ private int? _utilityCacheThreadPoolSize; /** */ private int? _queryThreadPoolSize; /** */ private TimeSpan? _longQueryWarningTimeout; /** */ private bool? _isActiveOnStart; /** Local event listeners. Stored as array to ensure index access. */ private LocalEventListener[] _localEventListenersInternal; /** Map from user-defined listener to it's id. */ private Dictionary<object, int> _localEventListenerIds; /// <summary> /// Default network retry count. /// </summary> public const int DefaultNetworkSendRetryCount = 3; /// <summary> /// Default late affinity assignment mode. /// </summary> public const bool DefaultIsLateAffinityAssignment = true; /// <summary> /// Default value for <see cref="IsActiveOnStart"/> property. /// </summary> public const bool DefaultIsActiveOnStart = true; /// <summary> /// Default value for <see cref="RedirectJavaConsoleOutput"/> property. /// </summary> public const bool DefaultRedirectJavaConsoleOutput = true; /// <summary> /// Initializes a new instance of the <see cref="IgniteConfiguration"/> class. /// </summary> public IgniteConfiguration() { JvmInitialMemoryMb = DefaultJvmInitMem; JvmMaxMemoryMb = DefaultJvmMaxMem; ClientConnectorConfigurationEnabled = DefaultClientConnectorConfigurationEnabled; RedirectJavaConsoleOutput = DefaultRedirectJavaConsoleOutput; } /// <summary> /// Initializes a new instance of the <see cref="IgniteConfiguration"/> class. /// </summary> /// <param name="configuration">The configuration to copy.</param> public IgniteConfiguration(IgniteConfiguration configuration) { IgniteArgumentCheck.NotNull(configuration, "configuration"); using (var stream = IgniteManager.Memory.Allocate().GetStream()) { var marsh = BinaryUtils.Marshaller; configuration.Write(marsh.StartMarshal(stream)); stream.SynchronizeOutput(); stream.Seek(0, SeekOrigin.Begin); ReadCore(marsh.StartUnmarshal(stream)); } CopyLocalProperties(configuration); } /// <summary> /// Initializes a new instance of the <see cref="IgniteConfiguration" /> class from a reader. /// </summary> /// <param name="binaryReader">The binary reader.</param> /// <param name="baseConfig">The base configuration.</param> internal IgniteConfiguration(BinaryReader binaryReader, IgniteConfiguration baseConfig) { Debug.Assert(binaryReader != null); Debug.Assert(baseConfig != null); Read(binaryReader); CopyLocalProperties(baseConfig); } /// <summary> /// Writes this instance to a writer. /// </summary> /// <param name="writer">The writer.</param> internal void Write(BinaryWriter writer) { Debug.Assert(writer != null); // Simple properties writer.WriteBooleanNullable(_clientMode); writer.WriteIntArray(IncludedEventTypes == null ? null : IncludedEventTypes.ToArray()); writer.WriteTimeSpanAsLongNullable(_metricsExpireTime); writer.WriteIntNullable(_metricsHistorySize); writer.WriteTimeSpanAsLongNullable(_metricsLogFrequency); writer.WriteTimeSpanAsLongNullable(_metricsUpdateFrequency); writer.WriteIntNullable(_networkSendRetryCount); writer.WriteTimeSpanAsLongNullable(_networkSendRetryDelay); writer.WriteTimeSpanAsLongNullable(_networkTimeout); writer.WriteString(WorkDirectory); writer.WriteString(Localhost); writer.WriteBooleanNullable(_isDaemon); writer.WriteTimeSpanAsLongNullable(_failureDetectionTimeout); writer.WriteTimeSpanAsLongNullable(_clientFailureDetectionTimeout); writer.WriteTimeSpanAsLongNullable(_longQueryWarningTimeout); writer.WriteBooleanNullable(_isActiveOnStart); writer.WriteObjectDetached(ConsistentId); // Thread pools writer.WriteIntNullable(_publicThreadPoolSize); writer.WriteIntNullable(_stripedThreadPoolSize); writer.WriteIntNullable(_serviceThreadPoolSize); writer.WriteIntNullable(_systemThreadPoolSize); writer.WriteIntNullable(_asyncCallbackThreadPoolSize); writer.WriteIntNullable(_managementThreadPoolSize); writer.WriteIntNullable(_dataStreamerThreadPoolSize); writer.WriteIntNullable(_utilityCacheThreadPoolSize); writer.WriteIntNullable(_queryThreadPoolSize); // Cache config writer.WriteCollectionRaw(CacheConfiguration); // Discovery config var disco = DiscoverySpi; if (disco != null) { writer.WriteBoolean(true); var tcpDisco = disco as TcpDiscoverySpi; if (tcpDisco == null) throw new InvalidOperationException("Unsupported discovery SPI: " + disco.GetType()); tcpDisco.Write(writer); } else writer.WriteBoolean(false); // Communication config var comm = CommunicationSpi; if (comm != null) { writer.WriteBoolean(true); var tcpComm = comm as TcpCommunicationSpi; if (tcpComm == null) throw new InvalidOperationException("Unsupported communication SPI: " + comm.GetType()); tcpComm.Write(writer); } else writer.WriteBoolean(false); // Binary config if (BinaryConfiguration != null) { writer.WriteBoolean(true); if (BinaryConfiguration.CompactFooterInternal != null) { writer.WriteBoolean(true); writer.WriteBoolean(BinaryConfiguration.CompactFooter); } else { writer.WriteBoolean(false); } // Name mapper. var mapper = BinaryConfiguration.NameMapper as BinaryBasicNameMapper; writer.WriteBoolean(mapper != null && mapper.IsSimpleName); } else { writer.WriteBoolean(false); } // User attributes var attrs = UserAttributes; if (attrs == null) writer.WriteInt(0); else { writer.WriteInt(attrs.Count); foreach (var pair in attrs) { writer.WriteString(pair.Key); writer.Write(pair.Value); } } // Atomic if (AtomicConfiguration != null) { writer.WriteBoolean(true); writer.WriteInt(AtomicConfiguration.AtomicSequenceReserveSize); writer.WriteInt(AtomicConfiguration.Backups); writer.WriteInt((int) AtomicConfiguration.CacheMode); } else writer.WriteBoolean(false); // Tx if (TransactionConfiguration != null) { writer.WriteBoolean(true); writer.WriteInt(TransactionConfiguration.PessimisticTransactionLogSize); writer.WriteInt((int) TransactionConfiguration.DefaultTransactionConcurrency); writer.WriteInt((int) TransactionConfiguration.DefaultTransactionIsolation); writer.WriteLong((long) TransactionConfiguration.DefaultTimeout.TotalMilliseconds); writer.WriteInt((int) TransactionConfiguration.PessimisticTransactionLogLinger.TotalMilliseconds); } else writer.WriteBoolean(false); // Event storage if (EventStorageSpi == null) { writer.WriteByte(0); } else if (EventStorageSpi is NoopEventStorageSpi) { writer.WriteByte(1); } else { var memEventStorage = EventStorageSpi as MemoryEventStorageSpi; if (memEventStorage == null) { throw new IgniteException(string.Format( "Unsupported IgniteConfiguration.EventStorageSpi: '{0}'. " + "Supported implementations: '{1}', '{2}'.", EventStorageSpi.GetType(), typeof(NoopEventStorageSpi), typeof(MemoryEventStorageSpi))); } writer.WriteByte(2); memEventStorage.Write(writer); } #pragma warning disable 618 // Obsolete if (MemoryConfiguration != null) { writer.WriteBoolean(true); MemoryConfiguration.Write(writer); } else { writer.WriteBoolean(false); } #pragma warning restore 618 // SQL connector. #pragma warning disable 618 // Obsolete if (SqlConnectorConfiguration != null) { writer.WriteBoolean(true); SqlConnectorConfiguration.Write(writer); } #pragma warning restore 618 else { writer.WriteBoolean(false); } // Client connector. if (ClientConnectorConfiguration != null) { writer.WriteBoolean(true); ClientConnectorConfiguration.Write(writer); } else { writer.WriteBoolean(false); } writer.WriteBoolean(ClientConnectorConfigurationEnabled); // Persistence. #pragma warning disable 618 // Obsolete if (PersistentStoreConfiguration != null) { writer.WriteBoolean(true); PersistentStoreConfiguration.Write(writer); } else { writer.WriteBoolean(false); } #pragma warning restore 618 // Data storage. if (DataStorageConfiguration != null) { writer.WriteBoolean(true); DataStorageConfiguration.Write(writer); } else { writer.WriteBoolean(false); } // Plugins (should be last). if (PluginConfigurations != null) { var pos = writer.Stream.Position; writer.WriteInt(0); // reserve count var cnt = 0; foreach (var cfg in PluginConfigurations) { if (cfg.PluginConfigurationClosureFactoryId != null) { writer.WriteInt(cfg.PluginConfigurationClosureFactoryId.Value); cfg.WriteBinary(writer); cnt++; } } writer.Stream.WriteInt(pos, cnt); } else { writer.WriteInt(0); } // Local event listeners (should be last). if (LocalEventListeners != null) { writer.WriteInt(LocalEventListeners.Count); foreach (var listener in LocalEventListeners) { ValidateLocalEventListener(listener); writer.WriteIntArray(listener.EventTypes.ToArray()); } } else { writer.WriteInt(0); } } /// <summary> /// Validates the local event listener. /// </summary> // ReSharper disable once ParameterOnlyUsedForPreconditionCheck.Local // ReSharper disable once UnusedParameter.Local private static void ValidateLocalEventListener(LocalEventListener listener) { if (listener == null) { throw new IgniteException("LocalEventListeners can't contain nulls."); } if (listener.ListenerObject == null) { throw new IgniteException("LocalEventListener.Listener can't be null."); } if (listener.EventTypes == null || listener.EventTypes.Count == 0) { throw new IgniteException("LocalEventListener.EventTypes can't be null or empty."); } } /// <summary> /// Validates this instance and outputs information to the log, if necessary. /// </summary> internal void Validate(ILogger log) { Debug.Assert(log != null); var ccfg = CacheConfiguration; if (ccfg != null) { foreach (var cfg in ccfg) cfg.Validate(log); } } /// <summary> /// Reads data from specified reader into current instance. /// </summary> /// <param name="r">The binary reader.</param> private void ReadCore(BinaryReader r) { // Simple properties _clientMode = r.ReadBooleanNullable(); IncludedEventTypes = r.ReadIntArray(); _metricsExpireTime = r.ReadTimeSpanNullable(); _metricsHistorySize = r.ReadIntNullable(); _metricsLogFrequency = r.ReadTimeSpanNullable(); _metricsUpdateFrequency = r.ReadTimeSpanNullable(); _networkSendRetryCount = r.ReadIntNullable(); _networkSendRetryDelay = r.ReadTimeSpanNullable(); _networkTimeout = r.ReadTimeSpanNullable(); WorkDirectory = r.ReadString(); Localhost = r.ReadString(); _isDaemon = r.ReadBooleanNullable(); _failureDetectionTimeout = r.ReadTimeSpanNullable(); _clientFailureDetectionTimeout = r.ReadTimeSpanNullable(); _longQueryWarningTimeout = r.ReadTimeSpanNullable(); _isActiveOnStart = r.ReadBooleanNullable(); ConsistentId = r.ReadObject<object>(); // Thread pools _publicThreadPoolSize = r.ReadIntNullable(); _stripedThreadPoolSize = r.ReadIntNullable(); _serviceThreadPoolSize = r.ReadIntNullable(); _systemThreadPoolSize = r.ReadIntNullable(); _asyncCallbackThreadPoolSize = r.ReadIntNullable(); _managementThreadPoolSize = r.ReadIntNullable(); _dataStreamerThreadPoolSize = r.ReadIntNullable(); _utilityCacheThreadPoolSize = r.ReadIntNullable(); _queryThreadPoolSize = r.ReadIntNullable(); // Cache config CacheConfiguration = r.ReadCollectionRaw(x => new CacheConfiguration(x)); // Discovery config DiscoverySpi = r.ReadBoolean() ? new TcpDiscoverySpi(r) : null; // Communication config CommunicationSpi = r.ReadBoolean() ? new TcpCommunicationSpi(r) : null; // Binary config if (r.ReadBoolean()) { BinaryConfiguration = BinaryConfiguration ?? new BinaryConfiguration(); if (r.ReadBoolean()) { BinaryConfiguration.CompactFooter = r.ReadBoolean(); } if (r.ReadBoolean()) { BinaryConfiguration.NameMapper = BinaryBasicNameMapper.SimpleNameInstance; } } // User attributes UserAttributes = Enumerable.Range(0, r.ReadInt()) .ToDictionary(x => r.ReadString(), x => r.ReadObject<object>()); // Atomic if (r.ReadBoolean()) { AtomicConfiguration = new AtomicConfiguration { AtomicSequenceReserveSize = r.ReadInt(), Backups = r.ReadInt(), CacheMode = (CacheMode) r.ReadInt() }; } // Tx if (r.ReadBoolean()) { TransactionConfiguration = new TransactionConfiguration { PessimisticTransactionLogSize = r.ReadInt(), DefaultTransactionConcurrency = (TransactionConcurrency) r.ReadInt(), DefaultTransactionIsolation = (TransactionIsolation) r.ReadInt(), DefaultTimeout = TimeSpan.FromMilliseconds(r.ReadLong()), PessimisticTransactionLogLinger = TimeSpan.FromMilliseconds(r.ReadInt()) }; } // Event storage switch (r.ReadByte()) { case 1: EventStorageSpi = new NoopEventStorageSpi(); break; case 2: EventStorageSpi = MemoryEventStorageSpi.Read(r); break; } if (r.ReadBoolean()) { #pragma warning disable 618 // Obsolete MemoryConfiguration = new MemoryConfiguration(r); #pragma warning restore 618 // Obsolete } // SQL. if (r.ReadBoolean()) { #pragma warning disable 618 // Obsolete SqlConnectorConfiguration = new SqlConnectorConfiguration(r); #pragma warning restore 618 } // Client. if (r.ReadBoolean()) { ClientConnectorConfiguration = new ClientConnectorConfiguration(r); } ClientConnectorConfigurationEnabled = r.ReadBoolean(); // Persistence. if (r.ReadBoolean()) { #pragma warning disable 618 // Obsolete PersistentStoreConfiguration = new PersistentStoreConfiguration(r); #pragma warning restore 618 } // Data storage. if (r.ReadBoolean()) { DataStorageConfiguration = new DataStorageConfiguration(r); } } /// <summary> /// Reads data from specified reader into current instance. /// </summary> /// <param name="binaryReader">The binary reader.</param> private void Read(BinaryReader binaryReader) { ReadCore(binaryReader); // Misc IgniteHome = binaryReader.ReadString(); JvmInitialMemoryMb = (int) (binaryReader.ReadLong()/1024/2014); JvmMaxMemoryMb = (int) (binaryReader.ReadLong()/1024/2014); } /// <summary> /// Copies the local properties (properties that are not written in Write method). /// </summary> private void CopyLocalProperties(IgniteConfiguration cfg) { IgniteInstanceName = cfg.IgniteInstanceName; if (BinaryConfiguration != null && cfg.BinaryConfiguration != null) { BinaryConfiguration.CopyLocalProperties(cfg.BinaryConfiguration); } SpringConfigUrl = cfg.SpringConfigUrl; IgniteHome = cfg.IgniteHome; JvmClasspath = cfg.JvmClasspath; JvmOptions = cfg.JvmOptions; JvmDllPath = cfg.JvmDllPath; Assemblies = cfg.Assemblies; SuppressWarnings = cfg.SuppressWarnings; LifecycleHandlers = cfg.LifecycleHandlers; Logger = cfg.Logger; JvmInitialMemoryMb = cfg.JvmInitialMemoryMb; JvmMaxMemoryMb = cfg.JvmMaxMemoryMb; PluginConfigurations = cfg.PluginConfigurations; AutoGenerateIgniteInstanceName = cfg.AutoGenerateIgniteInstanceName; PeerAssemblyLoadingMode = cfg.PeerAssemblyLoadingMode; LocalEventListeners = cfg.LocalEventListeners; RedirectJavaConsoleOutput = cfg.RedirectJavaConsoleOutput; if (CacheConfiguration != null && cfg.CacheConfiguration != null) { var caches = cfg.CacheConfiguration.Where(x => x != null).ToDictionary(x => "_" + x.Name, x => x); foreach (var cache in CacheConfiguration) { CacheConfiguration src; if (cache != null && caches.TryGetValue("_" + cache.Name, out src)) { cache.CopyLocalProperties(src); } } } } /// <summary> /// Gets or sets optional local instance name. /// <para /> /// This name only works locally and has no effect on topology. /// <para /> /// This property is used to when there are multiple Ignite nodes in one process to distinguish them. /// </summary> public string IgniteInstanceName { get; set; } /// <summary> /// Gets or sets a value indicating whether unique <see cref="IgniteInstanceName"/> should be generated. /// <para /> /// Set this to true in scenarios where new node should be started regardless of other nodes present within /// current process. In particular, this setting is useful is ASP.NET and IIS environments, where AppDomains /// are loaded and unloaded within a single process during application restarts. Ignite stops all nodes /// on <see cref="AppDomain"/> unload, however, IIS does not wait for previous AppDomain to unload before /// starting up a new one, which may cause "Ignite instance with this name has already been started" errors. /// This setting solves the issue. /// </summary> public bool AutoGenerateIgniteInstanceName { get; set; } /// <summary> /// Gets or sets optional local instance name. /// <para /> /// This name only works locally and has no effect on topology. /// <para /> /// This property is used to when there are multiple Ignite nodes in one process to distinguish them. /// </summary> [Obsolete("Use IgniteInstanceName instead.")] [XmlIgnore] public string GridName { get { return IgniteInstanceName; } set { IgniteInstanceName = value; } } /// <summary> /// Gets or sets the binary configuration. /// </summary> /// <value> /// The binary configuration. /// </value> public BinaryConfiguration BinaryConfiguration { get; set; } /// <summary> /// Gets or sets the cache configuration. /// </summary> /// <value> /// The cache configuration. /// </value> [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public ICollection<CacheConfiguration> CacheConfiguration { get; set; } /// <summary> /// URL to Spring configuration file. /// <para /> /// Spring configuration is loaded first, then <see cref="IgniteConfiguration"/> properties are applied. /// Null property values do not override Spring values. /// Value-typed properties are tracked internally: if setter was not called, Spring value won't be overwritten. /// <para /> /// This merging happens on the top level only; e. g. if there are cache configurations defined in Spring /// and in .NET, .NET caches will overwrite Spring caches. /// </summary> [SuppressMessage("Microsoft.Design", "CA1056:UriPropertiesShouldNotBeStrings")] public string SpringConfigUrl { get; set; } /// <summary> /// Path to jvm.dll (libjvm.so on Linux, libjvm.dylib on Mac) file. /// If not set, it's location will be determined using JAVA_HOME environment variable. /// If path is neither set nor determined automatically, an exception will be thrown. /// </summary> public string JvmDllPath { get; set; } /// <summary> /// Path to Ignite home. If not set environment variable IGNITE_HOME will be used. /// </summary> public string IgniteHome { get; set; } /// <summary> /// Classpath used by JVM on Ignite start. /// </summary> public string JvmClasspath { get; set; } /// <summary> /// Collection of options passed to JVM on Ignite start. /// </summary> [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public ICollection<string> JvmOptions { get; set; } /// <summary> /// List of additional .Net assemblies to load on Ignite start. Each item can be either /// fully qualified assembly name, path to assembly to DLL or path to a directory when /// assemblies reside. /// </summary> [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public ICollection<string> Assemblies { get; set; } /// <summary> /// Whether to suppress warnings. /// </summary> public bool SuppressWarnings { get; set; } /// <summary> /// Lifecycle handlers. /// </summary> [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public ICollection<ILifecycleHandler> LifecycleHandlers { get; set; } /// <summary> /// Initial amount of memory in megabytes given to JVM. Maps to -Xms Java option. /// <code>-1</code> maps to JVM defaults. /// Defaults to <see cref="DefaultJvmInitMem"/>. /// </summary> [DefaultValue(DefaultJvmInitMem)] public int JvmInitialMemoryMb { get; set; } /// <summary> /// Maximum amount of memory in megabytes given to JVM. Maps to -Xmx Java option. /// <code>-1</code> maps to JVM defaults. /// Defaults to <see cref="DefaultJvmMaxMem"/>. /// </summary> [DefaultValue(DefaultJvmMaxMem)] public int JvmMaxMemoryMb { get; set; } /// <summary> /// Gets or sets the discovery service provider. /// Null for default discovery. /// </summary> public IDiscoverySpi DiscoverySpi { get; set; } /// <summary> /// Gets or sets the communication service provider. /// Null for default communication. /// </summary> public ICommunicationSpi CommunicationSpi { get; set; } /// <summary> /// Gets or sets a value indicating whether node should start in client mode. /// Client node cannot hold data in the caches. /// </summary> public bool ClientMode { get { return _clientMode ?? default(bool); } set { _clientMode = value; } } /// <summary> /// Gets or sets a set of event types (<see cref="EventType" />) to be recorded by Ignite. /// </summary> [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public ICollection<int> IncludedEventTypes { get; set; } /// <summary> /// Gets or sets pre-configured local event listeners. /// <para /> /// This is similar to calling <see cref="IEvents.LocalListen{T}(IEventListener{T},int[])"/>, /// but important difference is that some events occur during startup and can be only received this way. /// </summary> [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public ICollection<LocalEventListener> LocalEventListeners { get; set; } /// <summary> /// Initializes the local event listeners collections. /// </summary> private void InitLocalEventListeners() { if (LocalEventListeners != null && _localEventListenersInternal == null) { _localEventListenersInternal = LocalEventListeners.ToArray(); _localEventListenerIds = new Dictionary<object, int>(); for (var i = 0; i < _localEventListenersInternal.Length; i++) { var listener = _localEventListenersInternal[i]; ValidateLocalEventListener(listener); _localEventListenerIds[listener.ListenerObject] = i; } } } /// <summary> /// Gets the local event listeners. /// </summary> internal LocalEventListener[] LocalEventListenersInternal { get { InitLocalEventListeners(); return _localEventListenersInternal; } } /// <summary> /// Gets the local event listener ids. /// </summary> internal Dictionary<object, int> LocalEventListenerIds { get { InitLocalEventListeners(); return _localEventListenerIds; } } /// <summary> /// Gets or sets the time after which a certain metric value is considered expired. /// </summary> [DefaultValue(typeof(TimeSpan), "10675199.02:48:05.4775807")] public TimeSpan MetricsExpireTime { get { return _metricsExpireTime ?? DefaultMetricsExpireTime; } set { _metricsExpireTime = value; } } /// <summary> /// Gets or sets the number of metrics kept in history to compute totals and averages. /// </summary> [DefaultValue(DefaultMetricsHistorySize)] public int MetricsHistorySize { get { return _metricsHistorySize ?? DefaultMetricsHistorySize; } set { _metricsHistorySize = value; } } /// <summary> /// Gets or sets the frequency of metrics log print out. /// <see cref="TimeSpan.Zero"/> to disable metrics print out. /// </summary> [DefaultValue(typeof(TimeSpan), "00:01:00")] public TimeSpan MetricsLogFrequency { get { return _metricsLogFrequency ?? DefaultMetricsLogFrequency; } set { _metricsLogFrequency = value; } } /// <summary> /// Gets or sets the job metrics update frequency. /// <see cref="TimeSpan.Zero"/> to update metrics on job start/finish. /// Negative value to never update metrics. /// </summary> [DefaultValue(typeof(TimeSpan), "00:00:02")] public TimeSpan MetricsUpdateFrequency { get { return _metricsUpdateFrequency ?? DefaultMetricsUpdateFrequency; } set { _metricsUpdateFrequency = value; } } /// <summary> /// Gets or sets the network send retry count. /// </summary> [DefaultValue(DefaultNetworkSendRetryCount)] public int NetworkSendRetryCount { get { return _networkSendRetryCount ?? DefaultNetworkSendRetryCount; } set { _networkSendRetryCount = value; } } /// <summary> /// Gets or sets the network send retry delay. /// </summary> [DefaultValue(typeof(TimeSpan), "00:00:01")] public TimeSpan NetworkSendRetryDelay { get { return _networkSendRetryDelay ?? DefaultNetworkSendRetryDelay; } set { _networkSendRetryDelay = value; } } /// <summary> /// Gets or sets the network timeout. /// </summary> [DefaultValue(typeof(TimeSpan), "00:00:05")] public TimeSpan NetworkTimeout { get { return _networkTimeout ?? DefaultNetworkTimeout; } set { _networkTimeout = value; } } /// <summary> /// Gets or sets the work directory. /// If not provided, a folder under <see cref="IgniteHome"/> will be used. /// </summary> public string WorkDirectory { get; set; } /// <summary> /// Gets or sets system-wide local address or host for all Ignite components to bind to. /// If provided it will override all default local bind settings within Ignite. /// <para /> /// If <c>null</c> then Ignite tries to use local wildcard address.That means that all services /// will be available on all network interfaces of the host machine. /// <para /> /// It is strongly recommended to set this parameter for all production environments. /// </summary> public string Localhost { get; set; } /// <summary> /// Gets or sets a value indicating whether this node should be a daemon node. /// <para /> /// Daemon nodes are the usual grid nodes that participate in topology but not visible on the main APIs, /// i.e. they are not part of any cluster groups. /// <para /> /// Daemon nodes are used primarily for management and monitoring functionality that is built on Ignite /// and needs to participate in the topology, but also needs to be excluded from the "normal" topology, /// so that it won't participate in the task execution or in-memory data grid storage. /// </summary> public bool IsDaemon { get { return _isDaemon ?? default(bool); } set { _isDaemon = value; } } /// <summary> /// Gets or sets the user attributes for this node. /// <para /> /// These attributes can be retrieved later via <see cref="IClusterNode.GetAttributes"/>. /// Environment variables are added to node attributes automatically. /// NOTE: attribute names starting with "org.apache.ignite" are reserved for internal use. /// </summary> [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public IDictionary<string, object> UserAttributes { get; set; } /// <summary> /// Gets or sets the atomic data structures configuration. /// </summary> public AtomicConfiguration AtomicConfiguration { get; set; } /// <summary> /// Gets or sets the transaction configuration. /// </summary> public TransactionConfiguration TransactionConfiguration { get; set; } /// <summary> /// Gets or sets a value indicating whether late affinity assignment mode should be used. /// <para /> /// On each topology change, for each started cache, partition-to-node mapping is /// calculated using AffinityFunction for cache. When late /// affinity assignment mode is disabled then new affinity mapping is applied immediately. /// <para /> /// With late affinity assignment mode, if primary node was changed for some partition, but data for this /// partition is not rebalanced yet on this node, then current primary is not changed and new primary /// is temporary assigned as backup. This nodes becomes primary only when rebalancing for all assigned primary /// partitions is finished. This mode can show better performance for cache operations, since when cache /// primary node executes some operation and data is not rebalanced yet, then it sends additional message /// to force rebalancing from other nodes. /// <para /> /// Note, that <see cref="ICacheAffinity"/> interface provides assignment information taking late assignment /// into account, so while rebalancing for new primary nodes is not finished it can return assignment /// which differs from assignment calculated by AffinityFunction. /// <para /> /// This property should have the same value for all nodes in cluster. /// <para /> /// If not provided, default value is <see cref="DefaultIsLateAffinityAssignment"/>. /// </summary> [SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic")] [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "value")] [DefaultValue(DefaultIsLateAffinityAssignment)] [Obsolete("No longer supported, always true.")] public bool IsLateAffinityAssignment { get { return DefaultIsLateAffinityAssignment; } // ReSharper disable once ValueParameterNotUsed set { /* No-op. */ } } /// <summary> /// Serializes this instance to the specified XML writer. /// </summary> /// <param name="writer">The writer.</param> /// <param name="rootElementName">Name of the root element.</param> public void ToXml(XmlWriter writer, string rootElementName) { IgniteConfigurationXmlSerializer.Serialize(this, writer, rootElementName); } /// <summary> /// Serializes this instance to an XML string. /// </summary> public string ToXml() { return IgniteConfigurationXmlSerializer.Serialize(this, "igniteConfiguration"); } /// <summary> /// Deserializes IgniteConfiguration from the XML reader. /// </summary> /// <param name="reader">The reader.</param> /// <returns>Deserialized instance.</returns> public static IgniteConfiguration FromXml(XmlReader reader) { return IgniteConfigurationXmlSerializer.Deserialize<IgniteConfiguration>(reader); } /// <summary> /// Deserializes IgniteConfiguration from the XML string. /// </summary> /// <param name="xml">Xml string.</param> /// <returns>Deserialized instance.</returns> public static IgniteConfiguration FromXml(string xml) { return IgniteConfigurationXmlSerializer.Deserialize<IgniteConfiguration>(xml); } /// <summary> /// Gets or sets the logger. /// <para /> /// If no logger is set, logging is delegated to Java, which uses the logger defined in Spring XML (if present) /// or logs to console otherwise. /// </summary> public ILogger Logger { get; set; } /// <summary> /// Gets or sets the failure detection timeout used by <see cref="TcpDiscoverySpi"/> /// and <see cref="TcpCommunicationSpi"/>. /// </summary> [DefaultValue(typeof(TimeSpan), "00:00:10")] public TimeSpan FailureDetectionTimeout { get { return _failureDetectionTimeout ?? DefaultFailureDetectionTimeout; } set { _failureDetectionTimeout = value; } } /// <summary> /// Gets or sets the failure detection timeout used by <see cref="TcpDiscoverySpi"/> /// and <see cref="TcpCommunicationSpi"/> for client nodes. /// </summary> [DefaultValue(typeof(TimeSpan), "00:00:30")] public TimeSpan ClientFailureDetectionTimeout { get { return _clientFailureDetectionTimeout ?? DefaultClientFailureDetectionTimeout; } set { _clientFailureDetectionTimeout = value; } } /// <summary> /// Gets or sets the configurations for plugins to be started. /// </summary> [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public ICollection<IPluginConfiguration> PluginConfigurations { get; set; } /// <summary> /// Gets or sets the event storage interface. /// <para /> /// Only predefined implementations are supported: /// <see cref="NoopEventStorageSpi"/>, <see cref="MemoryEventStorageSpi"/>. /// </summary> public IEventStorageSpi EventStorageSpi { get; set; } /// <summary> /// Gets or sets the page memory configuration. /// <see cref="MemoryConfiguration"/> for more details. /// <para /> /// Obsolete, use <see cref="DataStorageConfiguration"/>. /// </summary> [Obsolete("Use DataStorageConfiguration.")] public MemoryConfiguration MemoryConfiguration { get; set; } /// <summary> /// Gets or sets the data storage configuration. /// </summary> public DataStorageConfiguration DataStorageConfiguration { get; set; } /// <summary> /// Gets or sets a value indicating how user assemblies should be loaded on remote nodes. /// <para /> /// For example, when executing <see cref="ICompute.Call{TRes}(IComputeFunc{TRes})"/>, /// the assembly with corresponding <see cref="IComputeFunc{TRes}"/> should be loaded on remote nodes. /// With this option enabled, Ignite will attempt to send the assembly to remote nodes /// and load it there automatically. /// <para /> /// Default is <see cref="Apache.Ignite.Core.Deployment.PeerAssemblyLoadingMode.Disabled"/>. /// <para /> /// Peer loading is enabled for <see cref="ICompute"/> functionality. /// </summary> public PeerAssemblyLoadingMode PeerAssemblyLoadingMode { get; set; } /// <summary> /// Gets or sets the size of the public thread pool, which processes compute jobs and user messages. /// </summary> public int PublicThreadPoolSize { get { return _publicThreadPoolSize ?? DefaultThreadPoolSize; } set { _publicThreadPoolSize = value; } } /// <summary> /// Gets or sets the size of the striped thread pool, which processes cache requests. /// </summary> public int StripedThreadPoolSize { get { return _stripedThreadPoolSize ?? DefaultThreadPoolSize; } set { _stripedThreadPoolSize = value; } } /// <summary> /// Gets or sets the size of the service thread pool, which processes Ignite services. /// </summary> public int ServiceThreadPoolSize { get { return _serviceThreadPoolSize ?? DefaultThreadPoolSize; } set { _serviceThreadPoolSize = value; } } /// <summary> /// Gets or sets the size of the system thread pool, which processes internal system messages. /// </summary> public int SystemThreadPoolSize { get { return _systemThreadPoolSize ?? DefaultThreadPoolSize; } set { _systemThreadPoolSize = value; } } /// <summary> /// Gets or sets the size of the asynchronous callback thread pool. /// </summary> public int AsyncCallbackThreadPoolSize { get { return _asyncCallbackThreadPoolSize ?? DefaultThreadPoolSize; } set { _asyncCallbackThreadPoolSize = value; } } /// <summary> /// Gets or sets the size of the management thread pool, which processes internal Ignite jobs. /// </summary> [DefaultValue(DefaultManagementThreadPoolSize)] public int ManagementThreadPoolSize { get { return _managementThreadPoolSize ?? DefaultManagementThreadPoolSize; } set { _managementThreadPoolSize = value; } } /// <summary> /// Gets or sets the size of the data streamer thread pool. /// </summary> public int DataStreamerThreadPoolSize { get { return _dataStreamerThreadPoolSize ?? DefaultThreadPoolSize; } set { _dataStreamerThreadPoolSize = value; } } /// <summary> /// Gets or sets the size of the utility cache thread pool. /// </summary> public int UtilityCacheThreadPoolSize { get { return _utilityCacheThreadPoolSize ?? DefaultThreadPoolSize; } set { _utilityCacheThreadPoolSize = value; } } /// <summary> /// Gets or sets the size of the query thread pool. /// </summary> public int QueryThreadPoolSize { get { return _queryThreadPoolSize ?? DefaultThreadPoolSize; } set { _queryThreadPoolSize = value; } } /// <summary> /// Gets or sets the SQL connector configuration (for JDBC and ODBC). /// </summary> [Obsolete("Use ClientConnectorConfiguration instead.")] public SqlConnectorConfiguration SqlConnectorConfiguration { get; set; } /// <summary> /// Gets or sets the client connector configuration (for JDBC, ODBC, and thin clients). /// </summary> public ClientConnectorConfiguration ClientConnectorConfiguration { get; set; } /// <summary> /// Gets or sets a value indicating whether client connector is enabled: /// allow thin clients, ODBC and JDBC drivers to work with Ignite /// (see <see cref="ClientConnectorConfiguration"/>). /// Default is <see cref="DefaultClientConnectorConfigurationEnabled"/>. /// </summary> [DefaultValue(DefaultClientConnectorConfigurationEnabled)] public bool ClientConnectorConfigurationEnabled { get; set; } /// <summary> /// Gets or sets the timeout after which long query warning will be printed. /// </summary> [DefaultValue(typeof(TimeSpan), "00:00:03")] public TimeSpan LongQueryWarningTimeout { get { return _longQueryWarningTimeout ?? DefaultLongQueryWarningTimeout; } set { _longQueryWarningTimeout = value; } } /// <summary> /// Gets or sets the persistent store configuration. /// <para /> /// Obsolete, use <see cref="DataStorageConfiguration"/>. /// </summary> [Obsolete("Use DataStorageConfiguration.")] public PersistentStoreConfiguration PersistentStoreConfiguration { get; set; } /// <summary> /// Gets or sets a value indicating whether grid should be active on start. /// See also <see cref="IIgnite.IsActive"/> and <see cref="IIgnite.SetActive"/>. /// <para /> /// This property is ignored when <see cref="DataStorageConfiguration"/> is present: /// cluster is always inactive on start when Ignite Persistence is enabled. /// </summary> [DefaultValue(DefaultIsActiveOnStart)] public bool IsActiveOnStart { get { return _isActiveOnStart ?? DefaultIsActiveOnStart; } set { _isActiveOnStart = value; } } /// <summary> /// Gets or sets consistent globally unique node identifier which survives node restarts. /// </summary> public object ConsistentId { get; set; } /// <summary> /// Gets or sets a value indicating whether Java console output should be redirected /// to <see cref="Console.Out"/> and <see cref="Console.Error"/>, respectively. /// <para /> /// Default is <see cref="DefaultRedirectJavaConsoleOutput"/>. /// <para /> /// Java code outputs valuable information to console. However, since that is Java console, /// it is not possible to capture that output with standard .NET APIs (<see cref="Console.SetOut"/>). /// As a result, many tools (IDEs, test runners) are not able to display Ignite console output in UI. /// <para /> /// This property is enabled by default and redirects Java console output to standard .NET console. /// It is recommended to disable this in production. /// </summary> [DefaultValue(DefaultRedirectJavaConsoleOutput)] public bool RedirectJavaConsoleOutput { get; set; } } }
using System; using System.IO; using System.Text; using Encoding = System.Text.Encoding; namespace Sxta.GenericProtocol.Encoding { /* Stream Reader Functions */ public static class StreamReaderExtensions { /* Read a byte */ public static byte ReadByte (this Stream stream, long offset) { stream.Position = offset; return (byte)stream.ReadByte (); } /* Read bytes */ public static byte[] ReadBytes (this Stream stream, long offset, int length) { byte[] array = new byte[length]; stream.Position = offset; stream.Read (array, 0, length); return array; } public static byte[] ReadBytes(this Stream stream, int length) { byte[] array = new byte[length]; stream.Read(array, 0, length); return array; } public static byte[] ReadBytes (this Stream stream, long offset, uint length) { return stream.ReadBytes (offset, (int)length); } /* Read a short */ public static short ReadShort (this Stream stream, long offset) { byte[] array = new byte[2]; stream.Position = offset; stream.Read (array, 0, 2); return BitConverter.ToInt16 (array, 0); } public static ushort ReadUShort (this Stream stream, long offset) { byte[] array = new byte[2]; stream.Position = offset; stream.Read (array, 0, 2); return BitConverter.ToUInt16 (array, 0); } /* Read an integer */ public static int ReadInt (this Stream stream, long offset) { byte[] array = new byte[4]; stream.Position = offset; stream.Read (array, 0, 4); return BitConverter.ToInt32 (array, 0); } public static uint ReadUInt (this Stream stream, long offset) { byte[] array = new byte[4]; stream.Position = offset; stream.Read (array, 0, 4); return BitConverter.ToUInt32 (array, 0); } /* Read a string */ public static string ReadString (this Stream stream, long offset, int maxLength, bool nullTerminator) { string str = string.Empty; stream.Position = offset; for (int i = 0; i < maxLength; i++) { char chr = (char)stream.ReadByte (); if (chr == '\0' && nullTerminator) break; else str += chr; } return str; } public static string ReadString (this Stream stream, long offset, int maxLength) { return stream.ReadString (offset, maxLength, true); } // Read a string with a specific encoding public static string ReadString(this Stream stream, long offset, int maxLength, System.Text.Encoding encoding, bool nullTerminator) { stream.Position = offset; byte[] array = new byte[maxLength]; stream.Read (array, 0x00, maxLength); string str = encoding.GetString (array); if (nullTerminator) str = str.TrimEnd ('\0'); return str; } public static string ReadString(this Stream stream, long offset, int maxLength, System.Text.Encoding encoding) { return stream.ReadString (offset, maxLength, encoding, true); } // Copy to a byte array public static byte[] ToByteArray (this Stream stream) { byte[] array = new byte[stream.Length]; stream.Position = 0; stream.Read (array, 0, array.Length); return array; } } /* Stream Writer Functions */ public static class StreamWriterExtensions { /* Write an byte */ public static void Write (this Stream stream, byte value) { stream.WriteByte (value); } /* Write a short */ public static void Write (this Stream stream, short value) { stream.Write (BitConverter.GetBytes (value), 0, 2); } public static void Write (this Stream stream, ushort value) { stream.Write (BitConverter.GetBytes (value), 0, 2); } /* Write an integer */ public static void Write (this Stream stream, int value) { stream.Write (BitConverter.GetBytes (value), 0, 4); } public static void Write (this Stream stream, uint value) { stream.Write (BitConverter.GetBytes (value), 0, 4); } /* Write a byte array */ public static void Write (this Stream stream, byte[] values) { stream.Write (values, 0, values.Length); } /* Write a string */ public static void Write (this Stream stream, string value) { for (int i = 0; i < value.Length; i++) stream.WriteByte ((byte)value [i]); } public static void Write (this Stream stream, string value, int length) { for (int i = 0; i < length; i++) { if (i < value.Length) stream.WriteByte ((byte)value [i]); else stream.WriteByte (0x0); } } public static void Write (this Stream stream, string value, int strLength, int length) { for (int i = 0; i < length; i++) { if (i < value.Length && i < strLength) stream.WriteByte ((byte)value [i]); else stream.WriteByte (0x0); } } // Write a string with a specific encoding public static void Write(this Stream stream, string value, int strLength, int length, System.Text.Encoding encoding) { byte[] strArray = encoding.GetBytes (value); int trimAmount = 0; while (strArray.Length > strLength) { trimAmount++; strArray = encoding.GetBytes (value.Substring (0, value.Length - trimAmount)); } for (int i = 0; i < length; i++) { if (i < strArray.Length && i < strLength) stream.WriteByte (strArray [i]); else stream.WriteByte (0x00); } } /* Write a stream */ public static void Write (this Stream output, Stream input) { byte[] buffer = new byte[4096]; input.Position = 0; int bytes; while ((bytes = input.Read(buffer, 0, buffer.Length)) > 0) output.Write (buffer, 0, bytes); } public static void Write (this Stream output, MemoryStream input) { input.Position = 0; input.WriteTo (output); } public static void Write (this Stream output, Stream input, long offset, long length) { byte[] buffer = new byte[4096]; input.Position = offset; int bytes; while ((bytes = input.Read(buffer, 0, (int)(input.Position + buffer.Length > offset + length ? offset + length - input.Position : buffer.Length))) > 0) output.Write (buffer, 0, bytes); } /* Copy stream */ public static MemoryStream Copy (this Stream input) { MemoryStream output = new MemoryStream ((int)input.Length); byte[] buffer = new byte[4096]; input.Position = 0; int bytes; while ((bytes = input.Read(buffer, 0, buffer.Length)) > 0) output.Write (buffer, 0, bytes); return output; } public static MemoryStream Copy (this Stream input, long offset, int length) { MemoryStream output = new MemoryStream (length); byte[] buffer = new byte[4096]; input.Position = offset; int bytes; while ((bytes = input.Read(buffer, 0, (int)(input.Position + buffer.Length > offset + length ? offset + length - input.Position : buffer.Length))) > 0) output.Write (buffer, 0, bytes); return output; } public static MemoryStream Copy (this Stream input, long offset, uint length) { MemoryStream output = new MemoryStream ((int)length); byte[] buffer = new byte[4096]; input.Position = offset; int bytes; while ((bytes = input.Read(buffer, 0, (int)(input.Position + buffer.Length > offset + length ? offset + length - input.Position : buffer.Length))) > 0) output.Write (buffer, 0, bytes); return output; } } }
#region Disclaimer/Info /////////////////////////////////////////////////////////////////////////////////////////////////// // .Text WebLog // // .Text is an open source weblog system started by Scott Watermasysk. // Blog: http://ScottWater.com/blog // RSS: http://scottwater.com/blog/rss.aspx // Email: [email protected] // // For updated news and information please visit http://scottwater.com/dottext and subscribe to // the Rss feed @ http://scottwater.com/dottext/rss.aspx // // On its release (on or about August 1, 2003) this application is licensed under the BSD. However, I reserve the // right to change or modify this at any time. The most recent and up to date license can always be fount at: // http://ScottWater.com/License.txt // // Please direct all code related questions to: // GotDotNet Workspace: http://www.gotdotnet.com/Community/Workspaces/workspace.aspx?id=e99fccb3-1a8c-42b5-90ee-348f6b77c407 // Yahoo Group http://groups.yahoo.com/group/DotText/ // /////////////////////////////////////////////////////////////////////////////////////////////////// #endregion using System; using System.Collections; using System.Collections.Specialized; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using Dottext.Framework; using Dottext.Framework.Configuration; using Dottext.Web.Admin; // TODO: Expose Ancestors for editing locally? N2H namespace Dottext.Web.Admin.WebUI { [ ToolboxData("<{0}:BreadCrumbs runat=\"server\" />") ] public class BreadCrumbs : Control { protected const string PREFIXTEXT_DEFAULT = "Location:"; protected const string SEPARATOR_DEFAULT = "&nbsp;&#187;&nbsp;"; protected const string SPACER_DEFAULT = "&nbsp;"; protected Control container; protected PageLocation _lastItem; protected string _lastItemText; protected bool _lastItemOverride = false; protected string _pageID = String.Empty; protected bool _isPanel = true; protected bool _includeRoot = true; protected bool _includeSelf = true; protected bool _lastItemStatic; protected bool _usePrefixText = false; protected string _prefixText = PREFIXTEXT_DEFAULT; protected bool _useSpacers = true; protected string _spacer = SPACER_DEFAULT; protected string _separator = SEPARATOR_DEFAULT; protected string _cssClass = String.Empty; protected string _linkCssClass = String.Empty; protected string _lastCssClass = String.Empty; protected NameValueCollection _linkStyle = new NameValueCollection(); protected NameValueCollection _lastStyle = new NameValueCollection(); public BreadCrumbs() { SetContainer(); } #region Accessors public string PageID { get { if (_pageID.Length > 0) return _pageID; else return this.Page.GetType().BaseType.FullName; } set { _pageID = value; } } public bool IsPanel { get { return _isPanel; } set { if (_isPanel != value) { _isPanel = value; SetContainer(); } } } public bool IncludeRoot { get { return _includeRoot; } set { _includeRoot = value; } } public bool IncludeSelf { get { return _includeSelf; } set { _includeSelf = value; } } public bool UsePrefixText { get { return _usePrefixText; } set { _usePrefixText = value; } } public string PrefixText { get { return _prefixText; } set { _prefixText = value; } } public bool UseSpacers { get { return _useSpacers; } set { _useSpacers = value; } } public string Spacer { get { return _spacer; } set { _spacer = value; } } public string Separator { get { return _separator; } set { _separator = value; } } public bool LastItemStatic { get { return _lastItemStatic; } set { _lastItemStatic = value; } } public string CssClass { get { return _cssClass; } set { _cssClass = value; } } public string LinkCssClass { get { return _linkCssClass; } set { _linkCssClass = value; } } public string LastCssClass { get { return _lastCssClass; } set { _lastCssClass = value; } } public NameValueCollection LinkStyle { get { return _linkStyle; } } public NameValueCollection LastStyle { get { return _lastStyle; } } #endregion protected void SetContainer() { if (_isPanel) { container = new Panel(); this.Controls.Clear(); this.Controls.Add(container); } else { this.Controls.Clear(); container = this; } } public void AddLastItem(string title) { _lastItemStatic = true; _lastItemOverride = true; _lastItemText = title; } public void AddLastItem(string title, string url) { AddLastItem(title, url, String.Empty); } public void AddLastItem(string title, string url, string description) { _lastItem = new PageLocation(String.Empty, title, url, description); _lastItemOverride = true; } private string _fullyQualifiedBaseUrl; public string FullyQualifiedBaseUrl { get { if( this._fullyQualifiedBaseUrl == null) { this._fullyQualifiedBaseUrl = Config.CurrentBlog().FullyQualifiedUrl + "admin/"; } return this._fullyQualifiedBaseUrl; } set {this._fullyQualifiedBaseUrl = value;} } protected HyperLink CreateHyperLinkFromLocation(PageLocation value, bool isLastItem) { HyperLink result = new HyperLink(); result.Text = value.Title; result.NavigateUrl = FullyQualifiedBaseUrl + value.Url; result.CssClass = isLastItem ? _lastCssClass : _linkCssClass; result = (HyperLink)ApplyStyles(result, isLastItem); result.Target = value.Target; return result; } protected WebControl ApplyStyles(WebControl control, bool isLastItem) { if (isLastItem && _lastStyle.Count > 0) return Utilities.CopyStyles(control, _lastStyle); else if (_linkStyle.Count > 0) return Utilities.CopyStyles(control, _linkStyle); else return control; } protected PageLocation[] GetSampleAncestors() { PageLocation[] results = new PageLocation[3]; results[0] = new PageLocation("", "Level 3", "#"); results[1] = new PageLocation("", "Level 2", "#"); results[2] = new PageLocation("", "Level 1", "#"); return results; } protected override void Render(HtmlTextWriter writer) { container.Controls.Clear(); PageLocation[] lineage; if (null != HttpContext.Current) lineage = SiteMap.Instance.GetAncestors(this.PageID, _includeSelf); else lineage = GetSampleAncestors(); if (null != lineage && lineage.Length > 0) { if (_usePrefixText && _prefixText.Length > 0) { container.Controls.Add(new LiteralControl(_prefixText)); if (_useSpacers) container.Controls.Add(new LiteralControl(_spacer)); } int startAt = _includeRoot ? lineage.Length - 1 : lineage.Length - 2; for (int i = startAt; i >= 0; i--) { if (i > 0 || _lastItemOverride || !_lastItemStatic) { container.Controls.Add(CreateHyperLinkFromLocation(lineage[i], i > 0 || _lastItemOverride)); } else //if (!_lastItemOverride && _lastItemStatic) (redundant) { container.Controls.Add(new LiteralControl(lineage[i].Title)); } if (_useSpacers && (i > 0 || _lastItemOverride)) container.Controls.Add(new LiteralControl(_separator)); } if (_lastItemOverride) { if (null != _lastItem) { if (!_lastItemStatic) container.Controls.Add(CreateHyperLinkFromLocation(_lastItem, true)); else container.Controls.Add(new LiteralControl(_lastItem.Title)); } else if (_lastItemText.Length > 0) container.Controls.Add(new LiteralControl(_lastItemText)); } } if (_isPanel && _cssClass.Length > 0) (container as Panel).CssClass = _cssClass; base.Render(writer); } } }
// // ExtensionNode.cs // // Author: // Lluis Sanchez Gual // // Copyright (C) 2007 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Collections; using System.Collections.Generic; using System.Xml; using System.Reflection; using Mono.Addins.Description; namespace Mono.Addins { /// <summary> /// A node of the extension model. /// </summary> /// <remarks> /// An extension node is an element registered by an add-in in an extension point. /// A host can get nodes registered in an extension point using methods such as /// AddinManager.GetExtensionNodes(string), which returns a collection of ExtensionNode objects. /// /// ExtensionNode will normally be used as a base class of more complex extension point types. /// The most common subclass is Mono.Addins.TypeExtensionNode, which allows registering a class /// implemented in an add-in. /// </remarks> public class ExtensionNode { bool childrenLoaded; TreeNode treeNode; ExtensionNodeList childNodes; RuntimeAddin addin; string addinId; ExtensionNodeType nodeType; ModuleDescription module; AddinEngine addinEngine; event ExtensionNodeEventHandler extensionNodeChanged; /// <summary> /// Identifier of the node. /// </summary> /// <remarks> /// It is not mandatory to specify an 'id' for a node. When none is provided, /// the add-in manager will automatically generate an unique id for the node. /// The ExtensionNode.HasId property can be used to know if the 'id' has been /// specified by the developer or not. /// </remarks> public string Id { get { return treeNode != null ? treeNode.Id : string.Empty; } } /// <summary> /// Location of this node in the extension tree. /// </summary> /// <remarks> /// The node path is composed by the path of the extension point where it is defined, /// the identifiers of its parent nodes, and its own identifier. /// </remarks> public string Path { get { return treeNode != null ? treeNode.GetPath () : string.Empty; } } /// <summary> /// Parent node of this node. /// </summary> public ExtensionNode Parent { get { if (treeNode != null && treeNode.Parent != null) return treeNode.Parent.ExtensionNode; else return null; } } /// <summary> /// Extension context to which this node belongs /// </summary> public ExtensionContext ExtensionContext { get { return treeNode.Context; } } /// <summary> /// Specifies whether the extension node has as an Id or not. /// </summary> /// <remarks> /// It is not mandatory to specify an 'id' for a node. When none is provided, /// the add-in manager will automatically generate an unique id for the node. /// This property will return true if an 'id' was provided for the node, and /// false if the id was assigned by the add-in manager. /// </remarks> public bool HasId { get { return !Id.StartsWith (ExtensionTree.AutoIdPrefix); } } internal void SetTreeNode (TreeNode node) { treeNode = node; } internal void SetData (AddinEngine addinEngine, string plugid, ExtensionNodeType nodeType, ModuleDescription module) { this.addinEngine = addinEngine; this.addinId = plugid; this.nodeType = nodeType; this.module = module; } internal string AddinId { get { return addinId; } } internal TreeNode TreeNode { get { return treeNode; } } /// <summary> /// The add-in that registered this extension node. /// </summary> /// <remarks> /// This property provides access to the resources and types of the add-in that created this extension node. /// </remarks> public RuntimeAddin Addin { get { if (addin == null && addinId != null) { if (!addinEngine.IsAddinLoaded (addinId)) addinEngine.LoadAddin (null, addinId, true); addin = addinEngine.GetAddin (addinId); if (addin != null) addin = addin.GetModule (module); } if (addin == null) throw new InvalidOperationException ("Add-in '" + addinId + "' could not be loaded."); return addin; } } /// <summary> /// Notifies that a child node of this node has been added or removed. /// </summary> /// <remarks> /// The first time the event is subscribed, the handler will be called for each existing node. /// </remarks> public event ExtensionNodeEventHandler ExtensionNodeChanged { add { extensionNodeChanged += value; foreach (ExtensionNode node in ChildNodes) { try { value (this, new ExtensionNodeEventArgs (ExtensionChange.Add, node)); } catch (Exception ex) { RuntimeAddin nodeAddin; try { nodeAddin = node.Addin; } catch (Exception addinException) { addinEngine.ReportError (null, null, addinException, false); nodeAddin = null; } addinEngine.ReportError (null, nodeAddin != null ? nodeAddin.Id : null, ex, false); } } } remove { extensionNodeChanged -= value; } } /// <summary> /// Child nodes of this extension node. /// </summary> public ExtensionNodeList ChildNodes { get { if (childrenLoaded) return childNodes; try { if (treeNode.Children.Count == 0) { childNodes = ExtensionNodeList.Empty; return childNodes; } } catch (Exception ex) { addinEngine.ReportError (null, null, ex, false); childNodes = ExtensionNodeList.Empty; return childNodes; } finally { childrenLoaded = true; } List<ExtensionNode> list = new List<ExtensionNode> (); foreach (TreeNode cn in treeNode.Children) { // For each node check if it is visible for the current context. // If something fails while evaluating the condition, just ignore the node. try { if (cn.ExtensionNode != null && cn.IsEnabled) list.Add (cn.ExtensionNode); } catch (Exception ex) { addinEngine.ReportError (null, null, ex, false); } } if (list.Count > 0) childNodes = new ExtensionNodeList (list); else childNodes = ExtensionNodeList.Empty; return childNodes; } } /// <summary> /// Returns the child objects of a node. /// </summary> /// <returns> /// An array of child objects. /// </returns> /// <remarks> /// This method only works if all children of this node are of type Mono.Addins.TypeExtensionNode. /// The returned array is composed by all objects created by calling the /// TypeExtensionNode.GetInstance() method for each node. /// </remarks> public object[] GetChildObjects () { return GetChildObjects (typeof(object), true); } /// <summary> /// Returns the child objects of a node. /// </summary> /// <param name="reuseCachedInstance"> /// True if the method can reuse instances created in previous calls. /// </param> /// <returns> /// An array of child objects. /// </returns> /// <remarks> /// This method only works if all children of this node are of type Mono.Addins.TypeExtensionNode. /// The returned array is composed by all objects created by calling the TypeExtensionNode.CreateInstance() /// method for each node (or TypeExtensionNode.GetInstance() if reuseCachedInstance is set to true). /// </remarks> public object[] GetChildObjects (bool reuseCachedInstance) { return GetChildObjects (typeof(object), reuseCachedInstance); } /// <summary> /// Returns the child objects of a node (with type check). /// </summary> /// <param name="arrayElementType"> /// Type of the return array elements. /// </param> /// <returns> /// An array of child objects. /// </returns> /// <remarks> /// This method only works if all children of this node are of type Mono.Addins.TypeExtensionNode. /// The returned array is composed by all objects created by calling the /// TypeExtensionNode.GetInstance(Type) method for each node. /// /// An InvalidOperationException exception is thrown if one of the found child objects is not a /// subclass of the provided type. /// </remarks> public object[] GetChildObjects (Type arrayElementType) { return GetChildObjects (arrayElementType, true); } /// <summary> /// Returns the child objects of a node (casting to the specified type) /// </summary> /// <returns> /// An array of child objects. /// </returns> /// <remarks> /// This method only works if all children of this node are of type Mono.Addins.TypeExtensionNode. /// The returned array is composed by all objects created by calling the /// TypeExtensionNode.GetInstance() method for each node. /// </remarks> public T[] GetChildObjects<T> () { return (T[]) GetChildObjectsInternal (typeof(T), true); } /// <summary> /// Returns the child objects of a node (with type check). /// </summary> /// <param name="arrayElementType"> /// Type of the return array elements. /// </param> /// <param name="reuseCachedInstance"> /// True if the method can reuse instances created in previous calls. /// </param> /// <returns> /// An array of child objects. /// </returns> /// <remarks> /// This method only works if all children of this node are of type Mono.Addins.TypeExtensionNode. /// The returned array is composed by all objects created by calling the TypeExtensionNode.CreateInstance(Type) /// method for each node (or TypeExtensionNode.GetInstance(Type) if reuseCachedInstance is set to true). /// /// An InvalidOperationException exception will be thrown if one of the found child objects is not a subclass /// of the provided type. /// </remarks> public object[] GetChildObjects (Type arrayElementType, bool reuseCachedInstance) { return (object[]) GetChildObjectsInternal (arrayElementType, reuseCachedInstance); } /// <summary> /// Returns the child objects of a node (casting to the specified type). /// </summary> /// <param name="reuseCachedInstance"> /// True if the method can reuse instances created in previous calls. /// </param> /// <returns> /// An array of child objects. /// </returns> /// <remarks> /// This method only works if all children of this node are of type Mono.Addins.TypeExtensionNode. /// The returned array is composed by all objects created by calling the TypeExtensionNode.CreateInstance() /// method for each node (or TypeExtensionNode.GetInstance() if reuseCachedInstance is set to true). /// </remarks> public T[] GetChildObjects<T> (bool reuseCachedInstance) { return (T[]) GetChildObjectsInternal (typeof(T), reuseCachedInstance); } Array GetChildObjectsInternal (Type arrayElementType, bool reuseCachedInstance) { ArrayList list = new ArrayList (ChildNodes.Count); for (int n=0; n<ChildNodes.Count; n++) { InstanceExtensionNode node = ChildNodes [n] as InstanceExtensionNode; if (node == null) { addinEngine.ReportError ("Error while getting object for node in path '" + Path + "'. Extension node is not a subclass of InstanceExtensionNode.", null, null, false); continue; } try { if (reuseCachedInstance) list.Add (node.GetInstance (arrayElementType)); else list.Add (node.CreateInstance (arrayElementType)); } catch (Exception ex) { addinEngine.ReportError ("Error while getting object for node in path '" + Path + "'.", node.AddinId, ex, false); } } return list.ToArray (arrayElementType); } /// <summary> /// Reads the extension node data /// </summary> /// <param name='elem'> /// The element containing the extension data /// </param> /// <remarks> /// This method can be overridden to provide a custom method for reading extension node data from an element. /// The default implementation reads the attributes if the element and assigns the values to the fields /// and properties of the extension node that have the corresponding [NodeAttribute] decoration. /// </remarks> internal protected virtual void Read (NodeElement elem) { if (nodeType == null) return; NodeAttribute[] attributes = elem.Attributes; ReadObject (this, attributes, nodeType.Fields); if (nodeType.CustomAttributeMember != null) { var att = (CustomExtensionAttribute) Activator.CreateInstance (nodeType.CustomAttributeMember.MemberType, true); att.ExtensionNode = this; ReadObject (att, attributes, nodeType.CustomAttributeFields); nodeType.CustomAttributeMember.SetValue (this, att); } } void ReadObject (object ob, NodeAttribute[] attributes, Dictionary<string,ExtensionNodeType.FieldData> fields) { if (fields == null) return; // Make a copy because we are going to remove fields that have been used fields = new Dictionary<string,ExtensionNodeType.FieldData> (fields); foreach (NodeAttribute at in attributes) { ExtensionNodeType.FieldData f; if (!fields.TryGetValue (at.name, out f)) continue; fields.Remove (at.name); object val; Type memberType = f.MemberType; if (memberType == typeof(string)) { if (f.Localizable) val = GetAddinLocalizer ().GetString (at.value); else val = at.value; } else if (memberType == typeof(string[])) { string[] ss = at.value.Split (','); if (ss.Length == 0 && ss[0].Length == 0) val = new string [0]; else { for (int n=0; n<ss.Length; n++) ss [n] = ss[n].Trim (); val = ss; } } else if (memberType.IsEnum) { val = Enum.Parse (memberType, at.value); } else { try { val = Convert.ChangeType (at.Value, memberType); } catch (InvalidCastException) { throw new InvalidOperationException ("Property type not supported by [NodeAttribute]: " + f.Member.DeclaringType + "." + f.Member.Name); } } f.SetValue (ob, val); } if (fields.Count > 0) { // Check if one of the remaining fields is mandatory foreach (KeyValuePair<string,ExtensionNodeType.FieldData> e in fields) { ExtensionNodeType.FieldData f = e.Value; if (f.Required) throw new InvalidOperationException ("Required attribute '" + e.Key + "' not found."); } } } /// <summary> /// Tries to avoid loading the addin dependencies when getting the localizer. /// </summary> AddinLocalizer GetAddinLocalizer () { if (addin != null || addinId == null) return Addin.Localizer; Addin foundAddin = addinEngine.Registry.GetAddin (addinId); if (foundAddin == null || foundAddin.Description.Localizer != null) return Addin.Localizer; return addinEngine.DefaultLocalizer; } internal bool NotifyChildChanged () { if (!childrenLoaded) return false; ExtensionNodeList oldList = childNodes; childrenLoaded = false; bool changed = false; foreach (ExtensionNode nod in oldList) { if (ChildNodes [nod.Id] == null) { changed = true; OnChildNodeRemoved (nod); } } foreach (ExtensionNode nod in ChildNodes) { if (oldList [nod.Id] == null) { changed = true; OnChildNodeAdded (nod); } } if (changed) OnChildrenChanged (); return changed; } /// <summary> /// Called when the add-in that defined this extension node is actually loaded in memory. /// </summary> internal protected virtual void OnAddinLoaded () { } /// <summary> /// Called when the add-in that defined this extension node is being /// unloaded from memory. /// </summary> internal protected virtual void OnAddinUnloaded () { } /// <summary> /// Called when the children list of this node has changed. It may be due to add-ins /// being loaded/unloaded, or to conditions being changed. /// </summary> protected virtual void OnChildrenChanged () { } /// <summary> /// Called when a child node is added /// </summary> /// <param name="node"> /// Added node. /// </param> protected virtual void OnChildNodeAdded (ExtensionNode node) { if (extensionNodeChanged != null) extensionNodeChanged (this, new ExtensionNodeEventArgs (ExtensionChange.Add, node)); } /// <summary> /// Called when a child node is removed /// </summary> /// <param name="node"> /// Removed node. /// </param> protected virtual void OnChildNodeRemoved (ExtensionNode node) { if (extensionNodeChanged != null) extensionNodeChanged (this, new ExtensionNodeEventArgs (ExtensionChange.Remove, node)); } } /// <summary> /// An extension node with custom metadata /// </summary> /// <remarks> /// This is the default type for extension nodes bound to a custom extension attribute. /// </remarks> public class ExtensionNode<T>: ExtensionNode, IAttributedExtensionNode where T:CustomExtensionAttribute { T data; /// <summary> /// The custom attribute containing the extension metadata /// </summary> [NodeAttribute] public T Data { get { return data; } internal set { data = value; } } CustomExtensionAttribute IAttributedExtensionNode.Attribute { get { return data; } } } /// <summary> /// An extension node with custom metadata provided by an attribute /// </summary> /// <remarks> /// This interface is implemented by ExtensionNode&lt;T&gt; to provide non-generic access to the attribute instance. /// </remarks> public interface IAttributedExtensionNode { /// <summary> /// The custom attribute containing the extension metadata /// </summary> CustomExtensionAttribute Attribute { get; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using NuGet.Packaging.Core; using NuGet.Versioning; namespace nuget2bazel { public class WorkspaceParser { private readonly string _toparse; private int _pos = 0; public WorkspaceParser(string toparse) { _toparse = toparse; } public IEnumerable<WorkspaceEntry> Parse() { return ParseEntries(); } public class UnexpectedToken : Exception { public UnexpectedToken(string literal) { Literal = literal; } public string Literal { get; } } private IEnumerable<WorkspaceEntry> ParseEntries() { var result = new List<WorkspaceEntry>(); for (; ; ) { var entry = ParseEntry(); if (entry == null) break; result.Add(entry); } return result; } private WorkspaceEntry ParseEntry() { while (!IsEof() && IsWhitespace()) ++_pos; if (IsEof()) return null; var result = new WorkspaceEntry(); string package = null; string version = null; RequireToken(TokenCode.NUGET_PACKAGE); RequireToken(TokenCode.LPAR); var finished = false; while (!finished) { var (token, val) = PeekToken(); switch (token) { case TokenCode.NAME: RequireToken(TokenCode.NAME); RequireToken(TokenCode.EQUAL); try { RequireToken(TokenCode.STRING); } catch (UnexpectedToken ex) { result.Variable = ex.Literal; } break; case TokenCode.SOURCE: RequireToken(TokenCode.SOURCE); RequireToken(TokenCode.EQUAL); RequireToken(TokenCode.SOURCE); result.NugetSourceCustom = true; break; case TokenCode.CORE_FILES: result.Core_Files = RequireDictionaryList(TokenCode.CORE_FILES); break; case TokenCode.CORE_LIB: result.CoreLib = RequireDictionary(TokenCode.CORE_LIB); break; case TokenCode.CORE_REF: result.CoreRef = RequireDictionary(TokenCode.CORE_REF); break; case TokenCode.MONO_DEPS: result.Mono_Deps = RequireArray(TokenCode.MONO_DEPS); break; case TokenCode.MONO_FILES: result.Mono_Files = RequireArray(TokenCode.MONO_FILES); break; case TokenCode.MONO_LIB: result.MonoLib = RequireAssignment(TokenCode.MONO_LIB); break; case TokenCode.MONO_REF: result.MonoRef = RequireAssignment(TokenCode.MONO_REF); break; case TokenCode.NET_DEPS: result.Net_Deps = RequireDictionaryList(TokenCode.NET_DEPS); break; case TokenCode.NET_FILES: result.Net_Files = RequireDictionaryList(TokenCode.NET_FILES); break; case TokenCode.NET_LIB: result.NetLib = RequireDictionary(TokenCode.NET_LIB); break; case TokenCode.NET_REF: result.NetRef = RequireDictionary(TokenCode.NET_REF); break; case TokenCode.PACKAGE: package = RequireAssignment(TokenCode.PACKAGE); break; case TokenCode.VERSION: version = RequireAssignment(TokenCode.VERSION); break; case TokenCode.SHA256: result.Sha256 = RequireAssignment(TokenCode.SHA256); break; case TokenCode.CORE_TOOL: result.CoreTool = RequireDictionary(TokenCode.CORE_TOOL); break; case TokenCode.NET_TOOL: result.NetTool = RequireDictionary(TokenCode.NET_TOOL); break; case TokenCode.MONO_TOOL: result.MonoTool = RequireAssignment(TokenCode.MONO_TOOL); break; case TokenCode.CORE_DEPS: result.Core_Deps = RequireDictionaryList(TokenCode.CORE_DEPS); break; case TokenCode.RPAR: finished = true; GetToken(); break; } } result.PackageIdentity = new PackageIdentity(package, new NuGetVersion(version)); return result; } private string RequireToken(TokenCode required) { var (token, value) = GetToken(); if (token != required) throw new InvalidOperationException($"Unexpected token {token}, {value}. Expected {required}"); return value; } private string RequireAssignment(TokenCode required) { var token = PeekToken(); if (token.Item1 != required) return null; RequireToken(required); RequireToken(TokenCode.EQUAL); return RequireToken(TokenCode.STRING); } private IDictionary<string, string> RequireDictionary(TokenCode required) { var tok = PeekToken(); if (tok.Item1 != required) return null; RequireToken(required); RequireToken(TokenCode.EQUAL); RequireToken(TokenCode.LCURLY); var result = new Dictionary<string, string>(); for (; ; ) { var (token, value) = GetToken(); if (token == TokenCode.STRING) { RequireToken(TokenCode.COLON); var (token2, value2) = GetToken(); if (token2 != TokenCode.STRING) throw new InvalidOperationException($"Unexpected token {token2}, {value2}. Expected TokenCode.STRING"); result.Add(value, value2); continue; } if (token == TokenCode.RCURLY) break; } return result; } private IDictionary<string, IEnumerable<string>> RequireDictionaryList(TokenCode required) { var tok = PeekToken(); if (tok.Item1 != required) return null; RequireToken(required); RequireToken(TokenCode.EQUAL); RequireToken(TokenCode.LCURLY); var result = new Dictionary<string, IEnumerable<string>>(); for (; ; ) { var (token, value) = GetToken(); if (token == TokenCode.STRING) { RequireToken(TokenCode.COLON); var (token2, value2) = GetToken(); if (token2 != TokenCode.LBRACKET) throw new InvalidOperationException($"Unexpected token {token2}, {value2}. Expected TokenCode.LBRACKET"); var val = GetArrayValue(); result.Add(value, val); continue; } if (token == TokenCode.RCURLY) break; } return result; } private IEnumerable<string> GetArrayValue() { var result = new List<string>(); for (; ; ) { var (token, value) = GetToken(); if (token == TokenCode.STRING) { result.Add(value); continue; } if (token == TokenCode.RBRACKET) break; } return result; } private IEnumerable<string> RequireArray(TokenCode required) { var tok = PeekToken(); if (tok.Item1 != required) return null; RequireToken(required); RequireToken(TokenCode.EQUAL); RequireToken(TokenCode.LBRACKET); return GetArrayValue(); } public enum TokenCode { NUGET_PACKAGE, NAME, PACKAGE, VERSION, SHA256, CORE_LIB, NET_LIB, MONO_LIB, CORE_REF, NET_REF, MONO_REF, CORE_TOOL, NET_TOOL, MONO_TOOL, CORE_DEPS, NET_DEPS, MONO_DEPS, LBRACKET, RBRACKET, LPAR, RPAR, CORE_FILES, NET_FILES, MONO_FILES, STRING, EOF, ERROR, EQUAL, COLON, LCURLY, RCURLY, LITERAL, SOURCE, } public struct Token { public TokenCode Code; public string Value; } private (TokenCode, string) GetToken() { while (!IsEof() && IsWhitespace()) ++_pos; if (IsEof()) return (TokenCode.EOF, null); switch (_toparse[_pos]) { case '(': ++_pos; return (TokenCode.LPAR, null); case ')': ++_pos; return (TokenCode.RPAR, null); case '[': ++_pos; return (TokenCode.LBRACKET, null); case ']': ++_pos; return (TokenCode.RBRACKET, null); case '=': ++_pos; return (TokenCode.EQUAL, null); case ':': ++_pos; return (TokenCode.COLON, null); case '{': ++_pos; return (TokenCode.LCURLY, null); case '}': ++_pos; return (TokenCode.RCURLY, null); } if (_toparse[_pos] == '\"') return GetString(); int q; for (q = _pos; !IsSeparator(_toparse[q]) && q < _toparse.Length; ++q) ; var str = _toparse.Substring(_pos, q - _pos); _pos = q; if (str == "source") return (TokenCode.SOURCE, null); if (str == "nuget_package") return (TokenCode.NUGET_PACKAGE, null); if (str == "name") return (TokenCode.NAME, null); if (str == "package") return (TokenCode.PACKAGE, null); if (str == "version") return (TokenCode.VERSION, null); if (str == "sha256") return (TokenCode.SHA256, null); if (str == "core_lib") return (TokenCode.CORE_LIB, null); if (str == "net_lib") return (TokenCode.NET_LIB, null); if (str == "mono_lib") return (TokenCode.MONO_LIB, null); if (str == "core_ref") return (TokenCode.CORE_REF, null); if (str == "net_ref") return (TokenCode.NET_REF, null); if (str == "mono_ref") return (TokenCode.MONO_REF, null); if (str == "core_tool") return (TokenCode.CORE_TOOL, null); if (str == "net_tool") return (TokenCode.NET_TOOL, null); if (str == "mono_tool") return (TokenCode.MONO_TOOL, null); if (str == "core_deps") return (TokenCode.CORE_DEPS, null); if (str == "net_deps") return (TokenCode.NET_DEPS, null); if (str == "mono_deps") return (TokenCode.MONO_DEPS, null); if (str == "core_files") return (TokenCode.CORE_FILES, null); if (str == "net_files") return (TokenCode.NET_FILES, null); if (str == "mono_files") return (TokenCode.MONO_FILES, null); throw new UnexpectedToken(str); } private (TokenCode, string) PeekToken() { int pos = _pos; var result = GetToken(); _pos = pos; return result; } private (TokenCode, string) GetString() { ++_pos; var q = _pos; while (!IsEof() && _toparse[q] != '\"') ++q; if (IsEof()) throw new InvalidOperationException("Expected end of string"); var result = _toparse.Substring(_pos, q - _pos); _pos = q + 1; return (TokenCode.STRING, result); } private bool IsEof() { return _pos >= _toparse.Length; } private bool IsWhitespace(char p) { switch (p) { case ' ': case '\t': case '\n': case '\r': case ',': return true; } return false; } private bool IsSeparator(char p) { switch (p) { case ' ': case '\t': case '\n': case ',': case '(': case ')': case '[': case ']': case '=': case '\r': return true; } return false; } private bool IsWhitespace() { return IsWhitespace(_toparse[_pos]); } } }
// ZlibBaseStream.cs // ------------------------------------------------------------------ // // Copyright (c) 2009 Dino Chiesa and Microsoft Corporation. // All rights reserved. // // This code module is part of DotNetZip, a zipfile class library. // // ------------------------------------------------------------------ // // This code is licensed under the Microsoft Public License. // See the file License.txt for the license details. // More info on: http://dotnetzip.codeplex.com // // ------------------------------------------------------------------ // // last saved (in emacs): // Time-stamp: <2011-August-06 21:22:38> // // ------------------------------------------------------------------ // // This module defines the ZlibBaseStream class, which is an intnernal // base class for DeflateStream, ZlibStream and GZipStream. // // ------------------------------------------------------------------ using System; using System.IO; namespace BestHTTP.Decompression.Zlib { internal enum ZlibStreamFlavor { ZLIB = 1950, DEFLATE = 1951, GZIP = 1952 } internal class ZlibBaseStream : System.IO.Stream { protected internal ZlibCodec _z = null; // deferred init... new ZlibCodec(); protected internal StreamMode _streamMode = StreamMode.Undefined; protected internal FlushType _flushMode; protected internal ZlibStreamFlavor _flavor; protected internal CompressionMode _compressionMode; protected internal CompressionLevel _level; protected internal bool _leaveOpen; protected internal byte[] _workingBuffer; protected internal int _bufferSize = ZlibConstants.WorkingBufferSizeDefault; protected internal byte[] _buf1 = new byte[1]; protected internal System.IO.Stream _stream; protected internal CompressionStrategy Strategy = CompressionStrategy.Default; // workitem 7159 BestHTTP.Decompression.Crc.CRC32 crc; protected internal string _GzipFileName; protected internal string _GzipComment; protected internal DateTime _GzipMtime; protected internal int _gzipHeaderByteCount; internal int Crc32 { get { if (crc == null) return 0; return crc.Crc32Result; } } public ZlibBaseStream(System.IO.Stream stream, CompressionMode compressionMode, CompressionLevel level, ZlibStreamFlavor flavor, bool leaveOpen) : base() { this._flushMode = FlushType.None; //this._workingBuffer = new byte[WORKING_BUFFER_SIZE_DEFAULT]; this._stream = stream; this._leaveOpen = leaveOpen; this._compressionMode = compressionMode; this._flavor = flavor; this._level = level; // workitem 7159 if (flavor == ZlibStreamFlavor.GZIP) { this.crc = new BestHTTP.Decompression.Crc.CRC32(); } } protected internal bool _wantCompress { get { return (this._compressionMode == CompressionMode.Compress); } } private ZlibCodec z { get { if (_z == null) { bool wantRfc1950Header = (this._flavor == ZlibStreamFlavor.ZLIB); _z = new ZlibCodec(); if (this._compressionMode == CompressionMode.Decompress) { _z.InitializeInflate(wantRfc1950Header); } else { _z.Strategy = Strategy; _z.InitializeDeflate(this._level, wantRfc1950Header); } } return _z; } } private byte[] workingBuffer { get { if (_workingBuffer == null) _workingBuffer = new byte[_bufferSize]; return _workingBuffer; } } public override void Write(System.Byte[] buffer, int offset, int count) { // workitem 7159 // calculate the CRC on the unccompressed data (before writing) if (crc != null) crc.SlurpBlock(buffer, offset, count); if (_streamMode == StreamMode.Undefined) _streamMode = StreamMode.Writer; else if (_streamMode != StreamMode.Writer) throw new ZlibException("Cannot Write after Reading."); if (count == 0) return; // first reference of z property will initialize the private var _z z.InputBuffer = buffer; _z.NextIn = offset; _z.AvailableBytesIn = count; bool done = false; do { _z.OutputBuffer = workingBuffer; _z.NextOut = 0; _z.AvailableBytesOut = _workingBuffer.Length; int rc = (_wantCompress) ? _z.Deflate(_flushMode) : _z.Inflate(_flushMode); if (rc != ZlibConstants.Z_OK && rc != ZlibConstants.Z_STREAM_END) throw new ZlibException((_wantCompress ? "de" : "in") + "flating: " + _z.Message); //if (_workingBuffer.Length - _z.AvailableBytesOut > 0) _stream.Write(_workingBuffer, 0, _workingBuffer.Length - _z.AvailableBytesOut); done = _z.AvailableBytesIn == 0 && _z.AvailableBytesOut != 0; // If GZIP and de-compress, we're done when 8 bytes remain. if (_flavor == ZlibStreamFlavor.GZIP && !_wantCompress) done = (_z.AvailableBytesIn == 8 && _z.AvailableBytesOut != 0); } while (!done); } private void finish() { if (_z == null) return; if (_streamMode == StreamMode.Writer) { bool done = false; do { _z.OutputBuffer = workingBuffer; _z.NextOut = 0; _z.AvailableBytesOut = _workingBuffer.Length; int rc = (_wantCompress) ? _z.Deflate(FlushType.Finish) : _z.Inflate(FlushType.Finish); if (rc != ZlibConstants.Z_STREAM_END && rc != ZlibConstants.Z_OK) { string verb = (_wantCompress ? "de" : "in") + "flating"; if (_z.Message == null) throw new ZlibException(String.Format("{0}: (rc = {1})", verb, rc)); else throw new ZlibException(verb + ": " + _z.Message); } if (_workingBuffer.Length - _z.AvailableBytesOut > 0) { _stream.Write(_workingBuffer, 0, _workingBuffer.Length - _z.AvailableBytesOut); } done = _z.AvailableBytesIn == 0 && _z.AvailableBytesOut != 0; // If GZIP and de-compress, we're done when 8 bytes remain. if (_flavor == ZlibStreamFlavor.GZIP && !_wantCompress) done = (_z.AvailableBytesIn == 8 && _z.AvailableBytesOut != 0); } while (!done); Flush(); // workitem 7159 if (_flavor == ZlibStreamFlavor.GZIP) { if (_wantCompress) { // Emit the GZIP trailer: CRC32 and size mod 2^32 int c1 = crc.Crc32Result; _stream.Write(BitConverter.GetBytes(c1), 0, 4); int c2 = (Int32)(crc.TotalBytesRead & 0x00000000FFFFFFFF); _stream.Write(BitConverter.GetBytes(c2), 0, 4); } else { throw new ZlibException("Writing with decompression is not supported."); } } } // workitem 7159 else if (_streamMode == StreamMode.Reader) { if (_flavor == ZlibStreamFlavor.GZIP) { if (!_wantCompress) { // workitem 8501: handle edge case (decompress empty stream) if (_z.TotalBytesOut == 0L) return; // Read and potentially verify the GZIP trailer: // CRC32 and size mod 2^32 byte[] trailer = new byte[8]; // workitems 8679 & 12554 if (_z.AvailableBytesIn < 8) { // Make sure we have read to the end of the stream Array.Copy(_z.InputBuffer, _z.NextIn, trailer, 0, _z.AvailableBytesIn); int bytesNeeded = 8 - _z.AvailableBytesIn; int bytesRead = _stream.Read(trailer, _z.AvailableBytesIn, bytesNeeded); if (bytesNeeded != bytesRead) { throw new ZlibException(String.Format("Missing or incomplete GZIP trailer. Expected 8 bytes, got {0}.", _z.AvailableBytesIn + bytesRead)); } } else { Array.Copy(_z.InputBuffer, _z.NextIn, trailer, 0, trailer.Length); } Int32 crc32_expected = BitConverter.ToInt32(trailer, 0); Int32 crc32_actual = crc.Crc32Result; Int32 isize_expected = BitConverter.ToInt32(trailer, 4); Int32 isize_actual = (Int32)(_z.TotalBytesOut & 0x00000000FFFFFFFF); if (crc32_actual != crc32_expected) throw new ZlibException(String.Format("Bad CRC32 in GZIP trailer. (actual({0:X8})!=expected({1:X8}))", crc32_actual, crc32_expected)); if (isize_actual != isize_expected) throw new ZlibException(String.Format("Bad size in GZIP trailer. (actual({0})!=expected({1}))", isize_actual, isize_expected)); } else { throw new ZlibException("Reading with compression is not supported."); } } } } private void end() { if (z == null) return; if (_wantCompress) { _z.EndDeflate(); } else { _z.EndInflate(); } _z = null; } public #if !NETFX_CORE override #endif void Close() { if (_stream == null) return; try { finish(); } finally { end(); if (!_leaveOpen) _stream.Dispose(); _stream = null; } } public override void Flush() { _stream.Flush(); } public override System.Int64 Seek(System.Int64 offset, System.IO.SeekOrigin origin) { throw new NotImplementedException(); //_outStream.Seek(offset, origin); } public override void SetLength(System.Int64 value) { _stream.SetLength(value); } #if NOT public int Read() { if (Read(_buf1, 0, 1) == 0) return 0; // calculate CRC after reading if (crc!=null) crc.SlurpBlock(_buf1,0,1); return (_buf1[0] & 0xFF); } #endif private bool nomoreinput = false; private string ReadZeroTerminatedString() { var list = new System.Collections.Generic.List<byte>(); bool done = false; do { // workitem 7740 int n = _stream.Read(_buf1, 0, 1); if (n != 1) throw new ZlibException("Unexpected EOF reading GZIP header."); else { if (_buf1[0] == 0) done = true; else list.Add(_buf1[0]); } } while (!done); byte[] a = list.ToArray(); return GZipStream.iso8859dash1.GetString(a, 0, a.Length); } private int _ReadAndValidateGzipHeader() { int totalBytesRead = 0; // read the header on the first read byte[] header = new byte[10]; int n = _stream.Read(header, 0, header.Length); // workitem 8501: handle edge case (decompress empty stream) if (n == 0) return 0; if (n != 10) throw new ZlibException("Not a valid GZIP stream."); if (header[0] != 0x1F || header[1] != 0x8B || header[2] != 8) throw new ZlibException("Bad GZIP header."); Int32 timet = BitConverter.ToInt32(header, 4); _GzipMtime = GZipStream._unixEpoch.AddSeconds(timet); totalBytesRead += n; if ((header[3] & 0x04) == 0x04) { // read and discard extra field n = _stream.Read(header, 0, 2); // 2-byte length field totalBytesRead += n; Int16 extraLength = (Int16)(header[0] + header[1] * 256); byte[] extra = new byte[extraLength]; n = _stream.Read(extra, 0, extra.Length); if (n != extraLength) throw new ZlibException("Unexpected end-of-file reading GZIP header."); totalBytesRead += n; } if ((header[3] & 0x08) == 0x08) _GzipFileName = ReadZeroTerminatedString(); if ((header[3] & 0x10) == 0x010) _GzipComment = ReadZeroTerminatedString(); if ((header[3] & 0x02) == 0x02) Read(_buf1, 0, 1); // CRC16, ignore return totalBytesRead; } public override System.Int32 Read(System.Byte[] buffer, System.Int32 offset, System.Int32 count) { // According to MS documentation, any implementation of the IO.Stream.Read function must: // (a) throw an exception if offset & count reference an invalid part of the buffer, // or if count < 0, or if buffer is null // (b) return 0 only upon EOF, or if count = 0 // (c) if not EOF, then return at least 1 byte, up to <count> bytes if (_streamMode == StreamMode.Undefined) { if (!this._stream.CanRead) throw new ZlibException("The stream is not readable."); // for the first read, set up some controls. _streamMode = StreamMode.Reader; // (The first reference to _z goes through the private accessor which // may initialize it.) z.AvailableBytesIn = 0; if (_flavor == ZlibStreamFlavor.GZIP) { _gzipHeaderByteCount = _ReadAndValidateGzipHeader(); // workitem 8501: handle edge case (decompress empty stream) if (_gzipHeaderByteCount == 0) return 0; } } if (_streamMode != StreamMode.Reader) throw new ZlibException("Cannot Read after Writing."); if (count == 0) return 0; if (nomoreinput && _wantCompress) return 0; // workitem 8557 if (buffer == null) throw new ArgumentNullException("buffer"); if (count < 0) throw new ArgumentOutOfRangeException("count"); if (offset < buffer.GetLowerBound(0)) throw new ArgumentOutOfRangeException("offset"); if ((offset + count) > buffer.GetLength(0)) throw new ArgumentOutOfRangeException("count"); int rc = 0; // set up the output of the deflate/inflate codec: _z.OutputBuffer = buffer; _z.NextOut = offset; _z.AvailableBytesOut = count; // This is necessary in case _workingBuffer has been resized. (new byte[]) // (The first reference to _workingBuffer goes through the private accessor which // may initialize it.) _z.InputBuffer = workingBuffer; do { // need data in _workingBuffer in order to deflate/inflate. Here, we check if we have any. if ((_z.AvailableBytesIn == 0) && (!nomoreinput)) { // No data available, so try to Read data from the captive stream. _z.NextIn = 0; _z.AvailableBytesIn = _stream.Read(_workingBuffer, 0, _workingBuffer.Length); if (_z.AvailableBytesIn == 0) nomoreinput = true; } // we have data in InputBuffer; now compress or decompress as appropriate rc = (_wantCompress) ? _z.Deflate(_flushMode) : _z.Inflate(_flushMode); if (nomoreinput && (rc == ZlibConstants.Z_BUF_ERROR)) return 0; if (rc != ZlibConstants.Z_OK && rc != ZlibConstants.Z_STREAM_END) throw new ZlibException(String.Format("{0}flating: rc={1} msg={2}", (_wantCompress ? "de" : "in"), rc, _z.Message)); if ((nomoreinput || rc == ZlibConstants.Z_STREAM_END) && (_z.AvailableBytesOut == count)) break; // nothing more to read } //while (_z.AvailableBytesOut == count && rc == ZlibConstants.Z_OK); while (_z.AvailableBytesOut > 0 && !nomoreinput && rc == ZlibConstants.Z_OK); // workitem 8557 // is there more room in output? if (_z.AvailableBytesOut > 0) { if (rc == ZlibConstants.Z_OK && _z.AvailableBytesIn == 0) { // deferred } // are we completely done reading? if (nomoreinput) { // and in compression? if (_wantCompress) { // no more input data available; therefore we flush to // try to complete the read rc = _z.Deflate(FlushType.Finish); if (rc != ZlibConstants.Z_OK && rc != ZlibConstants.Z_STREAM_END) throw new ZlibException(String.Format("Deflating: rc={0} msg={1}", rc, _z.Message)); } } } rc = (count - _z.AvailableBytesOut); // calculate CRC after reading if (crc != null) crc.SlurpBlock(buffer, offset, rc); return rc; } public override System.Boolean CanRead { get { return this._stream.CanRead; } } public override System.Boolean CanSeek { get { return this._stream.CanSeek; } } public override System.Boolean CanWrite { get { return this._stream.CanWrite; } } public override System.Int64 Length { get { return _stream.Length; } } public override long Position { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } internal enum StreamMode { Writer, Reader, Undefined, } public static void CompressString(String s, Stream compressor) { byte[] uncompressed = System.Text.Encoding.UTF8.GetBytes(s); using (compressor) { compressor.Write(uncompressed, 0, uncompressed.Length); } } public static void CompressBuffer(byte[] b, Stream compressor) { // workitem 8460 using (compressor) { compressor.Write(b, 0, b.Length); } } public static String UncompressString(byte[] compressed, Stream decompressor) { // workitem 8460 byte[] working = new byte[1024]; var encoding = System.Text.Encoding.UTF8; using (var output = new MemoryStream()) { using (decompressor) { int n; while ((n = decompressor.Read(working, 0, working.Length)) != 0) { output.Write(working, 0, n); } } // reset to allow read from start output.Seek(0, SeekOrigin.Begin); var sr = new StreamReader(output, encoding); return sr.ReadToEnd(); } } public static byte[] UncompressBuffer(byte[] compressed, Stream decompressor) { // workitem 8460 byte[] working = new byte[1024]; using (var output = new MemoryStream()) { using (decompressor) { int n; while ((n = decompressor.Read(working, 0, working.Length)) != 0) { output.Write(working, 0, n); } } return output.ToArray(); } } } }
/****************************************************************************** * Copyright (C) Leap Motion, Inc. 2011-2017. * * Leap Motion proprietary and confidential. * * * * Use subject to the terms of the Leap Motion SDK Agreement available at * * https://developer.leapmotion.com/sdk_agreement, or another agreement * * between Leap Motion and you, your company or other organization. * ******************************************************************************/ using Leap.Unity.Attributes; using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Events; namespace Leap.Unity.Animation { /// <summary> /// This is a wrapper MonoBehaviour that demonstrates and exposes some of the /// basic functionality of the Tween library. Tweens can interpolate between /// more than just Transform properties, so don't be afraid to roll your own. /// </summary> public class TransformTweenBehaviour : MonoBehaviour { [Tooltip("The transform to which to apply the tweened properties.")] public Transform targetTransform; [Tooltip("The transform whose position/rotation/localScale provide the start state of the tween.")] public Transform startTransform; [Tooltip("The transform whose position/rotation/localScale provide the end state of the tween.")] public Transform endTransform; public bool startAtEnd = false; [Header("Tween Settings")] public bool tweenLocalPosition = true; public bool tweenLocalRotation = true; public bool tweenLocalScale = true; [MinValue(0.001F)] public float tweenDuration = 0.25F; public SmoothType tweenSmoothType = SmoothType.Smooth; #region Events public Action<float> OnProgress = (progress) => { }; public Action OnLeaveStart = () => { }; public Action OnReachEnd = () => { }; public Action OnLeaveEnd = () => { }; public Action OnReachStart = () => { }; #endregion private Tween _tween; /// <summary> /// Returns the Tween object the TransformTween behaviour produces on Start(). /// /// Use this to play or otherwise manipulate the animation. /// </summary> public Tween tween { get { return _tween; } set { _tween = value; } } void OnValidate() { if (targetTransform != null) { if (startTransform == targetTransform) { Debug.LogError("The start transform of the TransformTweenBehaviour should be " + "a different transform than the target transform; the start " + "transform provides starting position/rotation/scale information " + "for the tween.", this.gameObject); } else if (endTransform == targetTransform) { Debug.LogError("The end transform of the TransformTweenBehaviour should be " + "a different transform than the target transform; the end " + "transform provides ending position/rotation/scale information " + "for the tween.", this.gameObject); } } } void Awake() { initUnityEvents(); // Tween setup methods return the Tween object itself, so you can chain your setup // method calls. _tween = Tween.Persistent().OverTime(tweenDuration) .Smooth(tweenSmoothType); if (tweenLocalPosition) _tween = _tween.Target(targetTransform) .LocalPosition(startTransform, endTransform); if (tweenLocalRotation) _tween = _tween.Target(targetTransform) .LocalRotation(startTransform, endTransform); if (tweenLocalScale) _tween = _tween.Target(targetTransform) .LocalScale(startTransform, endTransform); // Hook up the UnityEvents to the actual Tween callbacks. _tween.OnProgress(OnProgress); _tween.OnLeaveStart(OnLeaveStart); _tween.OnReachEnd(OnReachEnd); _tween.OnLeaveEnd(OnLeaveEnd); _tween.OnReachStart(OnReachStart); // TODO: This isn't great but it's the only way I've seen to make sure the tween // updates with its progress at the right state :( if (startAtEnd) { _tween.progress = 0.9999999F; _tween.Play(Direction.Forward); } else { _tween.progress = 0.0000001F; _tween.Play(Direction.Backward); } } void OnDestroy() { if (_tween.isValid) { _tween.Release(); } } private Coroutine _playTweenAfterDelayCoroutine; private Direction _curDelayedDirection = Direction.Backward; /// <summary> /// Tweens play forward by default, but at any time past the starting /// state they can also be played backwards to return to the starting /// state. See the tween property for more direct control of this /// behaviour's tween. /// </summary> public void PlayTween() { PlayTween(Direction.Forward); } public void PlayTween(Direction tweenDirection = Direction.Forward, float afterDelay = 0F) { if (_playTweenAfterDelayCoroutine != null && tweenDirection != _curDelayedDirection) { StopCoroutine(_playTweenAfterDelayCoroutine); _curDelayedDirection = tweenDirection; } _playTweenAfterDelayCoroutine = StartCoroutine(playAfterDelay(tweenDirection, afterDelay)); } private IEnumerator playAfterDelay(Direction tweenDirection, float delay) { yield return new WaitForSeconds(delay); tween.Play(tweenDirection); } public void PlayForward() { PlayTween(Direction.Forward); } public void PlayBackward() { PlayTween(Direction.Backward); } public void PlayForwardAfterDelay(float delay = 0F) { PlayTween(Direction.Forward, delay); } public void PlayBackwardAfterDelay(float delay = 0F) { PlayTween(Direction.Backward, delay); } /// <summary> /// Stops the underlying tween and resets it to the starting state. /// </summary> public void StopTween() { tween.Stop(); } public void SetTargetToStart() { setTargetTo(startTransform); } public void SetTargetToEnd() { setTargetTo(endTransform); } private void setTargetTo(Transform t) { if (targetTransform != null && t != null) { if (tweenLocalPosition) targetTransform.localPosition = t.localPosition; if (tweenLocalRotation) targetTransform.localRotation = t.localRotation; if (tweenLocalScale) targetTransform.localScale = t.localScale; } } #region Unity Events (Internal) [System.Serializable] public class FloatEvent : UnityEvent<float> { } [SerializeField] private EnumEventTable _eventTable; public enum EventType { //OnProgress = 100, // Requires float Event data OnLeaveStart = 110, OnReachEnd = 120, OnLeaveEnd = 130, OnReachStart = 140 } private void initUnityEvents() { setupCallback(ref OnLeaveStart, EventType.OnLeaveStart); setupCallback(ref OnReachEnd, EventType.OnReachEnd); setupCallback(ref OnLeaveEnd, EventType.OnLeaveEnd); setupCallback(ref OnReachStart, EventType.OnReachStart); } private void setupCallback(ref Action action, EventType type) { action += () => _eventTable.Invoke((int)type); } private void setupCallback<T>(ref Action<T> action, EventType type) { action += (anchObj) => _eventTable.Invoke((int)type); } #endregion } }
using System.Runtime.Intrinsics; using NUnit.Framework; using TerraFX.Numerics; using SysVector3 = System.Numerics.Vector3; namespace TerraFX.UnitTests.Numerics; /// <summary>Provides a set of tests covering the <see cref="Vector3" /> struct.</summary> [TestFixture(TestOf = typeof(Vector3))] public class Vector3Tests { /// <summary>Provides validation of the <see cref="Vector3.Zero" /> property.</summary> [Test] public static void ZeroTest() { Assert.That(() => Vector3.Zero, Is.EqualTo(Vector3.Create(0.0f, 0.0f, 0.0f)) ); } /// <summary>Provides validation of the <see cref="Vector3.UnitX" /> property.</summary> [Test] public static void UnitXTest() { Assert.That(() => Vector3.UnitX, Is.EqualTo(Vector3.Create(1.0f, 0.0f, 0.0f)) ); } /// <summary>Provides validation of the <see cref="Vector3.UnitY" /> property.</summary> [Test] public static void UnitYTest() { Assert.That(() => Vector3.UnitY, Is.EqualTo(Vector3.Create(0.0f, 1.0f, 0.0f)) ); } /// <summary>Provides validation of the <see cref="Vector3.UnitZ" /> property.</summary> [Test] public static void UnitZTest() { Assert.That(() => Vector3.UnitZ, Is.EqualTo(Vector3.Create(0.0f, 0.0f, 1.0f)) ); } /// <summary>Provides validation of the <see cref="Vector3.One" /> property.</summary> [Test] public static void OneTest() { Assert.That(() => Vector3.One, Is.EqualTo(Vector3.Create(1.0f, 1.0f, 1.0f)) ); } /// <summary>Provides validation of the <see cref="M:Vector3.Create" /> methods.</summary> [Test] public static void CreateTest() { var value = Vector3.Zero; Assert.That(() => value.X, Is.EqualTo(0.0f)); Assert.That(() => value.Y, Is.EqualTo(0.0f)); Assert.That(() => value.Z, Is.EqualTo(0.0f)); value = Vector3.Create(0.0f, 1.0f, 2.0f); Assert.That(() => value.X, Is.EqualTo(0.0f)); Assert.That(() => value.Y, Is.EqualTo(1.0f)); Assert.That(() => value.Z, Is.EqualTo(2.0f)); value = Vector3.Create(3.0f); Assert.That(() => value.X, Is.EqualTo(3.0f)); Assert.That(() => value.Y, Is.EqualTo(3.0f)); Assert.That(() => value.Z, Is.EqualTo(3.0f)); value = Vector3.Create(Vector2.Create(4.0f, 5.0f), 6.0f); Assert.That(() => value.X, Is.EqualTo(4.0f)); Assert.That(() => value.Y, Is.EqualTo(5.0f)); Assert.That(() => value.Z, Is.EqualTo(6.0f)); value = Vector3.Create(new SysVector3(7.0f, 8.0f, 9.0f)); Assert.That(() => value.X, Is.EqualTo(7.0f)); Assert.That(() => value.Y, Is.EqualTo(8.0f)); Assert.That(() => value.Z, Is.EqualTo(9.0f)); value = Vector3.Create(Vector128.Create(10.0f, 11.0f, 12.0f, 13.0f)); Assert.That(() => value.X, Is.EqualTo(10.0f)); Assert.That(() => value.Y, Is.EqualTo(11.0f)); Assert.That(() => value.Z, Is.EqualTo(12.0f)); } /// <summary>Provides validation of the <see cref="Vector3.Length" /> property.</summary> [Test] public static void LengthTest() { Assert.That(() => Vector3.Create(0.0f, 1.0f, 2.0f).Length, Is.EqualTo(2.236068f) ); } /// <summary>Provides validation of the <see cref="Vector3.LengthSquared" /> property.</summary> [Test] public static void LengthSquaredTest() { Assert.That(() => Vector3.Create(0.0f, 1.0f, 2.0f).LengthSquared, Is.EqualTo(5.0f) ); } /// <summary>Provides validation of the <see cref="Vector3.op_Equality" /> method.</summary> [Test] public static void OpEqualityTest() { Assert.That(() => Vector3.Create(0.0f, 1.0f, 2.0f) == Vector3.Create(0.0f, 1.0f, 2.0f), Is.True ); Assert.That(() => Vector3.Create(0.0f, 1.0f, 2.0f) == Vector3.Create(3.0f, 4.0f, 5.0f), Is.False ); } /// <summary>Provides validation of the <see cref="Vector3.op_Inequality" /> method.</summary> [Test] public static void OpInequalityTest() { Assert.That(() => Vector3.Create(0.0f, 1.0f, 2.0f) != Vector3.Create(0.0f, 1.0f, 2.0f), Is.False ); Assert.That(() => Vector3.Create(0.0f, 1.0f, 2.0f) != Vector3.Create(3.0f, 4.0f, 5.0f), Is.True ); } /// <summary>Provides validation of the <see cref="Vector3.op_UnaryPlus" /> method.</summary> [Test] public static void OpUnaryPlusTest() { Assert.That(() => +Vector3.Create(0.0f, 1.0f, 2.0f), Is.EqualTo(Vector3.Create(0.0f, 1.0f, 2.0f)) ); } /// <summary>Provides validation of the <see cref="Vector3.op_UnaryNegation" /> method.</summary> [Test] public static void OpUnaryNegationTest() { Assert.That(() => -Vector3.Create(1.0f, 2.0f, 3.0f), Is.EqualTo(Vector3.Create(-1.0f, -2.0f, -3.0f)) ); } /// <summary>Provides validation of the <see cref="Vector3.op_Addition" /> method.</summary> [Test] public static void OpAdditionTest() { Assert.That(() => Vector3.Create(0.0f, 1.0f, 2.0f) + Vector3.Create(3.0f, 4.0f, 5.0f), Is.EqualTo(Vector3.Create(3.0f, 5.0f, 7.0f)) ); } /// <summary>Provides validation of the <see cref="Vector3.op_Subtraction" /> method.</summary> [Test] public static void OpSubtractionTest() { Assert.That(() => Vector3.Create(0.0f, 1.0f, 2.0f) - Vector3.Create(3.0f, 4.0f, 5.0f), Is.EqualTo(Vector3.Create(-3.0f, -3.0f, -3.0f)) ); } /// <summary>Provides validation of the <see cref="Vector3.op_Multiply(Vector3, Vector3)" /> method.</summary> [Test] public static void OpMultiplyTest() { Assert.That(() => Vector3.Create(0.0f, 1.0f, 2.0f) * Vector3.Create(3.0f, 4.0f, 5.0f), Is.EqualTo(Vector3.Create(0.0f, 4.0f, 10.0f)) ); Assert.That(() => Vector3.Create(0.0f, 1.0f, 2.0f) * 3.0f, Is.EqualTo(Vector3.Create(0.0f, 3.0f, 6.0f)) ); } /// <summary>Provides validation of the <see cref="Vector3.op_Division(Vector3, Vector3)" /> method.</summary> [Test] public static void OpDivisionTest() { Assert.That(() => Vector3.Create(0.0f, 1.0f, 2.0f) / 3.0f, Is.EqualTo(Vector3.Create(0.0f, 0.33333334f, 0.6666667f)) ); } /// <summary>Provides validation of the <see cref="Vector3.CompareEqualAll(Vector3, Vector3)" /> method.</summary> [Test] public static void CompareEqualAllTest() { Assert.That(() => Vector3.CompareEqualAll(Vector3.Create(0.0f, 1.0f, 2.0f), Vector3.Create(0.0f, 1.0f, 2.0f)), Is.True ); Assert.That(() => Vector3.CompareEqualAll(Vector3.Create(0.0f, 1.0f, 2.0f), Vector3.Create(3.0f, 4.0f, 5.0f)), Is.False ); } /// <summary>Provides validation of the <see cref="Vector3.CrossProduct(Vector3, Vector3)" /> method.</summary> [Test] public static void CrossProductTest() { Assert.That(() => Vector3.CrossProduct(Vector3.Create(0.0f, 1.0f, 2.0f), Vector3.Create(3.0f, 4.0f, 5.0f)), Is.EqualTo(Vector3.Create(-3, 6, -3)) ); } /// <summary>Provides validation of the <see cref="Vector3.DotProduct(Vector3, Vector3)" /> method.</summary> [Test] public static void DotProductTest() { Assert.That(() => Vector3.DotProduct(Vector3.Create(0.0f, 1.0f, 2.0f), Vector3.Create(3.0f, 4.0f, 5.0f)), Is.EqualTo(14.0f) ); } /// <summary>Provides validation of the <see cref="Vector3.IsAnyInfinity(Vector3)" /> method.</summary> [Test] public static void IsAnyInfinityTest() { Assert.That(() => Vector3.IsAnyInfinity(Vector3.Create(0.0f, 1.0f, float.PositiveInfinity)), Is.True ); Assert.That(() => Vector3.IsAnyInfinity(Vector3.Create(0.0f, 1.0f, float.NegativeInfinity)), Is.True ); Assert.That(() => Vector3.IsAnyInfinity(Vector3.Create(0.0f, 1.0f, 2.0f)), Is.False ); } /// <summary>Provides validation of the <see cref="Vector3.IsAnyNaN(Vector3)" /> method.</summary> [Test] public static void IsAnyNaNTest() { Assert.That(() => Vector3.IsAnyNaN(Vector3.Create(0.0f, 1.0f, float.NaN)), Is.True ); Assert.That(() => Vector3.IsAnyNaN(Vector3.Create(0.0f, 1.0f, 2.0f)), Is.False ); } /// <summary>Provides validation of the <see cref="Vector3.Max" /> method.</summary> [Test] public static void MaxTest() { Assert.That(() => Vector3.Max(Vector3.Create(0.0f, 1.0f, 2.0f), Vector3.Create(2.0f, 1.0f, 0.0f)), Is.EqualTo(Vector3.Create(2.0f, 1.0f, 2.0f)) ); } /// <summary>Provides validation of the <see cref="Vector3.Min" /> method.</summary> [Test] public static void MinTest() { Assert.That(() => Vector3.Min(Vector3.Create(-0.0f, -1.0f, -2.0f), Vector3.Create(-2.0f, -1.0f, -0.0f)), Is.EqualTo(Vector3.Create(-2.0f, -1.0f, -2.0f)) ); } /// <summary>Provides validation of the <see cref="Vector3.Normalize" /> method.</summary> [Test] public static void NormalizeTest() { Assert.That(() => Vector3.Normalize(Vector3.Create(0.0f, 1.0f, 2.0f)), Is.EqualTo(Vector3.Create(0.0f, 0.4472136f, 0.8944272f)) ); } /// <summary>Provides validation of the <see cref="Vector3.Rotate(Vector3, Quaternion)" /> method.</summary> [Test] public static void RotateTest() { Assert.That(() => Vector3.Rotate(Vector3.Create(0.0f, 1.0f, 2.0f), Quaternion.Identity), Is.EqualTo(Vector3.Create(0.0f, 1.0f, 2.0f)) ); } /// <summary>Provides validation of the <see cref="Vector3.RotateInverse(Vector3, Quaternion)" /> method.</summary> [Test] public static void RotateInverseTest() { Assert.That(() => Vector3.RotateInverse(Vector3.Create(0.0f, 1.0f, 2.0f), Quaternion.Identity), Is.EqualTo(Vector3.Create(0.0f, 1.0f, 2.0f)) ); } /// <summary>Provides validation of the <see cref="Vector3.Sqrt" /> method.</summary> [Test] public static void SqrtTest() { Assert.That(() => Vector3.Sqrt(Vector3.Create(0.0f, 1.0f, 2.0f)), Is.EqualTo(Vector3.Create(0.0f, 1.0f, 1.4142135f)) ); } /// <summary>Provides validation of the <see cref="Vector3.Transform(Vector3, Matrix4x4)" /> method.</summary> [Test] public static void TransformTest() { Assert.That(() => Vector3.Create(0.0f, 1.0f, 2.0f) * Matrix4x4.Identity, Is.EqualTo(Vector3.Create(0.0f, 1.0f, 2.0f)) ); Assert.That(() => Vector3.Transform(Vector3.Create(0.0f, 1.0f, 2.0f), Matrix4x4.Identity), Is.EqualTo(Vector3.Create(0.0f, 1.0f, 2.0f)) ); } /// <summary>Provides validation of the <see cref="Vector3.TransformNormal(Vector3, Matrix4x4)" /> method.</summary> [Test] public static void TransformNormalTest() { Assert.That(() => Vector3.TransformNormal(Vector3.Create(0.0f, 1.0f, 2.0f), Matrix4x4.Identity), Is.EqualTo(Vector3.Create(0.0f, 1.0f, 2.0f)) ); } /// <summary>Provides validation of the <see cref="Vector3.AsSystemVector3" /> method.</summary> [Test] public static void AsVector3Test() { Assert.That(() => Vector3.Create(0.0f, 1.0f, 2.0f).AsSystemVector3(), Is.EqualTo(new SysVector3(0.0f, 1.0f, 2.0f)) ); } /// <summary>Provides validation of the <see cref="Vector3.AsVector128" /> method.</summary> [Test] public static void AsVector128Test() { Assert.That(() => Vector3.Create(0.0f, 1.0f, 2.0f).AsVector128(), Is.EqualTo(Vector128.Create(0.0f, 1.0f, 2.0f, 0.0f)) ); } /// <summary>Provides validation of the <see cref="Vector3.WithX" /> method.</summary> [Test] public static void WithXTest() { Assert.That(() => Vector3.Create(0.0f, 1.0f, 2.0f).WithX(5.0f), Is.EqualTo(Vector3.Create(5.0f, 1.0f, 2.0f)) ); } /// <summary>Provides validation of the <see cref="Vector3.WithY" /> method.</summary> [Test] public static void WithYTest() { Assert.That(() => Vector3.Create(0.0f, 1.0f, 2.0f).WithY(5.0f), Is.EqualTo(Vector3.Create(0.0f, 5.0f, 2.0f)) ); } /// <summary>Provides validation of the <see cref="Vector3.WithZ" /> method.</summary> [Test] public static void WithZTest() { Assert.That(() => Vector3.Create(0.0f, 1.0f, 2.0f).WithZ(5.0f), Is.EqualTo(Vector3.Create(0.0f, 1.0f, 5.0f)) ); } }
// Copyright 2010-2021 Google LLC // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. namespace Google.OrTools.LinearSolver { using System; using System.Collections.Generic; // Patch the MPVariable class to support the natural language API. public partial class Variable { public static LinearExpr operator +(Variable a, double v) { return new VarWrapper(a) + v; } public static LinearExpr operator +(double v, Variable a) { return a + v; } public static LinearExpr operator +(Variable a, LinearExpr b) { return new VarWrapper(a) + b; } public static LinearExpr operator +(Variable a, Variable b) { return new VarWrapper(a) + new VarWrapper(b); } public static LinearExpr operator +(LinearExpr a, Variable b) { return a + new VarWrapper(b); } public static LinearExpr operator -(Variable a, double v) { return new VarWrapper(a) - v; } public static LinearExpr operator -(double v, Variable a) { return v - new VarWrapper(a); } public static LinearExpr operator -(Variable a, LinearExpr b) { return new VarWrapper(a) - b; } public static LinearExpr operator -(LinearExpr a, Variable b) { return a - new VarWrapper(b); } public static LinearExpr operator -(Variable a, Variable b) { return new VarWrapper(a) - new VarWrapper(b); } public static LinearExpr operator -(Variable a) { return -new VarWrapper(a); } public static LinearExpr operator *(Variable a, double v) { return new VarWrapper(a) * v; } public static LinearExpr operator /(Variable a, double v) { return new VarWrapper(a) / v; } public static LinearExpr operator *(double v, Variable a) { return v * new VarWrapper(a); } public static RangeConstraint operator ==(Variable a, double v) { return new VarWrapper(a) == v; } public static RangeConstraint operator ==(double v, Variable a) { return v == new VarWrapper(a); } public static RangeConstraint operator !=(Variable a, double v) { return new VarWrapper(a) != v; } public static RangeConstraint operator !=(double v, Variable a) { return new VarWrapper(a) != v; } public static Equality operator ==(Variable a, LinearExpr b) { return new VarWrapper(a) == b; } public static Equality operator ==(LinearExpr a, Variable b) { return a == new VarWrapper(b); } public static VarEquality operator ==(Variable a, Variable b) { return new VarEquality(a, b, true); } public static Equality operator !=(Variable a, LinearExpr b) { return new VarWrapper(a) != b; } public static Equality operator !=(LinearExpr a, Variable b) { return a != new VarWrapper(b); } public static VarEquality operator !=(Variable a, Variable b) { return new VarEquality(a, b, false); } public static RangeConstraint operator <=(Variable a, double v) { return new VarWrapper(a) <= v; } public static RangeConstraint operator >=(Variable a, double v) { return new VarWrapper(a) >= v; } public static RangeConstraint operator <=(double v, Variable a) { return new VarWrapper(a) >= v; } public static RangeConstraint operator >=(double v, Variable a) { return new VarWrapper(a) <= v; } public static RangeConstraint operator <=(Variable a, LinearExpr b) { return new VarWrapper(a) <= b; } public static RangeConstraint operator >=(Variable a, LinearExpr b) { return new VarWrapper(a) >= b; } public static RangeConstraint operator <=(Variable a, Variable b) { return new VarWrapper(a) <= new VarWrapper(b); } public static RangeConstraint operator >=(Variable a, Variable b) { return new VarWrapper(a) >= new VarWrapper(b); } public static RangeConstraint operator <=(LinearExpr a, Variable b) { return a <= new VarWrapper(b); } public static RangeConstraint operator >=(LinearExpr a, Variable b) { return a >= new VarWrapper(b); } } // TODO(user): Try to move this code back to the .swig with @define macros. public partial class MPVariableVector : IDisposable, System.Collections.IEnumerable #if !SWIG_DOTNET_1 , System.Collections.Generic.IList<Variable> #endif { // cast from C# MPVariable array public static implicit operator MPVariableVector(Variable[] inVal) { var outVal = new MPVariableVector(); foreach (Variable element in inVal) { outVal.Add(element); } return outVal; } // cast to C# MPVariable array public static implicit operator Variable[](MPVariableVector inVal) { var outVal = new Variable[inVal.Count]; inVal.CopyTo(outVal); return outVal; } } } // namespace Google.OrTools.LinearSolver
namespace Antlr.Runtime { using System.Collections.Generic; using ArgumentNullException = System.ArgumentNullException; using Array = System.Array; using Conditional = System.Diagnostics.ConditionalAttribute; using IDebugEventListener = Antlr.Runtime.Debug.IDebugEventListener; using MethodBase = System.Reflection.MethodBase; using Regex = System.Text.RegularExpressions.Regex; using StackFrame = System.Diagnostics.StackFrame; using StackTrace = System.Diagnostics.StackTrace; using TextWriter = System.IO.TextWriter; internal abstract class BaseRecognizer { public const int MemoRuleFailed = -2; public const int MemoRuleUnknown = -1; public const int InitialFollowStackSize = 100; // copies from Token object for convenience in actions public const int DefaultTokenChannel = TokenChannels.Default; public const int Hidden = TokenChannels.Hidden; public const string NextTokenRuleName = "nextToken"; protected internal RecognizerSharedState state; public BaseRecognizer() : this(new RecognizerSharedState()) { } public BaseRecognizer( RecognizerSharedState state ) { if ( state == null ) { state = new RecognizerSharedState(); } this.state = state; InitDFAs(); } public TextWriter TraceDestination { get; set; } public virtual void SetState(RecognizerSharedState value) { this.state = value; } protected virtual void InitDFAs() { } public virtual void Reset() { // wack everything related to error recovery if ( state == null ) { return; // no shared state work to do } state._fsp = -1; state.errorRecovery = false; state.lastErrorIndex = -1; state.failed = false; state.syntaxErrors = 0; // wack everything related to backtracking and memoization state.backtracking = 0; for ( int i = 0; state.ruleMemo != null && i < state.ruleMemo.Length; i++ ) { // wipe cache state.ruleMemo[i] = null; } } public virtual object Match( IIntStream input, int ttype, BitSet follow ) { //System.out.println("match "+((TokenStream)input).LT(1)); object matchedSymbol = GetCurrentInputSymbol( input ); if ( input.LA( 1 ) == ttype ) { input.Consume(); state.errorRecovery = false; state.failed = false; return matchedSymbol; } if ( state.backtracking > 0 ) { state.failed = true; return matchedSymbol; } matchedSymbol = RecoverFromMismatchedToken( input, ttype, follow ); return matchedSymbol; } public virtual void MatchAny( IIntStream input ) { state.errorRecovery = false; state.failed = false; input.Consume(); } public virtual bool MismatchIsUnwantedToken( IIntStream input, int ttype ) { return input.LA( 2 ) == ttype; } public virtual bool MismatchIsMissingToken( IIntStream input, BitSet follow ) { if ( follow == null ) { // we have no information about the follow; we can only consume // a single token and hope for the best return false; } // compute what can follow this grammar element reference if ( follow.Member( TokenTypes.EndOfRule ) ) { BitSet viableTokensFollowingThisRule = ComputeContextSensitiveRuleFOLLOW(); follow = follow.Or( viableTokensFollowingThisRule ); if ( state._fsp >= 0 ) { // remove EOR if we're not the start symbol follow.Remove( TokenTypes.EndOfRule ); } } // if current token is consistent with what could come after set // then we know we're missing a token; error recovery is free to // "insert" the missing token //System.out.println("viable tokens="+follow.toString(getTokenNames())); //System.out.println("LT(1)="+((TokenStream)input).LT(1)); // BitSet cannot handle negative numbers like -1 (EOF) so I leave EOR // in follow set to indicate that the fall of the start symbol is // in the set (EOF can follow). if ( follow.Member( input.LA( 1 ) ) || follow.Member( TokenTypes.EndOfRule ) ) { //System.out.println("LT(1)=="+((TokenStream)input).LT(1)+" is consistent with what follows; inserting..."); return true; } return false; } public virtual void ReportError( RecognitionException e ) { // if we've already reported an error and have not matched a token // yet successfully, don't report any errors. if ( state.errorRecovery ) { //System.err.print("[SPURIOUS] "); return; } state.syntaxErrors++; // don't count spurious state.errorRecovery = true; DisplayRecognitionError( this.TokenNames, e ); } public virtual void DisplayRecognitionError( string[] tokenNames, RecognitionException e ) { string hdr = GetErrorHeader( e ); string msg = GetErrorMessage( e, tokenNames ); EmitErrorMessage( hdr + " " + msg ); } public virtual string GetErrorMessage( RecognitionException e, string[] tokenNames ) { string msg = e.Message; if ( e is UnwantedTokenException ) { UnwantedTokenException ute = (UnwantedTokenException)e; string tokenName = "<unknown>"; if ( ute.Expecting == TokenTypes.EndOfFile ) { tokenName = "EndOfFile"; } else { tokenName = tokenNames[ute.Expecting]; } msg = "extraneous input " + GetTokenErrorDisplay( ute.UnexpectedToken ) + " expecting " + tokenName; } else if ( e is MissingTokenException ) { MissingTokenException mte = (MissingTokenException)e; string tokenName = "<unknown>"; if ( mte.Expecting == TokenTypes.EndOfFile ) { tokenName = "EndOfFile"; } else { tokenName = tokenNames[mte.Expecting]; } msg = "missing " + tokenName + " at " + GetTokenErrorDisplay( e.Token ); } else if ( e is MismatchedTokenException ) { MismatchedTokenException mte = (MismatchedTokenException)e; string tokenName = "<unknown>"; if ( mte.Expecting == TokenTypes.EndOfFile ) { tokenName = "EndOfFile"; } else { tokenName = tokenNames[mte.Expecting]; } msg = "mismatched input " + GetTokenErrorDisplay( e.Token ) + " expecting " + tokenName; } else if ( e is MismatchedTreeNodeException ) { MismatchedTreeNodeException mtne = (MismatchedTreeNodeException)e; string tokenName = "<unknown>"; if ( mtne.Expecting == TokenTypes.EndOfFile ) { tokenName = "EndOfFile"; } else { tokenName = tokenNames[mtne.Expecting]; } // workaround for a .NET framework bug (NullReferenceException) string nodeText = ( mtne.Node != null ) ? mtne.Node.ToString() ?? string.Empty : string.Empty; msg = "mismatched tree node: " + nodeText + " expecting " + tokenName; } else if ( e is NoViableAltException ) { //NoViableAltException nvae = (NoViableAltException)e; // for development, can add "decision=<<"+nvae.grammarDecisionDescription+">>" // and "(decision="+nvae.decisionNumber+") and // "state "+nvae.stateNumber msg = "no viable alternative at input " + GetTokenErrorDisplay( e.Token ); } else if ( e is EarlyExitException ) { //EarlyExitException eee = (EarlyExitException)e; // for development, can add "(decision="+eee.decisionNumber+")" msg = "required (...)+ loop did not match anything at input " + GetTokenErrorDisplay( e.Token ); } else if ( e is MismatchedSetException ) { MismatchedSetException mse = (MismatchedSetException)e; msg = "mismatched input " + GetTokenErrorDisplay( e.Token ) + " expecting set " + mse.Expecting; } else if ( e is MismatchedNotSetException ) { MismatchedNotSetException mse = (MismatchedNotSetException)e; msg = "mismatched input " + GetTokenErrorDisplay( e.Token ) + " expecting set " + mse.Expecting; } else if ( e is FailedPredicateException ) { FailedPredicateException fpe = (FailedPredicateException)e; msg = "rule " + fpe.RuleName + " failed predicate: {" + fpe.PredicateText + "}?"; } return msg; } public virtual int NumberOfSyntaxErrors { get { return state.syntaxErrors; } } public virtual string GetErrorHeader( RecognitionException e ) { string prefix = SourceName ?? string.Empty; if (prefix.Length > 0) prefix += ' '; return string.Format("{0}line {1}:{2}", prefix, e.Line, e.CharPositionInLine + 1); } public virtual string GetTokenErrorDisplay( IToken t ) { string s = t.Text; if ( s == null ) { if ( t.Type == TokenTypes.EndOfFile ) { s = "<EOF>"; } else { s = "<" + t.Type + ">"; } } s = Regex.Replace( s, "\n", "\\\\n" ); s = Regex.Replace( s, "\r", "\\\\r" ); s = Regex.Replace( s, "\t", "\\\\t" ); return "'" + s + "'"; } public virtual void EmitErrorMessage( string msg ) { if (TraceDestination != null) TraceDestination.WriteLine( msg ); } public virtual void Recover( IIntStream input, RecognitionException re ) { if ( state.lastErrorIndex == input.Index ) { // uh oh, another error at same token index; must be a case // where LT(1) is in the recovery token set so nothing is // consumed; consume a single token so at least to prevent // an infinite loop; this is a failsafe. input.Consume(); } state.lastErrorIndex = input.Index; BitSet followSet = ComputeErrorRecoverySet(); BeginResync(); ConsumeUntil( input, followSet ); EndResync(); } public virtual void BeginResync() { } public virtual void EndResync() { } protected virtual BitSet ComputeErrorRecoverySet() { return CombineFollows( false ); } protected virtual BitSet ComputeContextSensitiveRuleFOLLOW() { return CombineFollows( true ); } // what is exact? it seems to only add sets from above on stack // if EOR is in set i. When it sees a set w/o EOR, it stops adding. // Why would we ever want them all? Maybe no viable alt instead of // mismatched token? protected virtual BitSet CombineFollows(bool exact) { int top = state._fsp; BitSet followSet = new BitSet(); for ( int i = top; i >= 0; i-- ) { BitSet localFollowSet = (BitSet)state.following[i]; followSet.OrInPlace( localFollowSet ); if ( exact ) { // can we see end of rule? if ( localFollowSet.Member( TokenTypes.EndOfRule ) ) { // Only leave EOR in set if at top (start rule); this lets // us know if have to include follow(start rule); i.e., EOF if ( i > 0 ) { followSet.Remove( TokenTypes.EndOfRule ); } } else { // can't see end of rule, quit break; } } } return followSet; } protected virtual object RecoverFromMismatchedToken( IIntStream input, int ttype, BitSet follow ) { RecognitionException e = null; // if next token is what we are looking for then "delete" this token if ( MismatchIsUnwantedToken( input, ttype ) ) { e = new UnwantedTokenException( ttype, input, TokenNames ); BeginResync(); input.Consume(); // simply delete extra token EndResync(); ReportError( e ); // report after consuming so AW sees the token in the exception // we want to return the token we're actually matching object matchedSymbol = GetCurrentInputSymbol( input ); input.Consume(); // move past ttype token as if all were ok return matchedSymbol; } // can't recover with single token deletion, try insertion if ( MismatchIsMissingToken( input, follow ) ) { object inserted = GetMissingSymbol( input, e, ttype, follow ); e = new MissingTokenException( ttype, input, inserted ); ReportError( e ); // report after inserting so AW sees the token in the exception return inserted; } // even that didn't work; must throw the exception e = new MismatchedTokenException(ttype, input, TokenNames); throw e; } public virtual object RecoverFromMismatchedSet( IIntStream input, RecognitionException e, BitSet follow ) { if ( MismatchIsMissingToken( input, follow ) ) { // System.out.println("missing token"); ReportError( e ); // we don't know how to conjure up a token for sets yet return GetMissingSymbol( input, e, TokenTypes.Invalid, follow ); } // TODO do single token deletion like above for Token mismatch throw e; } protected virtual object GetCurrentInputSymbol( IIntStream input ) { return null; } protected virtual object GetMissingSymbol( IIntStream input, RecognitionException e, int expectedTokenType, BitSet follow ) { return null; } public virtual void ConsumeUntil( IIntStream input, int tokenType ) { //System.out.println("consumeUntil "+tokenType); int ttype = input.LA( 1 ); while ( ttype != TokenTypes.EndOfFile && ttype != tokenType ) { input.Consume(); ttype = input.LA( 1 ); } } public virtual void ConsumeUntil( IIntStream input, BitSet set ) { //System.out.println("consumeUntil("+set.toString(getTokenNames())+")"); int ttype = input.LA( 1 ); while ( ttype != TokenTypes.EndOfFile && !set.Member( ttype ) ) { //System.out.println("consume during recover LA(1)="+getTokenNames()[input.LA(1)]); input.Consume(); ttype = input.LA( 1 ); } } protected void PushFollow( BitSet fset ) { if ( ( state._fsp + 1 ) >= state.following.Length ) { Array.Resize(ref state.following, state.following.Length * 2); } state.following[++state._fsp] = fset; } protected void PopFollow() { state._fsp--; } public virtual IList<string> GetRuleInvocationStack() { return GetRuleInvocationStack( new StackTrace( #if !SILVERLIGHT true #endif ) ); } public static IList<string> GetRuleInvocationStack(StackTrace trace) { if (trace == null) throw new ArgumentNullException("trace"); List<string> rules = new List<string>(); StackFrame[] stack = trace.GetFrames() ?? new StackFrame[0]; for (int i = stack.Length - 1; i >= 0; i--) { StackFrame frame = stack[i]; MethodBase method = frame.GetMethod(); GrammarRuleAttribute[] attributes = (GrammarRuleAttribute[])method.GetCustomAttributes(typeof(GrammarRuleAttribute), true); if (attributes != null && attributes.Length > 0) rules.Add(attributes[0].Name); } return rules; } public virtual int BacktrackingLevel { get { return state.backtracking; } set { state.backtracking = value; } } public virtual bool Failed { get { return state.failed; } } public virtual string[] TokenNames { get { return null; } } public virtual string GrammarFileName { get { return null; } } public abstract string SourceName { get; } public virtual List<string> ToStrings( ICollection<IToken> tokens ) { if ( tokens == null ) return null; List<string> strings = new List<string>( tokens.Count ); foreach ( IToken token in tokens ) { strings.Add( token.Text ); } return strings; } public virtual int GetRuleMemoization( int ruleIndex, int ruleStartIndex ) { if ( state.ruleMemo[ruleIndex] == null ) { state.ruleMemo[ruleIndex] = new Dictionary<int, int>(); } int stopIndex; if ( !state.ruleMemo[ruleIndex].TryGetValue( ruleStartIndex, out stopIndex ) ) return MemoRuleUnknown; return stopIndex; } public virtual bool AlreadyParsedRule( IIntStream input, int ruleIndex ) { int stopIndex = GetRuleMemoization( ruleIndex, input.Index ); if ( stopIndex == MemoRuleUnknown ) { return false; } if ( stopIndex == MemoRuleFailed ) { //System.out.println("rule "+ruleIndex+" will never succeed"); state.failed = true; } else { //System.out.println("seen rule "+ruleIndex+" before; skipping ahead to @"+(stopIndex+1)+" failed="+state.failed); input.Seek( stopIndex + 1 ); // jump to one past stop token } return true; } public virtual void Memoize( IIntStream input, int ruleIndex, int ruleStartIndex ) { int stopTokenIndex = state.failed ? MemoRuleFailed : input.Index - 1; if ( state.ruleMemo == null ) { if (TraceDestination != null) TraceDestination.WriteLine( "!!!!!!!!! memo array is null for " + GrammarFileName ); } if ( ruleIndex >= state.ruleMemo.Length ) { if (TraceDestination != null) TraceDestination.WriteLine("!!!!!!!!! memo size is " + state.ruleMemo.Length + ", but rule index is " + ruleIndex); } if ( state.ruleMemo[ruleIndex] != null ) { state.ruleMemo[ruleIndex][ruleStartIndex] = stopTokenIndex; } } public virtual int GetRuleMemoizationCacheSize() { int n = 0; for ( int i = 0; state.ruleMemo != null && i < state.ruleMemo.Length; i++ ) { var ruleMap = state.ruleMemo[i]; if ( ruleMap != null ) { n += ruleMap.Count; // how many input indexes are recorded? } } return n; } public virtual void TraceIn(string ruleName, int ruleIndex, object inputSymbol) { if (TraceDestination == null) return; TraceDestination.Write("enter " + ruleName + " " + inputSymbol); if (state.backtracking > 0) { TraceDestination.Write(" backtracking=" + state.backtracking); } TraceDestination.WriteLine(); } public virtual void TraceOut(string ruleName, int ruleIndex, object inputSymbol) { if (TraceDestination == null) return; TraceDestination.Write("exit " + ruleName + " " + inputSymbol); if (state.backtracking > 0) { TraceDestination.Write(" backtracking=" + state.backtracking); if (state.failed) TraceDestination.Write(" failed"); else TraceDestination.Write(" succeeded"); } TraceDestination.WriteLine(); } #region Debugging support public virtual IDebugEventListener DebugListener { get { return null; } } [Conditional("ANTLR_DEBUG")] protected virtual void DebugEnterRule(string grammarFileName, string ruleName) { IDebugEventListener dbg = DebugListener; if (dbg != null) dbg.EnterRule(grammarFileName, ruleName); } [Conditional("ANTLR_DEBUG")] protected virtual void DebugExitRule(string grammarFileName, string ruleName) { IDebugEventListener dbg = DebugListener; if (dbg != null) dbg.ExitRule(grammarFileName, ruleName); } [Conditional("ANTLR_DEBUG")] protected virtual void DebugEnterSubRule(int decisionNumber) { IDebugEventListener dbg = DebugListener; if (dbg != null) dbg.EnterSubRule(decisionNumber); } [Conditional("ANTLR_DEBUG")] protected virtual void DebugExitSubRule(int decisionNumber) { IDebugEventListener dbg = DebugListener; if (dbg != null) dbg.ExitSubRule(decisionNumber); } [Conditional("ANTLR_DEBUG")] protected virtual void DebugEnterAlt(int alt) { IDebugEventListener dbg = DebugListener; if (dbg != null) dbg.EnterAlt(alt); } [Conditional("ANTLR_DEBUG")] protected virtual void DebugEnterDecision(int decisionNumber, bool couldBacktrack) { IDebugEventListener dbg = DebugListener; if (dbg != null) dbg.EnterDecision(decisionNumber, couldBacktrack); } [Conditional("ANTLR_DEBUG")] protected virtual void DebugExitDecision(int decisionNumber) { IDebugEventListener dbg = DebugListener; if (dbg != null) dbg.ExitDecision(decisionNumber); } [Conditional("ANTLR_DEBUG")] protected virtual void DebugLocation(int line, int charPositionInLine) { IDebugEventListener dbg = DebugListener; if (dbg != null) dbg.Location(line, charPositionInLine); } [Conditional("ANTLR_DEBUG")] protected virtual void DebugSemanticPredicate(bool result, string predicate) { IDebugEventListener dbg = DebugListener; if (dbg != null) dbg.SemanticPredicate(result, predicate); } [Conditional("ANTLR_DEBUG")] protected virtual void DebugBeginBacktrack(int level) { IDebugEventListener dbg = DebugListener; if (dbg != null) dbg.BeginBacktrack(level); } [Conditional("ANTLR_DEBUG")] protected virtual void DebugEndBacktrack(int level, bool successful) { IDebugEventListener dbg = DebugListener; if (dbg != null) dbg.EndBacktrack(level, successful); } [Conditional("ANTLR_DEBUG")] protected virtual void DebugRecognitionException(RecognitionException ex) { IDebugEventListener dbg = DebugListener; if (dbg != null) dbg.RecognitionException(ex); } #endregion } }
using System; using UnityEngine; using System.Collections.Generic; using System.Collections; using CommandUndoRedo; namespace RuntimeGizmos { //To be safe, if you are changing any transforms hierarchy, such as parenting an object to something, //you should call ClearTargets before doing so just to be sure nothing unexpected happens... as well as call UndoRedoManager.Clear() //For example, if you select an object that has children, move the children elsewhere, deselect the original object, then try to add those old children to the selection, I think it wont work. [RequireComponent(typeof(Camera))] public class TransformGizmo : MonoBehaviour { public TransformSpace space = TransformSpace.Global; public TransformType transformType = TransformType.Move; public TransformPivot pivot = TransformPivot.Pivot; public CenterType centerType = CenterType.All; public ScaleType scaleType = ScaleType.FromPoint; //These are the same as the unity editor hotkeys public KeyCode SetMoveType = KeyCode.W; public KeyCode SetRotateType = KeyCode.E; public KeyCode SetScaleType = KeyCode.R; //public KeyCode SetRectToolType = KeyCode.T; public KeyCode SetAllTransformType = KeyCode.Y; public KeyCode SetSpaceToggle = KeyCode.X; public KeyCode SetPivotModeToggle = KeyCode.Z; public KeyCode SetCenterTypeToggle = KeyCode.C; public KeyCode SetScaleTypeToggle = KeyCode.S; public KeyCode translationSnapping = KeyCode.LeftControl; public KeyCode AddSelection = KeyCode.LeftShift; public KeyCode RemoveSelection = KeyCode.LeftControl; public KeyCode ActionKey = KeyCode.LeftShift; //Its set to shift instead of control so that while in the editor we dont accidentally undo editor changes =/ public KeyCode UndoAction = KeyCode.Z; public KeyCode RedoAction = KeyCode.Y; public Color xColor = new Color(1, 0, 0, 0.8f); public Color yColor = new Color(0, 1, 0, 0.8f); public Color zColor = new Color(0, 0, 1, 0.8f); public Color allColor = new Color(.7f, .7f, .7f, 0.8f); public Color selectedColor = new Color(1, 1, 0, 0.8f); public Color hoverColor = new Color(1, .75f, 0, 0.8f); public float planesOpacity = .5f; //public Color rectPivotColor = new Color(0, 0, 1, 0.8f); //public Color rectCornerColor = new Color(0, 0, 1, 0.8f); //public Color rectAnchorColor = new Color(.7f, .7f, .7f, 0.8f); //public Color rectLineColor = new Color(.7f, .7f, .7f, 0.8f); public float movementSnap = .25f; public float rotationSnap = 15f; public float scaleSnap = 1f; public float handleLength = .25f; public float handleWidth = .003f; public float planeSize = .035f; public float triangleSize = .03f; public float boxSize = .03f; public int circleDetail = 40; public float allMoveHandleLengthMultiplier = 1f; public float allRotateHandleLengthMultiplier = 1.4f; public float allScaleHandleLengthMultiplier = 1.6f; public float minSelectedDistanceCheck = .01f; public float moveSpeedMultiplier = 1f; public float scaleSpeedMultiplier = 1f; public float rotateSpeedMultiplier = 1f; public float allRotateSpeedMultiplier = 20f; public bool useFirstSelectedAsMain = true; //If circularRotationMethod is true, when rotating you will need to move your mouse around the object as if turning a wheel. //If circularRotationMethod is false, when rotating you can just click and drag in a line to rotate. public bool circularRotationMethod; //Mainly for if you want the pivot point to update correctly if selected objects are moving outside the transformgizmo. //Might be poor on performance if lots of objects are selected... public bool forceUpdatePivotPointOnChange = true; public int maxUndoStored = 100; public bool manuallyHandleGizmo; public LayerMask selectionMask = Physics.DefaultRaycastLayers; public Action onCheckForSelectedAxis; public Action onDrawCustomGizmo; public Camera myCamera {get; private set;} public bool isTransforming {get; private set;} public float totalScaleAmount {get; private set;} public Quaternion totalRotationAmount {get; private set;} public Axis translatingAxis {get {return nearAxis;}} public Axis translatingAxisPlane {get {return planeAxis;}} public bool hasTranslatingAxisPlane {get {return translatingAxisPlane != Axis.None && translatingAxisPlane != Axis.Any;}} public TransformType transformingType {get {return translatingType;}} public Vector3 pivotPoint {get; private set;} Vector3 totalCenterPivotPoint; public Transform mainTargetRoot {get {return (targetRootsOrdered.Count > 0) ? (useFirstSelectedAsMain) ? targetRootsOrdered[0] : targetRootsOrdered[targetRootsOrdered.Count - 1] : null;}} AxisInfo axisInfo; Axis nearAxis = Axis.None; Axis planeAxis = Axis.None; TransformType translatingType; AxisVectors handleLines = new AxisVectors(); AxisVectors handlePlanes = new AxisVectors(); AxisVectors handleTriangles = new AxisVectors(); AxisVectors handleSquares = new AxisVectors(); AxisVectors circlesLines = new AxisVectors(); //We use a HashSet and a List for targetRoots so that we get fast lookup with the hashset while also keeping track of the order with the list. List<Transform> targetRootsOrdered = new List<Transform>(); Dictionary<Transform, TargetInfo> targetRoots = new Dictionary<Transform, TargetInfo>(); HashSet<Renderer> highlightedRenderers = new HashSet<Renderer>(); HashSet<Transform> children = new HashSet<Transform>(); List<Transform> childrenBuffer = new List<Transform>(); List<Renderer> renderersBuffer = new List<Renderer>(); List<Material> materialsBuffer = new List<Material>(); WaitForEndOfFrame waitForEndOFFrame = new WaitForEndOfFrame(); Coroutine forceUpdatePivotCoroutine; static Material lineMaterial; static Material outlineMaterial; void Awake() { myCamera = GetComponent<Camera>(); SetMaterial(); } void OnEnable() { forceUpdatePivotCoroutine = StartCoroutine(ForceUpdatePivotPointAtEndOfFrame()); } void OnDisable() { ClearTargets(); //Just so things gets cleaned up, such as removing any materials we placed on objects. StopCoroutine(forceUpdatePivotCoroutine); } void OnDestroy() { ClearAllHighlightedRenderers(); } void Update() { HandleUndoRedo(); SetSpaceAndType(); if(manuallyHandleGizmo) { if(onCheckForSelectedAxis != null) onCheckForSelectedAxis(); }else{ SetNearAxis(); } GetTarget(); if(mainTargetRoot == null) return; TransformSelected(); } void LateUpdate() { if(mainTargetRoot == null) return; //We run this in lateupdate since coroutines run after update and we want our gizmos to have the updated target transform position after TransformSelected() SetAxisInfo(); if(manuallyHandleGizmo) { if(onDrawCustomGizmo != null) onDrawCustomGizmo(); }else{ SetLines(); } } void OnPostRender() { if(mainTargetRoot == null || manuallyHandleGizmo) return; lineMaterial.SetPass(0); Color xColor = (nearAxis == Axis.X) ? (isTransforming) ? selectedColor : hoverColor : this.xColor; Color yColor = (nearAxis == Axis.Y) ? (isTransforming) ? selectedColor : hoverColor : this.yColor; Color zColor = (nearAxis == Axis.Z) ? (isTransforming) ? selectedColor : hoverColor : this.zColor; Color allColor = (nearAxis == Axis.Any) ? (isTransforming) ? selectedColor : hoverColor : this.allColor; //Note: The order of drawing the axis decides what gets drawn over what. TransformType moveOrScaleType = (transformType == TransformType.Scale || (isTransforming && translatingType == TransformType.Scale)) ? TransformType.Scale : TransformType.Move; DrawQuads(handleLines.z, GetColor(moveOrScaleType, this.zColor, zColor, hasTranslatingAxisPlane)); DrawQuads(handleLines.x, GetColor(moveOrScaleType, this.xColor, xColor, hasTranslatingAxisPlane)); DrawQuads(handleLines.y, GetColor(moveOrScaleType, this.yColor, yColor, hasTranslatingAxisPlane)); DrawTriangles(handleTriangles.x, GetColor(TransformType.Move, this.xColor, xColor, hasTranslatingAxisPlane)); DrawTriangles(handleTriangles.y, GetColor(TransformType.Move, this.yColor, yColor, hasTranslatingAxisPlane)); DrawTriangles(handleTriangles.z, GetColor(TransformType.Move, this.zColor, zColor, hasTranslatingAxisPlane)); DrawQuads(handlePlanes.z, GetColor(TransformType.Move, this.zColor, zColor, planesOpacity, !hasTranslatingAxisPlane)); DrawQuads(handlePlanes.x, GetColor(TransformType.Move, this.xColor, xColor, planesOpacity, !hasTranslatingAxisPlane)); DrawQuads(handlePlanes.y, GetColor(TransformType.Move, this.yColor, yColor, planesOpacity, !hasTranslatingAxisPlane)); DrawQuads(handleSquares.x, GetColor(TransformType.Scale, this.xColor, xColor)); DrawQuads(handleSquares.y, GetColor(TransformType.Scale, this.yColor, yColor)); DrawQuads(handleSquares.z, GetColor(TransformType.Scale, this.zColor, zColor)); DrawQuads(handleSquares.all, GetColor(TransformType.Scale, this.allColor, allColor)); DrawQuads(circlesLines.all, GetColor(TransformType.Rotate, this.allColor, allColor)); DrawQuads(circlesLines.x, GetColor(TransformType.Rotate, this.xColor, xColor)); DrawQuads(circlesLines.y, GetColor(TransformType.Rotate, this.yColor, yColor)); DrawQuads(circlesLines.z, GetColor(TransformType.Rotate, this.zColor, zColor)); } Color GetColor(TransformType type, Color normalColor, Color nearColor, bool forceUseNormal = false) { return GetColor(type, normalColor, nearColor, false, 1, forceUseNormal); } Color GetColor(TransformType type, Color normalColor, Color nearColor, float alpha, bool forceUseNormal = false) { return GetColor(type, normalColor, nearColor, true, alpha, forceUseNormal); } Color GetColor(TransformType type, Color normalColor, Color nearColor, bool setAlpha, float alpha, bool forceUseNormal = false) { Color color; if(!forceUseNormal && TranslatingTypeContains(type, false)) { color = nearColor; }else{ color = normalColor; } if(setAlpha) { color.a = alpha; } return color; } void HandleUndoRedo() { if(maxUndoStored != UndoRedoManager.maxUndoStored) { UndoRedoManager.maxUndoStored = maxUndoStored; } if(Input.GetKey(ActionKey)) { if(Input.GetKeyDown(UndoAction)) { UndoRedoManager.Undo(); } else if(Input.GetKeyDown(RedoAction)) { UndoRedoManager.Redo(); } } } //We only support scaling in local space. public TransformSpace GetProperTransformSpace() { return transformType == TransformType.Scale ? TransformSpace.Local : space; } public bool TransformTypeContains(TransformType type) { return TransformTypeContains(transformType, type); } public bool TranslatingTypeContains(TransformType type, bool checkIsTransforming = true) { TransformType transType = !checkIsTransforming || isTransforming ? translatingType : transformType; return TransformTypeContains(transType, type); } public bool TransformTypeContains(TransformType mainType, TransformType type) { return ExtTransformType.TransformTypeContains(mainType, type, GetProperTransformSpace()); } public float GetHandleLength(TransformType type, Axis axis = Axis.None, bool multiplyDistanceMultiplier = true) { float length = handleLength; if(transformType == TransformType.All) { if(type == TransformType.Move) length *= allMoveHandleLengthMultiplier; if(type == TransformType.Rotate) length *= allRotateHandleLengthMultiplier; if(type == TransformType.Scale) length *= allScaleHandleLengthMultiplier; } if(multiplyDistanceMultiplier) length *= GetDistanceMultiplier(); if(type == TransformType.Scale && isTransforming && (translatingAxis == axis || translatingAxis == Axis.Any)) length += totalScaleAmount; return length; } void SetSpaceAndType() { if(Input.GetKey(ActionKey)) return; if(Input.GetKeyDown(SetMoveType)) transformType = TransformType.Move; else if(Input.GetKeyDown(SetRotateType)) transformType = TransformType.Rotate; else if(Input.GetKeyDown(SetScaleType)) transformType = TransformType.Scale; //else if(Input.GetKeyDown(SetRectToolType)) type = TransformType.RectTool; else if(Input.GetKeyDown(SetAllTransformType)) transformType = TransformType.All; if(!isTransforming) translatingType = transformType; if(Input.GetKeyDown(SetPivotModeToggle)) { if(pivot == TransformPivot.Pivot) pivot = TransformPivot.Center; else if(pivot == TransformPivot.Center) pivot = TransformPivot.Pivot; SetPivotPoint(); } if(Input.GetKeyDown(SetCenterTypeToggle)) { if(centerType == CenterType.All) centerType = CenterType.Solo; else if(centerType == CenterType.Solo) centerType = CenterType.All; SetPivotPoint(); } if(Input.GetKeyDown(SetSpaceToggle)) { if(space == TransformSpace.Global) space = TransformSpace.Local; else if(space == TransformSpace.Local) space = TransformSpace.Global; } if(Input.GetKeyDown(SetScaleTypeToggle)) { if(scaleType == ScaleType.FromPoint) scaleType = ScaleType.FromPointOffset; else if(scaleType == ScaleType.FromPointOffset) scaleType = ScaleType.FromPoint; } if(transformType == TransformType.Scale) { if(pivot == TransformPivot.Pivot) scaleType = ScaleType.FromPoint; //FromPointOffset can be inaccurate and should only really be used in Center mode if desired. } } void TransformSelected() { if(mainTargetRoot != null) { if(nearAxis != Axis.None && Input.GetMouseButtonDown(0)) { StartCoroutine(TransformSelected(translatingType)); } } } IEnumerator TransformSelected(TransformType transType) { isTransforming = true; totalScaleAmount = 0; totalRotationAmount = Quaternion.identity; Vector3 originalPivot = pivotPoint; Vector3 otherAxis1, otherAxis2; Vector3 axis = GetNearAxisDirection(out otherAxis1, out otherAxis2); Vector3 planeNormal = hasTranslatingAxisPlane ? axis : (transform.position - originalPivot).normalized; Vector3 projectedAxis = Vector3.ProjectOnPlane(axis, planeNormal).normalized; Vector3 previousMousePosition = Vector3.zero; Vector3 currentSnapMovementAmount = Vector3.zero; float currentSnapRotationAmount = 0; float currentSnapScaleAmount = 0; List<ICommand> transformCommands = new List<ICommand>(); for(int i = 0; i < targetRootsOrdered.Count; i++) { transformCommands.Add(new TransformCommand(this, targetRootsOrdered[i])); } while(!Input.GetMouseButtonUp(0)) { Ray mouseRay = myCamera.ScreenPointToRay(Input.mousePosition); Vector3 mousePosition = Geometry.LinePlaneIntersect(mouseRay.origin, mouseRay.direction, originalPivot, planeNormal); bool isSnapping = Input.GetKey(translationSnapping); if(previousMousePosition != Vector3.zero && mousePosition != Vector3.zero) { if(transType == TransformType.Move) { Vector3 movement = Vector3.zero; if(hasTranslatingAxisPlane) { movement = mousePosition - previousMousePosition; }else{ float moveAmount = ExtVector3.MagnitudeInDirection(mousePosition - previousMousePosition, projectedAxis) * moveSpeedMultiplier; movement = axis * moveAmount; } if(isSnapping && movementSnap > 0) { currentSnapMovementAmount += movement; movement = Vector3.zero; if(hasTranslatingAxisPlane) { float amountInAxis1 = ExtVector3.MagnitudeInDirection(currentSnapMovementAmount, otherAxis1); float amountInAxis2 = ExtVector3.MagnitudeInDirection(currentSnapMovementAmount, otherAxis2); float remainder1; float snapAmount1 = CalculateSnapAmount(movementSnap, amountInAxis1, out remainder1); float remainder2; float snapAmount2 = CalculateSnapAmount(movementSnap, amountInAxis2, out remainder2); if(snapAmount1 != 0) { Vector3 snapMove = (otherAxis1 * snapAmount1); movement += snapMove; currentSnapMovementAmount -= snapMove; } if(snapAmount2 != 0) { Vector3 snapMove = (otherAxis2 * snapAmount2); movement += snapMove; currentSnapMovementAmount -= snapMove; } } else { float remainder; float snapAmount = CalculateSnapAmount(movementSnap, currentSnapMovementAmount.magnitude, out remainder); if(snapAmount != 0) { movement = currentSnapMovementAmount.normalized * snapAmount; currentSnapMovementAmount = currentSnapMovementAmount.normalized * remainder; } } } for(int i = 0; i < targetRootsOrdered.Count; i++) { Transform target = targetRootsOrdered[i]; target.Translate(movement, Space.World); } SetPivotPointOffset(movement); } else if(transType == TransformType.Scale) { Vector3 projected = (nearAxis == Axis.Any) ? transform.right : projectedAxis; float scaleAmount = ExtVector3.MagnitudeInDirection(mousePosition - previousMousePosition, projected) * scaleSpeedMultiplier; if(isSnapping && scaleSnap > 0) { currentSnapScaleAmount += scaleAmount; scaleAmount = 0; float remainder; float snapAmount = CalculateSnapAmount(scaleSnap, currentSnapScaleAmount, out remainder); if(snapAmount != 0) { scaleAmount = snapAmount; currentSnapScaleAmount = remainder; } } //WARNING - There is a bug in unity 5.4 and 5.5 that causes InverseTransformDirection to be affected by scale which will break negative scaling. Not tested, but updating to 5.4.2 should fix it - https://issuetracker.unity3d.com/issues/transformdirection-and-inversetransformdirection-operations-are-affected-by-scale Vector3 localAxis = (GetProperTransformSpace() == TransformSpace.Local && nearAxis != Axis.Any) ? mainTargetRoot.InverseTransformDirection(axis) : axis; Vector3 targetScaleAmount = Vector3.one; if(nearAxis == Axis.Any) targetScaleAmount = (ExtVector3.Abs(mainTargetRoot.localScale.normalized) * scaleAmount); else targetScaleAmount = localAxis * scaleAmount; for(int i = 0; i < targetRootsOrdered.Count; i++) { Transform target = targetRootsOrdered[i]; Vector3 targetScale = target.localScale + targetScaleAmount; if(pivot == TransformPivot.Pivot) { target.localScale = targetScale; } else if(pivot == TransformPivot.Center) { if(scaleType == ScaleType.FromPoint) { target.SetScaleFrom(originalPivot, targetScale); } else if(scaleType == ScaleType.FromPointOffset) { target.SetScaleFromOffset(originalPivot, targetScale); } } } totalScaleAmount += scaleAmount; } else if(transType == TransformType.Rotate) { float rotateAmount = 0; Vector3 rotationAxis = axis; if(nearAxis == Axis.Any) { Vector3 rotation = transform.TransformDirection(new Vector3(Input.GetAxis("Mouse Y"), -Input.GetAxis("Mouse X"), 0)); Quaternion.Euler(rotation).ToAngleAxis(out rotateAmount, out rotationAxis); rotateAmount *= allRotateSpeedMultiplier; }else{ if(circularRotationMethod) { float angle = Vector3.SignedAngle(previousMousePosition - originalPivot, mousePosition - originalPivot, axis); rotateAmount = angle * rotateSpeedMultiplier; }else{ Vector3 projected = (nearAxis == Axis.Any || ExtVector3.IsParallel(axis, planeNormal)) ? planeNormal : Vector3.Cross(axis, planeNormal); rotateAmount = (ExtVector3.MagnitudeInDirection(mousePosition - previousMousePosition, projected) * (rotateSpeedMultiplier * 100f)) / GetDistanceMultiplier(); } } if(isSnapping && rotationSnap > 0) { currentSnapRotationAmount += rotateAmount; rotateAmount = 0; float remainder; float snapAmount = CalculateSnapAmount(rotationSnap, currentSnapRotationAmount, out remainder); if(snapAmount != 0) { rotateAmount = snapAmount; currentSnapRotationAmount = remainder; } } for(int i = 0; i < targetRootsOrdered.Count; i++) { Transform target = targetRootsOrdered[i]; if(pivot == TransformPivot.Pivot) { target.Rotate(rotationAxis, rotateAmount, Space.World); } else if(pivot == TransformPivot.Center) { target.RotateAround(originalPivot, rotationAxis, rotateAmount); } } totalRotationAmount *= Quaternion.Euler(rotationAxis * rotateAmount); } } previousMousePosition = mousePosition; yield return null; } for(int i = 0; i < transformCommands.Count; i++) { ((TransformCommand)transformCommands[i]).StoreNewTransformValues(); } CommandGroup commandGroup = new CommandGroup(); commandGroup.Set(transformCommands); UndoRedoManager.Insert(commandGroup); totalRotationAmount = Quaternion.identity; totalScaleAmount = 0; isTransforming = false; SetTranslatingAxis(transformType, Axis.None); SetPivotPoint(); } float CalculateSnapAmount(float snapValue, float currentAmount, out float remainder) { remainder = 0; if(snapValue <= 0) return currentAmount; float currentAmountAbs = Mathf.Abs(currentAmount); if(currentAmountAbs > snapValue) { remainder = currentAmountAbs % snapValue; return snapValue * (Mathf.Sign(currentAmount) * Mathf.Floor(currentAmountAbs / snapValue)); } return 0; } Vector3 GetNearAxisDirection(out Vector3 otherAxis1, out Vector3 otherAxis2) { otherAxis1 = otherAxis2 = Vector3.zero; if(nearAxis != Axis.None) { if(nearAxis == Axis.X) { otherAxis1 = axisInfo.yDirection; otherAxis2 = axisInfo.zDirection; return axisInfo.xDirection; } if(nearAxis == Axis.Y) { otherAxis1 = axisInfo.xDirection; otherAxis2 = axisInfo.zDirection; return axisInfo.yDirection; } if(nearAxis == Axis.Z) { otherAxis1 = axisInfo.xDirection; otherAxis2 = axisInfo.yDirection; return axisInfo.zDirection; } if(nearAxis == Axis.Any) { return Vector3.one; } } return Vector3.zero; } void GetTarget() { if(nearAxis == Axis.None && Input.GetMouseButtonDown(0)) { bool isAdding = Input.GetKey(AddSelection); bool isRemoving = Input.GetKey(RemoveSelection); RaycastHit hitInfo; if(Physics.Raycast(myCamera.ScreenPointToRay(Input.mousePosition), out hitInfo, Mathf.Infinity, selectionMask)) { Transform target = hitInfo.transform; if(isAdding) { AddTarget(target); } else if(isRemoving) { RemoveTarget(target); } else if(!isAdding && !isRemoving) { ClearAndAddTarget(target); } }else{ if(!isAdding && !isRemoving) { ClearTargets(); } } } } public void AddTarget(Transform target, bool addCommand = true) { if(target != null) { if(targetRoots.ContainsKey(target)) return; if(children.Contains(target)) return; if(addCommand) UndoRedoManager.Insert(new AddTargetCommand(this, target, targetRootsOrdered)); AddTargetRoot(target); AddTargetHighlightedRenderers(target); SetPivotPoint(); } } public void RemoveTarget(Transform target, bool addCommand = true) { if(target != null) { if(!targetRoots.ContainsKey(target)) return; if(addCommand) UndoRedoManager.Insert(new RemoveTargetCommand(this, target)); RemoveTargetHighlightedRenderers(target); RemoveTargetRoot(target); SetPivotPoint(); } } public void ClearTargets(bool addCommand = true) { if(addCommand) UndoRedoManager.Insert(new ClearTargetsCommand(this, targetRootsOrdered)); ClearAllHighlightedRenderers(); targetRoots.Clear(); targetRootsOrdered.Clear(); children.Clear(); } void ClearAndAddTarget(Transform target) { UndoRedoManager.Insert(new ClearAndAddTargetCommand(this, target, targetRootsOrdered)); ClearTargets(false); AddTarget(target, false); } void AddTargetHighlightedRenderers(Transform target) { if(target != null) { GetTargetRenderers(target, renderersBuffer); for(int i = 0; i < renderersBuffer.Count; i++) { Renderer render = renderersBuffer[i]; if(!highlightedRenderers.Contains(render)) { materialsBuffer.Clear(); materialsBuffer.AddRange(render.sharedMaterials); if(!materialsBuffer.Contains(outlineMaterial)) { materialsBuffer.Add(outlineMaterial); render.materials = materialsBuffer.ToArray(); } highlightedRenderers.Add(render); } } materialsBuffer.Clear(); } } void GetTargetRenderers(Transform target, List<Renderer> renderers) { renderers.Clear(); if(target != null) { target.GetComponentsInChildren<Renderer>(true, renderers); } } void ClearAllHighlightedRenderers() { foreach(var target in targetRoots) { RemoveTargetHighlightedRenderers(target.Key); } //In case any are still left, such as if they changed parents or what not when they were highlighted. renderersBuffer.Clear(); renderersBuffer.AddRange(highlightedRenderers); RemoveHighlightedRenderers(renderersBuffer); } void RemoveTargetHighlightedRenderers(Transform target) { GetTargetRenderers(target, renderersBuffer); RemoveHighlightedRenderers(renderersBuffer); } void RemoveHighlightedRenderers(List<Renderer> renderers) { for(int i = 0; i < renderersBuffer.Count; i++) { Renderer render = renderersBuffer[i]; if(render != null) { materialsBuffer.Clear(); materialsBuffer.AddRange(render.sharedMaterials); if(materialsBuffer.Contains(outlineMaterial)) { materialsBuffer.Remove(outlineMaterial); render.materials = materialsBuffer.ToArray(); } } highlightedRenderers.Remove(render); } renderersBuffer.Clear(); } void AddTargetRoot(Transform targetRoot) { targetRoots.Add(targetRoot, new TargetInfo()); targetRootsOrdered.Add(targetRoot); AddAllChildren(targetRoot); } void RemoveTargetRoot(Transform targetRoot) { if(targetRoots.Remove(targetRoot)) { targetRootsOrdered.Remove(targetRoot); RemoveAllChildren(targetRoot); } } void AddAllChildren(Transform target) { childrenBuffer.Clear(); target.GetComponentsInChildren<Transform>(true, childrenBuffer); childrenBuffer.Remove(target); for(int i = 0; i < childrenBuffer.Count; i++) { Transform child = childrenBuffer[i]; children.Add(child); RemoveTargetRoot(child); //We do this in case we selected child first and then the parent. } childrenBuffer.Clear(); } void RemoveAllChildren(Transform target) { childrenBuffer.Clear(); target.GetComponentsInChildren<Transform>(true, childrenBuffer); childrenBuffer.Remove(target); for(int i = 0; i < childrenBuffer.Count; i++) { children.Remove(childrenBuffer[i]); } childrenBuffer.Clear(); } public void SetPivotPoint() { if(mainTargetRoot != null) { if(pivot == TransformPivot.Pivot) { pivotPoint = mainTargetRoot.position; } else if(pivot == TransformPivot.Center) { totalCenterPivotPoint = Vector3.zero; Dictionary<Transform, TargetInfo>.Enumerator targetsEnumerator = targetRoots.GetEnumerator(); //We avoid foreach to avoid garbage. while(targetsEnumerator.MoveNext()) { Transform target = targetsEnumerator.Current.Key; TargetInfo info = targetsEnumerator.Current.Value; info.centerPivotPoint = target.GetCenter(centerType); totalCenterPivotPoint += info.centerPivotPoint; } totalCenterPivotPoint /= targetRoots.Count; if(centerType == CenterType.Solo) { pivotPoint = targetRoots[mainTargetRoot].centerPivotPoint; } else if(centerType == CenterType.All) { pivotPoint = totalCenterPivotPoint; } } } } void SetPivotPointOffset(Vector3 offset) { pivotPoint += offset; totalCenterPivotPoint += offset; } IEnumerator ForceUpdatePivotPointAtEndOfFrame() { while(this.enabled) { ForceUpdatePivotPointOnChange(); yield return waitForEndOFFrame; } } void ForceUpdatePivotPointOnChange() { if(forceUpdatePivotPointOnChange) { if(mainTargetRoot != null && !isTransforming) { bool hasSet = false; Dictionary<Transform, TargetInfo>.Enumerator targets = targetRoots.GetEnumerator(); while(targets.MoveNext()) { if(!hasSet) { if(targets.Current.Value.previousPosition != Vector3.zero && targets.Current.Key.position != targets.Current.Value.previousPosition) { SetPivotPoint(); hasSet = true; } } targets.Current.Value.previousPosition = targets.Current.Key.position; } } } } public void SetTranslatingAxis(TransformType type, Axis axis, Axis planeAxis = Axis.None) { this.translatingType = type; this.nearAxis = axis; this.planeAxis = planeAxis; } public AxisInfo GetAxisInfo() { AxisInfo currentAxisInfo = axisInfo; if(isTransforming && GetProperTransformSpace() == TransformSpace.Global && translatingType == TransformType.Rotate) { currentAxisInfo.xDirection = totalRotationAmount * Vector3.right; currentAxisInfo.yDirection = totalRotationAmount * Vector3.up; currentAxisInfo.zDirection = totalRotationAmount * Vector3.forward; } return currentAxisInfo; } void SetNearAxis() { if(isTransforming) return; SetTranslatingAxis(transformType, Axis.None); if(mainTargetRoot == null) return; float distanceMultiplier = GetDistanceMultiplier(); float handleMinSelectedDistanceCheck = (this.minSelectedDistanceCheck + handleWidth) * distanceMultiplier; if(nearAxis == Axis.None && (TransformTypeContains(TransformType.Move) || TransformTypeContains(TransformType.Scale))) { //Important to check scale lines before move lines since in TransformType.All the move planes would block the scales center scale all gizmo. if(nearAxis == Axis.None && TransformTypeContains(TransformType.Scale)) { float tipMinSelectedDistanceCheck = (this.minSelectedDistanceCheck + boxSize) * distanceMultiplier; HandleNearestPlanes(TransformType.Scale, handleSquares, tipMinSelectedDistanceCheck); } if(nearAxis == Axis.None && TransformTypeContains(TransformType.Move)) { //Important to check the planes first before the handle tip since it makes selecting the planes easier. float planeMinSelectedDistanceCheck = (this.minSelectedDistanceCheck + planeSize) * distanceMultiplier; HandleNearestPlanes(TransformType.Move, handlePlanes, planeMinSelectedDistanceCheck); if(nearAxis != Axis.None) { planeAxis = nearAxis; } else { float tipMinSelectedDistanceCheck = (this.minSelectedDistanceCheck + triangleSize) * distanceMultiplier; HandleNearestLines(TransformType.Move, handleTriangles, tipMinSelectedDistanceCheck); } } if(nearAxis == Axis.None) { //Since Move and Scale share the same handle line, we give Move the priority. TransformType transType = transformType == TransformType.All ? TransformType.Move : transformType; HandleNearestLines(transType, handleLines, handleMinSelectedDistanceCheck); } } if(nearAxis == Axis.None && TransformTypeContains(TransformType.Rotate)) { HandleNearestLines(TransformType.Rotate, circlesLines, handleMinSelectedDistanceCheck); } } void HandleNearestLines(TransformType type, AxisVectors axisVectors, float minSelectedDistanceCheck) { float xClosestDistance = ClosestDistanceFromMouseToLines(axisVectors.x); float yClosestDistance = ClosestDistanceFromMouseToLines(axisVectors.y); float zClosestDistance = ClosestDistanceFromMouseToLines(axisVectors.z); float allClosestDistance = ClosestDistanceFromMouseToLines(axisVectors.all); HandleNearest(type, xClosestDistance, yClosestDistance, zClosestDistance, allClosestDistance, minSelectedDistanceCheck); } void HandleNearestPlanes(TransformType type, AxisVectors axisVectors, float minSelectedDistanceCheck) { float xClosestDistance = ClosestDistanceFromMouseToPlanes(axisVectors.x); float yClosestDistance = ClosestDistanceFromMouseToPlanes(axisVectors.y); float zClosestDistance = ClosestDistanceFromMouseToPlanes(axisVectors.z); float allClosestDistance = ClosestDistanceFromMouseToPlanes(axisVectors.all); HandleNearest(type, xClosestDistance, yClosestDistance, zClosestDistance, allClosestDistance, minSelectedDistanceCheck); } void HandleNearest(TransformType type, float xClosestDistance, float yClosestDistance, float zClosestDistance, float allClosestDistance, float minSelectedDistanceCheck) { if(type == TransformType.Scale && allClosestDistance <= minSelectedDistanceCheck) SetTranslatingAxis(type, Axis.Any); else if(xClosestDistance <= minSelectedDistanceCheck && xClosestDistance <= yClosestDistance && xClosestDistance <= zClosestDistance) SetTranslatingAxis(type, Axis.X); else if(yClosestDistance <= minSelectedDistanceCheck && yClosestDistance <= xClosestDistance && yClosestDistance <= zClosestDistance) SetTranslatingAxis(type, Axis.Y); else if(zClosestDistance <= minSelectedDistanceCheck && zClosestDistance <= xClosestDistance && zClosestDistance <= yClosestDistance) SetTranslatingAxis(type, Axis.Z); else if(type == TransformType.Rotate && mainTargetRoot != null) { Ray mouseRay = myCamera.ScreenPointToRay(Input.mousePosition); Vector3 mousePlaneHit = Geometry.LinePlaneIntersect(mouseRay.origin, mouseRay.direction, pivotPoint, (transform.position - pivotPoint).normalized); if((pivotPoint - mousePlaneHit).sqrMagnitude <= (GetHandleLength(TransformType.Rotate)).Squared()) SetTranslatingAxis(type, Axis.Any); } } float ClosestDistanceFromMouseToLines(List<Vector3> lines) { Ray mouseRay = myCamera.ScreenPointToRay(Input.mousePosition); float closestDistance = float.MaxValue; for(int i = 0; i + 1 < lines.Count; i++) { IntersectPoints points = Geometry.ClosestPointsOnSegmentToLine(lines[i], lines[i + 1], mouseRay.origin, mouseRay.direction); float distance = Vector3.Distance(points.first, points.second); if(distance < closestDistance) { closestDistance = distance; } } return closestDistance; } float ClosestDistanceFromMouseToPlanes(List<Vector3> planePoints) { float closestDistance = float.MaxValue; if(planePoints.Count >= 4) { Ray mouseRay = myCamera.ScreenPointToRay(Input.mousePosition); for(int i = 0; i < planePoints.Count; i += 4) { Plane plane = new Plane(planePoints[i], planePoints[i + 1], planePoints[i + 2]); float distanceToPlane; if(plane.Raycast(mouseRay, out distanceToPlane)) { Vector3 pointOnPlane = mouseRay.origin + (mouseRay.direction * distanceToPlane); Vector3 planeCenter = (planePoints[0] + planePoints[1] + planePoints[2] + planePoints[3]) / 4f; float distance = Vector3.Distance(planeCenter, pointOnPlane); if(distance < closestDistance) { closestDistance = distance; } } } } return closestDistance; } //float DistanceFromMouseToPlane(List<Vector3> planeLines) //{ // if(planeLines.Count >= 4) // { // Ray mouseRay = myCamera.ScreenPointToRay(Input.mousePosition); // Plane plane = new Plane(planeLines[0], planeLines[1], planeLines[2]); // float distanceToPlane; // if(plane.Raycast(mouseRay, out distanceToPlane)) // { // Vector3 pointOnPlane = mouseRay.origin + (mouseRay.direction * distanceToPlane); // Vector3 planeCenter = (planeLines[0] + planeLines[1] + planeLines[2] + planeLines[3]) / 4f; // return Vector3.Distance(planeCenter, pointOnPlane); // } // } // return float.MaxValue; //} void SetAxisInfo() { if(mainTargetRoot != null) { axisInfo.Set(mainTargetRoot, pivotPoint, GetProperTransformSpace()); } } //This helps keep the size consistent no matter how far we are from it. public float GetDistanceMultiplier() { if(mainTargetRoot == null) return 0f; if(myCamera.orthographic) return Mathf.Max(.01f, myCamera.orthographicSize * 2f); return Mathf.Max(.01f, Mathf.Abs(ExtVector3.MagnitudeInDirection(pivotPoint - transform.position, myCamera.transform.forward))); } void SetLines() { SetHandleLines(); SetHandlePlanes(); SetHandleTriangles(); SetHandleSquares(); SetCircles(GetAxisInfo(), circlesLines); } void SetHandleLines() { handleLines.Clear(); if(TranslatingTypeContains(TransformType.Move) || TranslatingTypeContains(TransformType.Scale)) { float lineWidth = handleWidth * GetDistanceMultiplier(); float xLineLength = 0; float yLineLength = 0; float zLineLength = 0; if(TranslatingTypeContains(TransformType.Move)) { xLineLength = yLineLength = zLineLength = GetHandleLength(TransformType.Move); } else if(TranslatingTypeContains(TransformType.Scale)) { xLineLength = GetHandleLength(TransformType.Scale, Axis.X); yLineLength = GetHandleLength(TransformType.Scale, Axis.Y); zLineLength = GetHandleLength(TransformType.Scale, Axis.Z); } AddQuads(pivotPoint, axisInfo.xDirection, axisInfo.yDirection, axisInfo.zDirection, xLineLength, lineWidth, handleLines.x); AddQuads(pivotPoint, axisInfo.yDirection, axisInfo.xDirection, axisInfo.zDirection, yLineLength, lineWidth, handleLines.y); AddQuads(pivotPoint, axisInfo.zDirection, axisInfo.xDirection, axisInfo.yDirection, zLineLength, lineWidth, handleLines.z); } } int AxisDirectionMultiplier(Vector3 direction, Vector3 otherDirection) { return ExtVector3.IsInDirection(direction, otherDirection) ? 1 : -1; } void SetHandlePlanes() { handlePlanes.Clear(); if(TranslatingTypeContains(TransformType.Move)) { Vector3 pivotToCamera = myCamera.transform.position - pivotPoint; float cameraXSign = Mathf.Sign(Vector3.Dot(axisInfo.xDirection, pivotToCamera)); float cameraYSign = Mathf.Sign(Vector3.Dot(axisInfo.yDirection, pivotToCamera)); float cameraZSign = Mathf.Sign(Vector3.Dot(axisInfo.zDirection, pivotToCamera)); float planeSize = this.planeSize; if(transformType == TransformType.All) { planeSize *= allMoveHandleLengthMultiplier; } planeSize *= GetDistanceMultiplier(); Vector3 xDirection = (axisInfo.xDirection * planeSize) * cameraXSign; Vector3 yDirection = (axisInfo.yDirection * planeSize) * cameraYSign; Vector3 zDirection = (axisInfo.zDirection * planeSize) * cameraZSign; Vector3 xPlaneCenter = pivotPoint + (yDirection + zDirection); Vector3 yPlaneCenter = pivotPoint + (xDirection + zDirection); Vector3 zPlaneCenter = pivotPoint + (xDirection + yDirection); AddQuad(xPlaneCenter, axisInfo.yDirection, axisInfo.zDirection, planeSize, handlePlanes.x); AddQuad(yPlaneCenter, axisInfo.xDirection, axisInfo.zDirection, planeSize, handlePlanes.y); AddQuad(zPlaneCenter, axisInfo.xDirection, axisInfo.yDirection, planeSize, handlePlanes.z); } } void SetHandleTriangles() { handleTriangles.Clear(); if(TranslatingTypeContains(TransformType.Move)) { float triangleLength = triangleSize * GetDistanceMultiplier(); AddTriangles(axisInfo.GetXAxisEnd(GetHandleLength(TransformType.Move)), axisInfo.xDirection, axisInfo.yDirection, axisInfo.zDirection, triangleLength, handleTriangles.x); AddTriangles(axisInfo.GetYAxisEnd(GetHandleLength(TransformType.Move)), axisInfo.yDirection, axisInfo.xDirection, axisInfo.zDirection, triangleLength, handleTriangles.y); AddTriangles(axisInfo.GetZAxisEnd(GetHandleLength(TransformType.Move)), axisInfo.zDirection, axisInfo.yDirection, axisInfo.xDirection, triangleLength, handleTriangles.z); } } void AddTriangles(Vector3 axisEnd, Vector3 axisDirection, Vector3 axisOtherDirection1, Vector3 axisOtherDirection2, float size, List<Vector3> resultsBuffer) { Vector3 endPoint = axisEnd + (axisDirection * (size * 2f)); Square baseSquare = GetBaseSquare(axisEnd, axisOtherDirection1, axisOtherDirection2, size / 2f); resultsBuffer.Add(baseSquare.bottomLeft); resultsBuffer.Add(baseSquare.topLeft); resultsBuffer.Add(baseSquare.topRight); resultsBuffer.Add(baseSquare.topLeft); resultsBuffer.Add(baseSquare.bottomRight); resultsBuffer.Add(baseSquare.topRight); for(int i = 0; i < 4; i++) { resultsBuffer.Add(baseSquare[i]); resultsBuffer.Add(baseSquare[i + 1]); resultsBuffer.Add(endPoint); } } void SetHandleSquares() { handleSquares.Clear(); if(TranslatingTypeContains(TransformType.Scale)) { float boxSize = this.boxSize * GetDistanceMultiplier(); AddSquares(axisInfo.GetXAxisEnd(GetHandleLength(TransformType.Scale, Axis.X)), axisInfo.xDirection, axisInfo.yDirection, axisInfo.zDirection, boxSize, handleSquares.x); AddSquares(axisInfo.GetYAxisEnd(GetHandleLength(TransformType.Scale, Axis.Y)), axisInfo.yDirection, axisInfo.xDirection, axisInfo.zDirection, boxSize, handleSquares.y); AddSquares(axisInfo.GetZAxisEnd(GetHandleLength(TransformType.Scale, Axis.Z)), axisInfo.zDirection, axisInfo.xDirection, axisInfo.yDirection, boxSize, handleSquares.z); AddSquares(pivotPoint - (axisInfo.xDirection * (boxSize * .5f)), axisInfo.xDirection, axisInfo.yDirection, axisInfo.zDirection, boxSize, handleSquares.all); } } void AddSquares(Vector3 axisStart, Vector3 axisDirection, Vector3 axisOtherDirection1, Vector3 axisOtherDirection2, float size, List<Vector3> resultsBuffer) { AddQuads(axisStart, axisDirection, axisOtherDirection1, axisOtherDirection2, size, size * .5f, resultsBuffer); } void AddQuads(Vector3 axisStart, Vector3 axisDirection, Vector3 axisOtherDirection1, Vector3 axisOtherDirection2, float length, float width, List<Vector3> resultsBuffer) { Vector3 axisEnd = axisStart + (axisDirection * length); AddQuads(axisStart, axisEnd, axisOtherDirection1, axisOtherDirection2, width, resultsBuffer); } void AddQuads(Vector3 axisStart, Vector3 axisEnd, Vector3 axisOtherDirection1, Vector3 axisOtherDirection2, float width, List<Vector3> resultsBuffer) { Square baseRectangle = GetBaseSquare(axisStart, axisOtherDirection1, axisOtherDirection2, width); Square baseRectangleEnd = GetBaseSquare(axisEnd, axisOtherDirection1, axisOtherDirection2, width); resultsBuffer.Add(baseRectangle.bottomLeft); resultsBuffer.Add(baseRectangle.topLeft); resultsBuffer.Add(baseRectangle.topRight); resultsBuffer.Add(baseRectangle.bottomRight); resultsBuffer.Add(baseRectangleEnd.bottomLeft); resultsBuffer.Add(baseRectangleEnd.topLeft); resultsBuffer.Add(baseRectangleEnd.topRight); resultsBuffer.Add(baseRectangleEnd.bottomRight); for(int i = 0; i < 4; i++) { resultsBuffer.Add(baseRectangle[i]); resultsBuffer.Add(baseRectangleEnd[i]); resultsBuffer.Add(baseRectangleEnd[i + 1]); resultsBuffer.Add(baseRectangle[i + 1]); } } void AddQuad(Vector3 axisStart, Vector3 axisOtherDirection1, Vector3 axisOtherDirection2, float width, List<Vector3> resultsBuffer) { Square baseRectangle = GetBaseSquare(axisStart, axisOtherDirection1, axisOtherDirection2, width); resultsBuffer.Add(baseRectangle.bottomLeft); resultsBuffer.Add(baseRectangle.topLeft); resultsBuffer.Add(baseRectangle.topRight); resultsBuffer.Add(baseRectangle.bottomRight); } Square GetBaseSquare(Vector3 axisEnd, Vector3 axisOtherDirection1, Vector3 axisOtherDirection2, float size) { Square square; Vector3 offsetUp = ((axisOtherDirection1 * size) + (axisOtherDirection2 * size)); Vector3 offsetDown = ((axisOtherDirection1 * size) - (axisOtherDirection2 * size)); //These might not really be the proper directions, as in the bottomLeft might not really be at the bottom left... square.bottomLeft = axisEnd + offsetDown; square.topLeft = axisEnd + offsetUp; square.bottomRight = axisEnd - offsetUp; square.topRight = axisEnd - offsetDown; return square; } void SetCircles(AxisInfo axisInfo, AxisVectors axisVectors) { axisVectors.Clear(); if(TranslatingTypeContains(TransformType.Rotate)) { float circleLength = GetHandleLength(TransformType.Rotate); AddCircle(pivotPoint, axisInfo.xDirection, circleLength, axisVectors.x); AddCircle(pivotPoint, axisInfo.yDirection, circleLength, axisVectors.y); AddCircle(pivotPoint, axisInfo.zDirection, circleLength, axisVectors.z); AddCircle(pivotPoint, (pivotPoint - transform.position).normalized, circleLength, axisVectors.all, false); } } void AddCircle(Vector3 origin, Vector3 axisDirection, float size, List<Vector3> resultsBuffer, bool depthTest = true) { Vector3 up = axisDirection.normalized * size; Vector3 forward = Vector3.Slerp(up, -up, .5f); Vector3 right = Vector3.Cross(up, forward).normalized * size; Matrix4x4 matrix = new Matrix4x4(); matrix[0] = right.x; matrix[1] = right.y; matrix[2] = right.z; matrix[4] = up.x; matrix[5] = up.y; matrix[6] = up.z; matrix[8] = forward.x; matrix[9] = forward.y; matrix[10] = forward.z; Vector3 lastPoint = origin + matrix.MultiplyPoint3x4(new Vector3(Mathf.Cos(0), 0, Mathf.Sin(0))); Vector3 nextPoint = Vector3.zero; float multiplier = 360f / circleDetail; Plane plane = new Plane((transform.position - pivotPoint).normalized, pivotPoint); float circleHandleWidth = handleWidth * GetDistanceMultiplier(); for(int i = 0; i < circleDetail + 1; i++) { nextPoint.x = Mathf.Cos((i * multiplier) * Mathf.Deg2Rad); nextPoint.z = Mathf.Sin((i * multiplier) * Mathf.Deg2Rad); nextPoint.y = 0; nextPoint = origin + matrix.MultiplyPoint3x4(nextPoint); if(!depthTest || plane.GetSide(lastPoint)) { Vector3 centerPoint = (lastPoint + nextPoint) * .5f; Vector3 upDirection = (centerPoint - origin).normalized; AddQuads(lastPoint, nextPoint, upDirection, axisDirection, circleHandleWidth, resultsBuffer); } lastPoint = nextPoint; } } void DrawLines(List<Vector3> lines, Color color) { if(lines.Count == 0) return; GL.Begin(GL.LINES); GL.Color(color); for(int i = 0; i < lines.Count; i += 2) { GL.Vertex(lines[i]); GL.Vertex(lines[i + 1]); } GL.End(); } void DrawTriangles(List<Vector3> lines, Color color) { if(lines.Count == 0) return; GL.Begin(GL.TRIANGLES); GL.Color(color); for(int i = 0; i < lines.Count; i += 3) { GL.Vertex(lines[i]); GL.Vertex(lines[i + 1]); GL.Vertex(lines[i + 2]); } GL.End(); } void DrawQuads(List<Vector3> lines, Color color) { if(lines.Count == 0) return; GL.Begin(GL.QUADS); GL.Color(color); for(int i = 0; i < lines.Count; i += 4) { GL.Vertex(lines[i]); GL.Vertex(lines[i + 1]); GL.Vertex(lines[i + 2]); GL.Vertex(lines[i + 3]); } GL.End(); } void DrawFilledCircle(List<Vector3> lines, Color color) { if(lines.Count == 0) return; Vector3 center = Vector3.zero; for(int i = 0; i < lines.Count; i++) { center += lines[i]; } center /= lines.Count; GL.Begin(GL.TRIANGLES); GL.Color(color); for(int i = 0; i + 1 < lines.Count; i++) { GL.Vertex(lines[i]); GL.Vertex(lines[i + 1]); GL.Vertex(center); } GL.End(); } void SetMaterial() { if(lineMaterial == null) { lineMaterial = new Material(Shader.Find("Custom/Lines")); outlineMaterial = new Material(Shader.Find("Custom/Outline")); } } } }
//--------------------------------------------------------------------------- // // File TextSchema.cs // // Copyright (C) Microsoft Corporation. All rights reserved. // // Description: A static class providing information about text content schema // //--------------------------------------------------------------------------- namespace System.Windows.Documents { using MS.Internal; using System.Collections.Generic; using System.Windows.Controls; // TextBox, TextBlock using System.Windows.Media; // Brush /// <summary> /// Provides an information about text structure schema. /// The schema is used in editing operations for maintaining /// content integrity. /// </summary> /// <remarks> /// Currently this class is totally private and hard-coded /// for some particular text structure. /// The intention is to make this mechanism public - /// as part of Text OM, so that custom backing store implementation /// could provide its own schemas. /// But we need to experiment with this approach first to make /// sure that it is feasible. /// </remarks> internal static class TextSchema { // ............................................................... // // Constructors // // ............................................................... static TextSchema() { // Initialize TextElement inheritable properties DependencyProperty[] textElementPropertyList = new DependencyProperty[] { FrameworkElement.LanguageProperty, FrameworkElement.FlowDirectionProperty, NumberSubstitution.CultureSourceProperty, NumberSubstitution.SubstitutionProperty, NumberSubstitution.CultureOverrideProperty, TextElement.FontFamilyProperty, TextElement.FontStyleProperty, TextElement.FontWeightProperty, TextElement.FontStretchProperty, TextElement.FontSizeProperty, TextElement.ForegroundProperty, }; _inheritableTextElementProperties = new DependencyProperty[textElementPropertyList.Length + Typography.TypographyPropertiesList.Length]; Array.Copy(textElementPropertyList, 0, _inheritableTextElementProperties, 0, textElementPropertyList.Length); Array.Copy(Typography.TypographyPropertiesList, 0, _inheritableTextElementProperties, textElementPropertyList.Length, Typography.TypographyPropertiesList.Length); // Initialize Block/FlowDocument inheritable properties DependencyProperty[] blockPropertyList = new DependencyProperty[] { Block.TextAlignmentProperty, Block.LineHeightProperty, Block.IsHyphenationEnabledProperty, }; _inheritableBlockProperties = new DependencyProperty[blockPropertyList.Length + _inheritableTextElementProperties.Length]; Array.Copy(blockPropertyList, 0, _inheritableBlockProperties, 0, blockPropertyList.Length); Array.Copy(_inheritableTextElementProperties, 0, _inheritableBlockProperties, blockPropertyList.Length, _inheritableTextElementProperties.Length); // // Initialize TableCell related inheritable properties. // DependencyProperty[] tableCellPropertyList = new DependencyProperty[] { Block.TextAlignmentProperty }; _inheritableTableCellProperties = new DependencyProperty[tableCellPropertyList.Length + _inheritableTextElementProperties.Length]; Array.Copy(tableCellPropertyList, _inheritableTableCellProperties, tableCellPropertyList.Length); Array.Copy(_inheritableTextElementProperties, 0, _inheritableTableCellProperties, tableCellPropertyList.Length, _inheritableTextElementProperties.Length); } // ............................................................... // // Element Content Model // // ............................................................... internal static bool IsInTextContent(ITextPointer position) { return IsValidChild(position, typeof(string)); } #if UNUSED internal static bool IsValidChild(TextElement parent, TextElement child) { return ValidateChild(parent, child, false /* throwIfIllegalChild */, false /* throwIfIllegalHyperlinkDescendent */); } #endif internal static bool ValidateChild(TextElement parent, TextElement child, bool throwIfIllegalChild, bool throwIfIllegalHyperlinkDescendent) { // Disallow nested hyperlink elements. if (TextSchema.HasHyperlinkAncestor(parent) && TextSchema.HasIllegalHyperlinkDescendant(child, throwIfIllegalHyperlinkDescendent)) { return false; } bool isValidChild = IsValidChild(parent.GetType(), child.GetType()); if (!isValidChild && throwIfIllegalChild) { throw new InvalidOperationException(SR.Get(SRID.TextSchema_ChildTypeIsInvalid, parent.GetType().Name, child.GetType().Name)); } return isValidChild; } internal static bool IsValidChild(TextElement parent, Type childType) { return ValidateChild(parent, childType, false /* throwIfIllegalChild */, false /* throwIfIllegalHyperlinkDescendent */); } internal static bool ValidateChild(TextElement parent, Type childType, bool throwIfIllegalChild, bool throwIfIllegalHyperlinkDescendent) { // Disallow nested hyperlink elements. if (TextSchema.HasHyperlinkAncestor(parent)) { if (typeof(Hyperlink).IsAssignableFrom(childType) || typeof(AnchoredBlock).IsAssignableFrom(childType)) { if (throwIfIllegalHyperlinkDescendent) { throw new InvalidOperationException(SR.Get(SRID.TextSchema_IllegalHyperlinkChild, childType)); } return false; } } bool isValidChild = IsValidChild(parent.GetType(), childType); if (!isValidChild && throwIfIllegalChild) { throw new InvalidOperationException(SR.Get(SRID.TextSchema_ChildTypeIsInvalid, parent.GetType().Name, childType.Name)); } return isValidChild; } internal static bool IsValidChild(TextPointer position, Type childType) { return ValidateChild(position, childType, false /* throwIfIllegalChild */, false /* throwIfIllegalHyperlinkDescendent */); } internal static bool ValidateChild(TextPointer position, Type childType, bool throwIfIllegalChild, bool throwIfIllegalHyperlinkDescendent) { DependencyObject parent = position.Parent; if (parent == null) { TextElement leftElement = position.GetAdjacentElementFromOuterPosition(LogicalDirection.Backward); TextElement rightElement = position.GetAdjacentElementFromOuterPosition(LogicalDirection.Forward); return (leftElement == null || IsValidSibling(leftElement.GetType(), childType)) && (rightElement == null || IsValidSibling(rightElement.GetType(), childType)); } if (parent is TextElement) { return ValidateChild((TextElement)parent, childType, throwIfIllegalChild, throwIfIllegalHyperlinkDescendent); } bool isValidChild = IsValidChild(parent.GetType(), childType); if (!isValidChild && throwIfIllegalChild) { throw new InvalidOperationException(SR.Get(SRID.TextSchema_ChildTypeIsInvalid, parent.GetType().Name, childType.Name)); } return isValidChild; } internal static bool IsValidSibling(Type siblingType, Type newType) { if (typeof(Inline).IsAssignableFrom(newType)) { return typeof(Inline).IsAssignableFrom(siblingType); } else if (typeof(Block).IsAssignableFrom(newType)) { return typeof(Block).IsAssignableFrom(siblingType); } else if (typeof(TableRowGroup).IsAssignableFrom(newType)) { return typeof(TableRowGroup).IsAssignableFrom(siblingType); } else if (typeof(TableRow).IsAssignableFrom(newType)) { return typeof(TableRow).IsAssignableFrom(siblingType); } else if (typeof(TableCell).IsAssignableFrom(newType)) { return typeof(TableCell).IsAssignableFrom(siblingType); } else if (typeof(ListItem).IsAssignableFrom(newType)) { return typeof(ListItem).IsAssignableFrom(siblingType); } else { Invariant.Assert(false, "unexpected value for newType"); return false; } } internal static bool IsValidChild(ITextPointer position, Type childType) { // Disallow nested hyperlink elements. if (typeof(TextElement).IsAssignableFrom(position.ParentType) && TextPointerBase.IsInHyperlinkScope(position)) { if (typeof(Hyperlink).IsAssignableFrom(childType) || typeof(AnchoredBlock).IsAssignableFrom(childType)) { return false; } } return IsValidChild(position.ParentType, childType); } internal static bool IsValidChildOfContainer(Type parentType, Type childType) { Invariant.Assert(!typeof(TextElement).IsAssignableFrom(parentType)); return IsValidChild(parentType, childType); } // Walks parents of this TextElement until it finds a hyperlink ancestor. internal static bool HasHyperlinkAncestor(TextElement element) { Inline ancestor = element as Inline; while (ancestor != null && !(ancestor is Hyperlink)) { ancestor = ancestor.Parent as Inline; } return ancestor != null; } /// <summary> /// Returns true indicatinng that a type can be skipped for pointer normalization - /// it is formattinng tag not producing a caret stop position. /// </summary> /// <param name="elementType"></param> /// <returns></returns> internal static bool IsFormattingType(Type elementType) { return typeof(Run).IsAssignableFrom(elementType) || typeof(Span).IsAssignableFrom(elementType); } /// <summary> /// Determine if the given type is "known"-- that is, is part of the framework as /// opposed to a custom, user-defined type. /// </summary> internal static bool IsKnownType(Type elementType) { return elementType.Module == typeof(System.Windows.Documents.TextElement).Module || // presentationframework elementType.Module == typeof(System.Windows.UIElement).Module; // presentationcore } internal static bool IsNonFormattingInline(Type elementType) { return typeof(Inline).IsAssignableFrom(elementType) && !IsFormattingType(elementType); } internal static bool IsMergeableInline(Type elementType) { return IsFormattingType(elementType) && !IsNonMergeableInline(elementType); } internal static bool IsNonMergeableInline(Type elementType) { TextElementEditingBehaviorAttribute att = (TextElementEditingBehaviorAttribute)Attribute.GetCustomAttribute(elementType, typeof(TextElementEditingBehaviorAttribute)); if (att != null && att.IsMergeable == false) { return true; } else { return false; } } /// <summary> /// Returns true for a type which allows paragraph merging /// across its boundary. /// Hard-structured elements like Table, Floater, Figure /// does not allow paragraph merging. /// </summary> internal static bool AllowsParagraphMerging(Type elementType) { return typeof(Paragraph).IsAssignableFrom(elementType) || typeof(ListItem).IsAssignableFrom(elementType) || typeof(List).IsAssignableFrom(elementType) || typeof(Section).IsAssignableFrom(elementType); } /// <summary> /// Classifies the elementType as a generalized Paragraph - /// a block behaving similar to paragraph in regards of /// margins, indentations, bullets, and other paragraph properties. /// </summary> /// <param name="elementType"> /// Element type to check /// </param> /// <returns> /// true if the element can be treated as a paragraph /// </returns> internal static bool IsParagraphOrBlockUIContainer(Type elementType) { return typeof(Paragraph).IsAssignableFrom(elementType) || typeof(BlockUIContainer).IsAssignableFrom(elementType); } // Identifies any block element internal static bool IsBlock(Type type) { return ( // typeof(Block).IsAssignableFrom(type)); } internal static bool IsBreak(Type type) { return ( // typeof(LineBreak).IsAssignableFrom(type)); } // ............................................................... // // Formatting Properties // // ............................................................... // Helper for defining whether text decoration value is non-empty collection internal static bool HasTextDecorations(object value) { return (value is TextDecorationCollection) && ((TextDecorationCollection)value).Count > 0; } // From a given element type returns one of statically known // reduceElement parameter: True value of this parameter indicates that // serialization goes into XamlPackage, so all elements // can be preserved as is; otherwise some of them must be // reduced into simpler representations (such as InlineUIContainer -> Run // and BlockUIContainer -> Paragraph). internal static Type GetStandardElementType(Type type, bool reduceElement) { // Run-derived elements // -------------------- if (typeof(Run).IsAssignableFrom(type)) { // Must be after all elements derived from Run return typeof(Run); } // Span-derived elements // --------------------- else if (typeof(Hyperlink).IsAssignableFrom(type)) { return typeof(Hyperlink); } else if (typeof(Span).IsAssignableFrom(type)) { // Must be after all other standard Span-derived elements such as Hyperlink, Bold, etc. return typeof(Span); } // Other Inline elements // --------------------- else if (typeof(InlineUIContainer).IsAssignableFrom(type)) { return reduceElement ? typeof(Run) : typeof(InlineUIContainer); } else if (typeof(LineBreak).IsAssignableFrom(type)) { return typeof(LineBreak); } else if (typeof(Floater).IsAssignableFrom(type)) { return typeof(Floater); } else if (typeof(Figure).IsAssignableFrom(type)) { return typeof(Figure); } // Block-derived elements // ---------------------- else if (typeof(Paragraph).IsAssignableFrom(type)) { return typeof(Paragraph); } else if (typeof(Section).IsAssignableFrom(type)) { return typeof(Section); } else if (typeof(List).IsAssignableFrom(type)) { return typeof(List); } else if (typeof(Table).IsAssignableFrom(type)) { return typeof(Table); } else if (typeof(BlockUIContainer).IsAssignableFrom(type)) { return reduceElement ? typeof(Paragraph) : typeof(BlockUIContainer); } // Other TextElements // ------------------ else if (typeof(ListItem).IsAssignableFrom(type)) { return typeof(ListItem); } else if (typeof(TableColumn).IsAssignableFrom(type)) { return typeof(TableColumn); } else if (typeof(TableRowGroup).IsAssignableFrom(type)) { return typeof(TableRowGroup); } else if (typeof(TableRow).IsAssignableFrom(type)) { return typeof(TableRow); } else if (typeof(TableCell).IsAssignableFrom(type)) { return typeof(TableCell); } // To make compiler happy in cases of Invariant.Assert - return something Invariant.Assert(false, "We do not expect any unknown elements derived directly from TextElement, Block or Inline. Schema must have been checking for that"); return null; } // Returns a list of inheritable properties applicable to a particular type internal static DependencyProperty[] GetInheritableProperties(Type type) { if (typeof(TableCell).IsAssignableFrom(type)) { return _inheritableTableCellProperties; } if (typeof(Block).IsAssignableFrom(type) || typeof(FlowDocument).IsAssignableFrom(type)) { return _inheritableBlockProperties; } Invariant.Assert(typeof(TextElement).IsAssignableFrom(type) || typeof(TableColumn).IsAssignableFrom(type), "type must be one of TextElement, FlowDocument or TableColumn"); return _inheritableTextElementProperties; } // Returns a list of noninheritable properties applicable to a particular type // They are safe to be transferred from outer scope to inner scope when the outer one // is removed (e.g. TextRangeEdit.RemoveUnnecessarySpans(...)). internal static DependencyProperty[] GetNoninheritableProperties(Type type) { // Run-derived elements // -------------------- if (typeof(Run).IsAssignableFrom(type)) { // Must be after all elements derived from Run return _inlineProperties; } // Span-derived elements // --------------------- else if (typeof(Hyperlink).IsAssignableFrom(type)) { return _hyperlinkProperties; } else if (typeof(Span).IsAssignableFrom(type)) { // Must be after all other standard Span-derived elements such as Hyperlink, Bold, etc. return _inlineProperties; } // Other Inline elements // --------------------- else if (typeof(InlineUIContainer).IsAssignableFrom(type)) { return _inlineProperties; } else if (typeof(LineBreak).IsAssignableFrom(type)) { return _emptyPropertyList; } else if (typeof(Floater).IsAssignableFrom(type)) { return _floaterProperties; } else if (typeof(Figure).IsAssignableFrom(type)) { return _figureProperties; } // Block-derived elements // ---------------------- else if (typeof(Paragraph).IsAssignableFrom(type)) { return _paragraphProperties; } else if (typeof(Section).IsAssignableFrom(type)) { return _blockProperties; } else if (typeof(List).IsAssignableFrom(type)) { return _listProperties; } else if (typeof(Table).IsAssignableFrom(type)) { return _tableProperties; } else if (typeof(BlockUIContainer).IsAssignableFrom(type)) { return _blockProperties; } // Other TextElements // ------------------ else if (typeof(ListItem).IsAssignableFrom(type)) { return _listItemProperties; } else if (typeof(TableColumn).IsAssignableFrom(type)) { return _tableColumnProperties; } else if (typeof(TableRowGroup).IsAssignableFrom(type)) { return _tableRowGroupProperties; } else if (typeof(TableRow).IsAssignableFrom(type)) { return _tableRowProperties; } else if (typeof(TableCell).IsAssignableFrom(type)) { return _tableCellProperties; } Invariant.Assert(false, "We do not expect any unknown elements derived directly from TextElement. Schema must have been checking for that"); return _emptyPropertyList; // to make compiler happy } // Compares two values for equality /// <summary> /// Property comparison helper. /// Compares property values for equivalence from serialization /// standpoint. In editing we consider properties equal /// if they have the same serialized representation. /// Differences coming from current dynamic state changes /// should not affect comparison if they are not going to be /// visible after serialization. /// Instantiation dirrefences are also insignificant. /// </summary> /// <param name="value1"> /// </param> /// <param name="value2"> /// </param> /// <returns> /// True if two values have the same serialized representation /// </returns> internal static bool ValuesAreEqual(object value1, object value2) { if ((object)value1 == (object)value2) // this check includes two nulls { return true; } // Comparing null with empty collections if (value1 == null) { if (value2 is TextDecorationCollection) { TextDecorationCollection decorations2 = (TextDecorationCollection)value2; return decorations2.Count == 0; } else if (value2 is TextEffectCollection) { TextEffectCollection effects2 = (TextEffectCollection)value2; return effects2.Count == 0; } return false; } else if (value2 == null) { if (value1 is TextDecorationCollection) { TextDecorationCollection decorations1 = (TextDecorationCollection)value1; return decorations1.Count == 0; } else if (value1 is TextEffectCollection) { TextEffectCollection effects1 = (TextEffectCollection)value1; return effects1.Count == 0; } return false; } // Must be of exactly the same types (really ?) // if (value1.GetType() != value2.GetType()) { return false; } // Special cases for known types: TextDecorations, FontFamily, Brush if (value1 is TextDecorationCollection) { TextDecorationCollection decorations1 = (TextDecorationCollection)value1; TextDecorationCollection decorations2 = (TextDecorationCollection)value2; return decorations1.ValueEquals(decorations2); } else if (value1 is FontFamily) { FontFamily fontFamily1 = (FontFamily)value1; FontFamily fontFamily2 = (FontFamily)value2; return fontFamily1.Equals(fontFamily2); } else if (value1 is Brush) { return AreBrushesEqual((Brush)value1, (Brush)value2); } else { string string1 = value1.ToString(); string string2 = value2.ToString(); return string1 == string2; } } /// <summary> /// Tests whether it is the paragraph property or not. /// Used to decide should the property be applied to character runs or to paragraphs /// in TextRange.ApplyProperty() /// </summary> internal static bool IsParagraphProperty(DependencyProperty formattingProperty) { // Check inheritable paragraph properties for (int i = 0; i < _inheritableBlockProperties.Length; i++) { if (formattingProperty == _inheritableBlockProperties[i]) { return true; } } // Check non-inheritable paragraph properties for (int i = 0; i < _paragraphProperties.Length; i++) { if (formattingProperty == _paragraphProperties[i]) { return true; } } return false; } /// <summary> /// Returns true if this property is applicable to inline character formatting element /// </summary> internal static bool IsCharacterProperty(DependencyProperty formattingProperty) { // Check inheritable inline properties for (int i = 0; i < _inheritableTextElementProperties.Length; i++) { if (formattingProperty == _inheritableTextElementProperties[i]) { return true; } } // Check non-inheritable Inline properties for (int i = 0; i < _inlineProperties.Length; i++) { if (formattingProperty == _inlineProperties[i]) { return true; } } return false; } /// <summary> /// Returns true if this property is a character property NOT affecting formatting. /// </summary> internal static bool IsNonFormattingCharacterProperty(DependencyProperty property) { for (int i = 0; i < _nonFormattingCharacterProperties.Length; i++) { if (property == _nonFormattingCharacterProperties[i]) { return true; } } return false; } internal static DependencyProperty[] GetNonFormattingCharacterProperties() { return _nonFormattingCharacterProperties; } /// <summary> /// Returns true if this property is a structural property of inline element. /// </summary> /// <remarks> /// A structural character property is more strict for its scope than other (non-structural) inline properties (such as fontweight). /// While the associativity rule holds true for non-structural properties when there values are equal, /// (FontWeight)A (FontWeight)B == (FontWeight) AB /// this does not hold true for structual properties even when there values may be equal, /// (FlowDirection)A (FlowDirection)B != (FlowDirection)A B /// Hence, these properties require special logic in setting, merging, splitting rules for inline elements. /// </remarks> internal static bool IsStructuralCharacterProperty(DependencyProperty formattingProperty) { int i; for (i = 0; i < _structuralCharacterProperties.Length; i++) { if (formattingProperty == _structuralCharacterProperties[i]) break; } return (i < _structuralCharacterProperties.Length); } // Returns true if a property value can be incremented or decremented internal static bool IsPropertyIncremental(DependencyProperty property) { if (property == null) { return false; } Type propertyType = property.PropertyType; return typeof(double).IsAssignableFrom(propertyType) || typeof(long).IsAssignableFrom(propertyType) || typeof(int).IsAssignableFrom(propertyType) || typeof(Thickness).IsAssignableFrom(propertyType); } // Set of properties affecting editing behavior that must be transferred // from hosting UI elements (like RichTextBox) to FlowDocument to ensure appropriate // editing behavior. // This is especially important for FlowDocuments with FormattingDefaults="Standalone". internal static DependencyProperty[] BehavioralProperties { get { return _behavioralPropertyList; } } internal static DependencyProperty[] ImageProperties { get { return _imagePropertyList; } } // List of structural properties. internal static DependencyProperty[] StructuralCharacterProperties { get { return _structuralCharacterProperties; } } //------------------------------------------------------ // // Private Methods // //------------------------------------------------------ #region Private Methods private static bool IsValidChild(Type parentType, Type childType) { // Text Content if (parentType == null || // typeof(Run).IsAssignableFrom(parentType) || typeof(TextBox).IsAssignableFrom(parentType) || typeof(PasswordBox).IsAssignableFrom(parentType)) { // NOTE: Even though we use TextBlock or FlowDocumentView for TextBox's render scope, // a parent for position will be directly TextBlock or PasswordBox, thus allowing // text content. Otherwise neither TextBlock nor FlowDocumentView allow direct text content - // only through Run. return childType == typeof(string); } // TextBlock allowed children else if (typeof(TextBlock).IsAssignableFrom(parentType)) { return typeof(Inline).IsAssignableFrom(childType) && !typeof(AnchoredBlock).IsAssignableFrom(childType); } // Hyperlink allowed children else if (typeof(Hyperlink).IsAssignableFrom(parentType)) { return typeof(Inline).IsAssignableFrom(childType) && !typeof(Hyperlink).IsAssignableFrom(childType) && !typeof(AnchoredBlock).IsAssignableFrom(childType); } // Inline items else if (typeof(Span).IsAssignableFrom(parentType) || typeof(Paragraph).IsAssignableFrom(parentType) || typeof(AccessText).IsAssignableFrom(parentType)) { return typeof(Inline).IsAssignableFrom(childType); } // Inline UIElements else if (typeof(InlineUIContainer).IsAssignableFrom(parentType)) { return typeof(UIElement).IsAssignableFrom(childType); } // List Content else if (typeof(List).IsAssignableFrom(parentType)) { return typeof(ListItem).IsAssignableFrom(childType); } // Table Content else if (typeof(Table).IsAssignableFrom(parentType)) { return typeof(TableRowGroup).IsAssignableFrom(childType); } else if (typeof(TableRowGroup).IsAssignableFrom(parentType)) { return typeof(TableRow).IsAssignableFrom(childType); } else if (typeof(TableRow).IsAssignableFrom(parentType)) { return typeof(TableCell).IsAssignableFrom(childType); } // Block Content // else if ( typeof(Section).IsAssignableFrom(parentType) || typeof(ListItem).IsAssignableFrom(parentType) || typeof(TableCell).IsAssignableFrom(parentType) || typeof(Floater).IsAssignableFrom(parentType) || typeof(Figure).IsAssignableFrom(parentType) || typeof(FlowDocument).IsAssignableFrom(parentType)) { return typeof(Block).IsAssignableFrom(childType); } // Block UIElements else if (typeof(BlockUIContainer).IsAssignableFrom(parentType)) { return typeof(UIElement).IsAssignableFrom(childType); } else { return false; } } // Returns true if passed textelement has any Hyperlink or AnchoredBlock descendant. // It this context, the element or one of its ancestors is a Hyperlink. private static bool HasIllegalHyperlinkDescendant(TextElement element, bool throwIfIllegalDescendent) { TextPointer start = element.ElementStart; TextPointer end = element.ElementEnd; while (start.CompareTo(end) < 0) { TextPointerContext forwardContext = start.GetPointerContext(LogicalDirection.Forward); if (forwardContext == TextPointerContext.ElementStart) { TextElement nextElement = (TextElement)start.GetAdjacentElement(LogicalDirection.Forward); if (nextElement is Hyperlink || nextElement is AnchoredBlock) { if (throwIfIllegalDescendent) { throw new InvalidOperationException(SR.Get(SRID.TextSchema_IllegalHyperlinkChild, nextElement.GetType())); } return true; } } start = start.GetNextContextPosition(LogicalDirection.Forward); } return false; } private static bool AreBrushesEqual(Brush brush1, Brush brush2) { SolidColorBrush solidBrush1 = brush1 as SolidColorBrush; if (solidBrush1 != null) { return solidBrush1.Color.Equals(((SolidColorBrush)brush2).Color); } else { // When the brush is not serializable to string, we consider values equal only is they are equal as objects string string1 = DPTypeDescriptorContext.GetStringValue(TextElement.BackgroundProperty, brush1); string string2 = DPTypeDescriptorContext.GetStringValue(TextElement.BackgroundProperty, brush2); return string1 != null && string2 != null ? string1 == string2 : false; } } #endregion Private Methods //------------------------------------------------------ // // Private Fields // //------------------------------------------------------ #region Private Fields // List of all inheritable properties applicable to TextElement types private static readonly DependencyProperty[] _inheritableTextElementProperties; // Block element adds a few inhertiable properties that dont apply to other TextElement types, // this list includes inheritable properties applicable to Block and also root FlowDocument types. private static readonly DependencyProperty[] _inheritableBlockProperties; // TableCell element adds inheritable TextAlignmentProperty that doesn't apply to other TextElement types. private static readonly DependencyProperty[] _inheritableTableCellProperties; // List of all non-inheritable properties applicable to Hyperlink element private static readonly DependencyProperty[] _hyperlinkProperties = new DependencyProperty[] { Hyperlink.NavigateUriProperty, Hyperlink.TargetNameProperty, Hyperlink.CommandProperty, Hyperlink.CommandParameterProperty, Hyperlink.CommandTargetProperty, // Inherits Inline Properties Inline.BaselineAlignmentProperty, Inline.TextDecorationsProperty, // Inherits TextElement properties TextElement.BackgroundProperty, //TextElement.TextEffectsProperty, -- the property is not supported in text editor // Inherits FrameworkContentElement properties FrameworkContentElement.ToolTipProperty, }; // List of all non-inheritable properties applicable to Inline element private static readonly DependencyProperty[] _inlineProperties = new DependencyProperty[] { Inline.BaselineAlignmentProperty, Inline.TextDecorationsProperty, // Inherits TextElement properties TextElement.BackgroundProperty, //TextElement.TextEffectsProperty, -- the property is not supported in text editor }; // List of all non-inheritable properties applicable to Paragraph element private static readonly DependencyProperty[] _paragraphProperties = new DependencyProperty[] { Paragraph.MinWidowLinesProperty, Paragraph.MinOrphanLinesProperty, Paragraph.TextIndentProperty, Paragraph.KeepWithNextProperty, Paragraph.KeepTogetherProperty, Paragraph.TextDecorationsProperty, // Inherits Block properties Block.MarginProperty, Block.PaddingProperty, Block.BorderThicknessProperty, Block.BorderBrushProperty, // Inherits TextElement properties TextElement.BackgroundProperty, //TextElement.TextEffectsProperty, -- the property is not supported in text editor }; // List of all non-inheritable properties applicable to List element private static readonly DependencyProperty[] _listProperties = new DependencyProperty[] { List.MarkerStyleProperty, List.MarkerOffsetProperty, List.StartIndexProperty, // Inherits Block properties Block.MarginProperty, Block.PaddingProperty, Block.BorderThicknessProperty, Block.BorderBrushProperty, // Inherits TextElement properties TextElement.BackgroundProperty, //TextElement.TextEffectsProperty, -- the property is not supported in text editor }; // List of all non-inheritable properties applicable to ListItem element private static readonly DependencyProperty[] _listItemProperties = new DependencyProperty[] { // Adds owner to Block properties ListItem.MarginProperty, ListItem.PaddingProperty, ListItem.BorderThicknessProperty, ListItem.BorderBrushProperty, // Inherits TextElement properties TextElement.BackgroundProperty, //TextElement.TextEffectsProperty, -- the property is not supported in text editor }; // List of all non-inheritable properties applicable to Table element private static readonly DependencyProperty[] _tableProperties = new DependencyProperty[] { Table.CellSpacingProperty, // Inherits Block properties Block.MarginProperty, Block.PaddingProperty, Block.BorderThicknessProperty, Block.BorderBrushProperty, // Inherits TextElement properties TextElement.BackgroundProperty, //TextElement.TextEffectsProperty, -- the property is not supported in text editor }; // List of all non-inheritable properties applicable to TableColumn element private static readonly DependencyProperty[] _tableColumnProperties = new DependencyProperty[] { TableColumn.WidthProperty, TableColumn.BackgroundProperty, }; // List of all non-inheritable properties applicable to TableRowGroup element private static readonly DependencyProperty[] _tableRowGroupProperties = new DependencyProperty[] { // Inherits TextElement properties TextElement.BackgroundProperty, //TextElement.TextEffectsProperty, -- the property is not supported in text editor }; // List of all non-inheritable properties applicable to TableRow element private static readonly DependencyProperty[] _tableRowProperties = new DependencyProperty[] { // Inherits TextElement properties TextElement.BackgroundProperty, //TextElement.TextEffectsProperty, -- the property is not supported in text editor }; // List of all non-inheritable properties applicable to TableCell element private static readonly DependencyProperty[] _tableCellProperties = new DependencyProperty[] { TableCell.ColumnSpanProperty, TableCell.RowSpanProperty, // Adds ownership to Block properties TableCell.PaddingProperty, TableCell.BorderThicknessProperty, TableCell.BorderBrushProperty, // Inherits TextElement properties TextElement.BackgroundProperty, //TextElement.TextEffectsProperty, -- the property is not supported in text editor }; // List of all non-inheritable properties applicable to Floater element private static readonly DependencyProperty[] _floaterProperties = new DependencyProperty[] { Floater.HorizontalAlignmentProperty, Floater.WidthProperty, // Adds ownership to Block properties Floater.MarginProperty, Floater.PaddingProperty, Floater.BorderThicknessProperty, Floater.BorderBrushProperty, // Inherits TextElement properties TextElement.BackgroundProperty, //TextElement.TextEffectsProperty, -- the property is not supported in text editor }; // List of all non-inheritable properties applicable to Figure element private static readonly DependencyProperty[] _figureProperties = new DependencyProperty[] { Figure.HorizontalAnchorProperty, Figure.VerticalAnchorProperty, Figure.HorizontalOffsetProperty, Figure.VerticalOffsetProperty, Figure.CanDelayPlacementProperty, Figure.WrapDirectionProperty, Figure.WidthProperty, Figure.HeightProperty, // Adds ownership to Block properties Figure.MarginProperty, Figure.PaddingProperty, Figure.BorderThicknessProperty, Figure.BorderBrushProperty, // Inherits TextElement properties TextElement.BackgroundProperty, //TextElement.TextEffectsProperty, -- the property is not supported in text editor }; // List of all non-inheritable properties applicable to Block element private static readonly DependencyProperty[] _blockProperties = new DependencyProperty[] { Block.MarginProperty, Block.PaddingProperty, Block.BorderThicknessProperty, Block.BorderBrushProperty, Block.BreakPageBeforeProperty, Block.BreakColumnBeforeProperty, Block.ClearFloatersProperty, Block.IsHyphenationEnabledProperty, // Inherits TextElement properties TextElement.BackgroundProperty, //TextElement.TextEffectsProperty, -- the property is not supported in text editor }; // List of all non-inheritable properties applicable to TextElement element private static readonly DependencyProperty[] _textElementPropertyList = new DependencyProperty[] { TextElement.BackgroundProperty, //TextElement.TextEffectsProperty, -- the property is not supported in text editor }; // List of all non-inheritable properties applicable to TextElement element private static readonly DependencyProperty[] _imagePropertyList = new DependencyProperty[] { Image.SourceProperty, Image.StretchProperty, Image.StretchDirectionProperty, // Inherits FrameworkElement properties //FrameworkElement.StyleProperty, //FrameworkElement.OverridesDefaultStyleProperty, //FrameworkElement.DataContextProperty, FrameworkElement.LanguageProperty, //FrameworkElement.NameProperty, //FrameworkElement.TagProperty, //FrameworkElement.InputScopeProperty, FrameworkElement.LayoutTransformProperty, FrameworkElement.WidthProperty, FrameworkElement.MinWidthProperty, FrameworkElement.MaxWidthProperty, FrameworkElement.HeightProperty, FrameworkElement.MinHeightProperty, FrameworkElement.MaxHeightProperty, //FrameworkElement.FlowDirectionProperty, FrameworkElement.MarginProperty, FrameworkElement.HorizontalAlignmentProperty, FrameworkElement.VerticalAlignmentProperty, //FrameworkElement.FocusVisualStyleProperty, FrameworkElement.CursorProperty, FrameworkElement.ForceCursorProperty, //FrameworkElement.FocusableProperty, FrameworkElement.ToolTipProperty, //FrameworkElement.ContextMenuProperty, // Inherits UIElement properties //UIElement.AllowDropProperty, UIElement.RenderTransformProperty, UIElement.RenderTransformOriginProperty, UIElement.OpacityProperty, UIElement.OpacityMaskProperty, UIElement.BitmapEffectProperty, UIElement.BitmapEffectInputProperty, UIElement.VisibilityProperty, UIElement.ClipToBoundsProperty, UIElement.ClipProperty, UIElement.SnapsToDevicePixelsProperty, }; // Behavioral property list private static readonly DependencyProperty[] _behavioralPropertyList = new DependencyProperty[] { UIElement.AllowDropProperty, }; // Empty property list private static readonly DependencyProperty[] _emptyPropertyList = new DependencyProperty[] { }; // Structural property list. // NB: Existing code depends on these being inheritable properties. private static readonly DependencyProperty[] _structuralCharacterProperties = new DependencyProperty[] { Inline.FlowDirectionProperty, }; // List of inline properties (both inheritable or non-inheritable) that are "content" properties, not "formatting" properties. private static readonly DependencyProperty[] _nonFormattingCharacterProperties = new DependencyProperty[] { FrameworkElement.FlowDirectionProperty, FrameworkElement.LanguageProperty, Run.TextProperty, }; #endregion Private Fields } }
// 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.Globalization; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using Internal.Runtime.CompilerServices; namespace System { // Represents a Globally Unique Identifier. [StructLayout(LayoutKind.Sequential)] [Serializable] [NonVersionable] // This only applies to field layout [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public partial struct Guid : IFormattable, IComparable, IComparable<Guid>, IEquatable<Guid>, ISpanFormattable { public static readonly Guid Empty = new Guid(); private int _a; // Do not rename (binary serialization) private short _b; // Do not rename (binary serialization) private short _c; // Do not rename (binary serialization) private byte _d; // Do not rename (binary serialization) private byte _e; // Do not rename (binary serialization) private byte _f; // Do not rename (binary serialization) private byte _g; // Do not rename (binary serialization) private byte _h; // Do not rename (binary serialization) private byte _i; // Do not rename (binary serialization) private byte _j; // Do not rename (binary serialization) private byte _k; // Do not rename (binary serialization) // Creates a new guid from an array of bytes. public Guid(byte[] b) : this(new ReadOnlySpan<byte>(b ?? throw new ArgumentNullException(nameof(b)))) { } // Creates a new guid from a read-only span. public Guid(ReadOnlySpan<byte> b) { if ((uint)b.Length != 16) { throw new ArgumentException(SR.Format(SR.Arg_GuidArrayCtor, "16"), nameof(b)); } if (BitConverter.IsLittleEndian) { this = MemoryMarshal.Read<Guid>(b); return; } // slower path for BigEndian: _k = b[15]; // hoist bounds checks _a = b[3] << 24 | b[2] << 16 | b[1] << 8 | b[0]; _b = (short)(b[5] << 8 | b[4]); _c = (short)(b[7] << 8 | b[6]); _d = b[8]; _e = b[9]; _f = b[10]; _g = b[11]; _h = b[12]; _i = b[13]; _j = b[14]; } [CLSCompliant(false)] public Guid(uint a, ushort b, ushort c, byte d, byte e, byte f, byte g, byte h, byte i, byte j, byte k) { _a = (int)a; _b = (short)b; _c = (short)c; _d = d; _e = e; _f = f; _g = g; _h = h; _i = i; _j = j; _k = k; } // Creates a new GUID initialized to the value represented by the arguments. public Guid(int a, short b, short c, byte[] d) { if (d == null) { throw new ArgumentNullException(nameof(d)); } if (d.Length != 8) { throw new ArgumentException(SR.Format(SR.Arg_GuidArrayCtor, "8"), nameof(d)); } _a = a; _b = b; _c = c; _k = d[7]; // hoist bounds checks _d = d[0]; _e = d[1]; _f = d[2]; _g = d[3]; _h = d[4]; _i = d[5]; _j = d[6]; } // Creates a new GUID initialized to the value represented by the // arguments. The bytes are specified like this to avoid endianness issues. public Guid(int a, short b, short c, byte d, byte e, byte f, byte g, byte h, byte i, byte j, byte k) { _a = a; _b = b; _c = c; _d = d; _e = e; _f = f; _g = g; _h = h; _i = i; _j = j; _k = k; } private enum GuidParseThrowStyle : byte { None = 0, All = 1, AllButOverflow = 2 } // This will store the result of the parsing. And it will eventually be used to construct a Guid instance. private struct GuidResult { private readonly GuidParseThrowStyle _throwStyle; internal Guid _parsedGuid; internal GuidResult(GuidParseThrowStyle canThrow) : this() { _throwStyle = canThrow; } internal void SetFailure(bool overflow, string failureMessageID) { if (_throwStyle == GuidParseThrowStyle.None) { return; } if (overflow) { if (_throwStyle == GuidParseThrowStyle.All) { throw new OverflowException(SR.GetResourceString(failureMessageID)); } throw new FormatException(SR.Format_GuidUnrecognized); } throw new FormatException(SR.GetResourceString(failureMessageID)); } } // Creates a new guid based on the value in the string. The value is made up // of hex digits speared by the dash ("-"). The string may begin and end with // brackets ("{", "}"). // // The string must be of the form dddddddd-dddd-dddd-dddd-dddddddddddd. where // d is a hex digit. (That is 8 hex digits, followed by 4, then 4, then 4, // then 12) such as: "CA761232-ED42-11CE-BACD-00AA0057B223" public Guid(string g) { if (g == null) { throw new ArgumentNullException(nameof(g)); } var result = new GuidResult(GuidParseThrowStyle.All); bool success = TryParseGuid(g, ref result); Debug.Assert(success, "GuidParseThrowStyle.All means throw on all failures"); this = result._parsedGuid; } public static Guid Parse(string input) => Parse(input != null ? (ReadOnlySpan<char>)input : throw new ArgumentNullException(nameof(input))); public static Guid Parse(ReadOnlySpan<char> input) { var result = new GuidResult(GuidParseThrowStyle.AllButOverflow); bool success = TryParseGuid(input, ref result); Debug.Assert(success, "GuidParseThrowStyle.AllButOverflow means throw on all failures"); return result._parsedGuid; } public static bool TryParse(string? input, out Guid result) { if (input == null) { result = default; return false; } return TryParse((ReadOnlySpan<char>)input, out result); } public static bool TryParse(ReadOnlySpan<char> input, out Guid result) { var parseResult = new GuidResult(GuidParseThrowStyle.None); if (TryParseGuid(input, ref parseResult)) { result = parseResult._parsedGuid; return true; } else { result = default; return false; } } public static Guid ParseExact(string input, string format) => ParseExact( input != null ? (ReadOnlySpan<char>)input : throw new ArgumentNullException(nameof(input)), format != null ? (ReadOnlySpan<char>)format : throw new ArgumentNullException(nameof(format))); public static Guid ParseExact(ReadOnlySpan<char> input, ReadOnlySpan<char> format) { if (format.Length != 1) { // all acceptable format strings are of length 1 throw new FormatException(SR.Format_InvalidGuidFormatSpecification); } input = input.Trim(); var result = new GuidResult(GuidParseThrowStyle.AllButOverflow); bool success = ((char)(format[0] | 0x20)) switch { 'd' => TryParseExactD(input, ref result), 'n' => TryParseExactN(input, ref result), 'b' => TryParseExactB(input, ref result), 'p' => TryParseExactP(input, ref result), 'x' => TryParseExactX(input, ref result), _ => throw new FormatException(SR.Format_InvalidGuidFormatSpecification), }; Debug.Assert(success, "GuidParseThrowStyle.AllButOverflow means throw on all failures"); return result._parsedGuid; } public static bool TryParseExact(string? input, string? format, out Guid result) { if (input == null) { result = default; return false; } return TryParseExact((ReadOnlySpan<char>)input, format, out result); } public static bool TryParseExact(ReadOnlySpan<char> input, ReadOnlySpan<char> format, out Guid result) { if (format.Length != 1) { result = default; return false; } input = input.Trim(); var parseResult = new GuidResult(GuidParseThrowStyle.None); bool success = false; switch ((char)(format[0] | 0x20)) { case 'd': success = TryParseExactD(input, ref parseResult); break; case 'n': success = TryParseExactN(input, ref parseResult); break; case 'b': success = TryParseExactB(input, ref parseResult); break; case 'p': success = TryParseExactP(input, ref parseResult); break; case 'x': success = TryParseExactX(input, ref parseResult); break; } if (success) { result = parseResult._parsedGuid; return true; } else { result = default; return false; } } private static bool TryParseGuid(ReadOnlySpan<char> guidString, ref GuidResult result) { guidString = guidString.Trim(); // Remove whitespace from beginning and end if (guidString.Length == 0) { result.SetFailure(overflow: false, nameof(SR.Format_GuidUnrecognized)); return false; } return (guidString[0]) switch { '(' => TryParseExactP(guidString, ref result), '{' => guidString.Contains('-') ? TryParseExactB(guidString, ref result) : TryParseExactX(guidString, ref result), _ => guidString.Contains('-') ? TryParseExactD(guidString, ref result) : TryParseExactN(guidString, ref result), }; } // Two helpers used for parsing components: // - uint.TryParse(..., NumberStyles.AllowHexSpecifier, ...) // Used when we expect the entire provided span to be filled with and only with hex digits and no overflow is possible // - TryParseHex // Used when the component may have an optional '+' and "0x" prefix, when it may overflow, etc. private static bool TryParseExactB(ReadOnlySpan<char> guidString, ref GuidResult result) { // e.g. "{d85b1407-351d-4694-9392-03acc5870eb1}" if ((uint)guidString.Length != 38 || guidString[0] != '{' || guidString[37] != '}') { result.SetFailure(overflow: false, nameof(SR.Format_GuidInvLen)); return false; } return TryParseExactD(guidString.Slice(1, 36), ref result); } private static bool TryParseExactD(ReadOnlySpan<char> guidString, ref GuidResult result) { // e.g. "d85b1407-351d-4694-9392-03acc5870eb1" // Compat notes due to the previous implementation's implementation details. // - Components may begin with "0x" or "0x+", but the expected length of each component // needs to include those prefixes, e.g. a four digit component could be "1234" or // "0x34" or "+0x4" or "+234", but not "0x1234" nor "+1234" nor "+0x1234". // - "0X" is valid instead of "0x" if ((uint)guidString.Length != 36) { result.SetFailure(overflow: false, nameof(SR.Format_GuidInvLen)); return false; } if (guidString[8] != '-' || guidString[13] != '-' || guidString[18] != '-' || guidString[23] != '-') { result.SetFailure(overflow: false, nameof(SR.Format_GuidDashes)); return false; } ref Guid g = ref result._parsedGuid; uint uintTmp; if (TryParseHex(guidString.Slice(0, 8), out Unsafe.As<int, uint>(ref g._a)) && // _a TryParseHex(guidString.Slice(9, 4), out uintTmp)) // _b { g._b = (short)uintTmp; if (TryParseHex(guidString.Slice(14, 4), out uintTmp)) // _c { g._c = (short)uintTmp; if (TryParseHex(guidString.Slice(19, 4), out uintTmp)) // _d, _e { g._d = (byte)(uintTmp >> 8); g._e = (byte)uintTmp; if (TryParseHex(guidString.Slice(24, 4), out uintTmp)) // _f, _g { g._f = (byte)(uintTmp >> 8); g._g = (byte)uintTmp; if (uint.TryParse(guidString.Slice(28, 8), NumberStyles.AllowHexSpecifier, null, out uintTmp)) // _h, _i, _j, _k { g._h = (byte)(uintTmp >> 24); g._i = (byte)(uintTmp >> 16); g._j = (byte)(uintTmp >> 8); g._k = (byte)uintTmp; return true; } } } } } result.SetFailure(overflow: false, nameof(SR.Format_GuidInvalidChar)); return false; } private static bool TryParseExactN(ReadOnlySpan<char> guidString, ref GuidResult result) { // e.g. "d85b1407351d4694939203acc5870eb1" if ((uint)guidString.Length != 32) { result.SetFailure(overflow: false, nameof(SR.Format_GuidInvLen)); return false; } ref Guid g = ref result._parsedGuid; uint uintTmp; if (uint.TryParse(guidString.Slice(0, 8), NumberStyles.AllowHexSpecifier, null, out Unsafe.As<int, uint>(ref g._a)) && // _a uint.TryParse(guidString.Slice(8, 8), NumberStyles.AllowHexSpecifier, null, out uintTmp)) // _b, _c { g._b = (short)(uintTmp >> 16); g._c = (short)uintTmp; if (uint.TryParse(guidString.Slice(16, 8), NumberStyles.AllowHexSpecifier, null, out uintTmp)) // _d, _e, _f, _g { g._d = (byte)(uintTmp >> 24); g._e = (byte)(uintTmp >> 16); g._f = (byte)(uintTmp >> 8); g._g = (byte)uintTmp; if (uint.TryParse(guidString.Slice(24, 8), NumberStyles.AllowHexSpecifier, null, out uintTmp)) // _h, _i, _j, _k { g._h = (byte)(uintTmp >> 24); g._i = (byte)(uintTmp >> 16); g._j = (byte)(uintTmp >> 8); g._k = (byte)uintTmp; return true; } } } result.SetFailure(overflow: false, nameof(SR.Format_GuidInvalidChar)); return false; } private static bool TryParseExactP(ReadOnlySpan<char> guidString, ref GuidResult result) { // e.g. "(d85b1407-351d-4694-9392-03acc5870eb1)" if ((uint)guidString.Length != 38 || guidString[0] != '(' || guidString[37] != ')') { result.SetFailure(overflow: false, nameof(SR.Format_GuidInvLen)); return false; } return TryParseExactD(guidString.Slice(1, 36), ref result); } private static bool TryParseExactX(ReadOnlySpan<char> guidString, ref GuidResult result) { // e.g. "{0xd85b1407,0x351d,0x4694,{0x93,0x92,0x03,0xac,0xc5,0x87,0x0e,0xb1}}" // Compat notes due to the previous implementation's implementation details. // - Each component need not be the full expected number of digits. // - Each component may contain any number of leading 0s // - The "short" components are parsed as 32-bits and only considered to overflow if they'd overflow 32 bits. // - The "byte" components are parsed as 32-bits and are considered to overflow if they'd overflow 8 bits, // but for the Guid ctor, whether they overflow 8 bits or 32 bits results in differing exceptions. // - Components may begin with "0x", "0x+", even "0x+0x". // - "0X" is valid instead of "0x" // Eat all of the whitespace. Unlike the other forms, X allows for any amount of whitespace // anywhere, not just at the beginning and end. guidString = EatAllWhitespace(guidString); // Check for leading '{' if ((uint)guidString.Length == 0 || guidString[0] != '{') { result.SetFailure(overflow: false, nameof(SR.Format_GuidBrace)); return false; } // Check for '0x' if (!IsHexPrefix(guidString, 1)) { result.SetFailure(overflow: false, nameof(SR.Format_GuidHexPrefix)); return false; } // Find the end of this hex number (since it is not fixed length) int numStart = 3; int numLen = guidString.Slice(numStart).IndexOf(','); if (numLen <= 0) { result.SetFailure(overflow: false, nameof(SR.Format_GuidComma)); return false; } bool overflow = false; if (!TryParseHex(guidString.Slice(numStart, numLen), out Unsafe.As<int, uint>(ref result._parsedGuid._a), ref overflow) || overflow) { result.SetFailure(overflow, overflow ? nameof(SR.Overflow_UInt32) : nameof(SR.Format_GuidInvalidChar)); return false; } // Check for '0x' if (!IsHexPrefix(guidString, numStart + numLen + 1)) { result.SetFailure(overflow: false, nameof(SR.Format_GuidHexPrefix)); return false; } // +3 to get by ',0x' numStart = numStart + numLen + 3; numLen = guidString.Slice(numStart).IndexOf(','); if (numLen <= 0) { result.SetFailure(overflow: false, nameof(SR.Format_GuidComma)); return false; } // Read in the number if (!TryParseHex(guidString.Slice(numStart, numLen), out result._parsedGuid._b, ref overflow) || overflow) { result.SetFailure(overflow, overflow ? nameof(SR.Overflow_UInt32) : nameof(SR.Format_GuidInvalidChar)); return false; } // Check for '0x' if (!IsHexPrefix(guidString, numStart + numLen + 1)) { result.SetFailure(overflow: false, nameof(SR.Format_GuidHexPrefix)); return false; } // +3 to get by ',0x' numStart = numStart + numLen + 3; numLen = guidString.Slice(numStart).IndexOf(','); if (numLen <= 0) { result.SetFailure(overflow: false, nameof(SR.Format_GuidComma)); return false; } // Read in the number if (!TryParseHex(guidString.Slice(numStart, numLen), out result._parsedGuid._c, ref overflow) || overflow) { result.SetFailure(overflow, overflow ? nameof(SR.Overflow_UInt32) : nameof(SR.Format_GuidInvalidChar)); return false; } // Check for '{' if ((uint)guidString.Length <= (uint)(numStart + numLen + 1) || guidString[numStart + numLen + 1] != '{') { result.SetFailure(overflow: false, nameof(SR.Format_GuidBrace)); return false; } // Prepare for loop numLen++; for (int i = 0; i < 8; i++) { // Check for '0x' if (!IsHexPrefix(guidString, numStart + numLen + 1)) { result.SetFailure(overflow: false, nameof(SR.Format_GuidHexPrefix)); return false; } // +3 to get by ',0x' or '{0x' for first case numStart = numStart + numLen + 3; // Calculate number length if (i < 7) // first 7 cases { numLen = guidString.Slice(numStart).IndexOf(','); if (numLen <= 0) { result.SetFailure(overflow: false, nameof(SR.Format_GuidComma)); return false; } } else // last case ends with '}', not ',' { numLen = guidString.Slice(numStart).IndexOf('}'); if (numLen <= 0) { result.SetFailure(overflow: false, nameof(SR.Format_GuidBraceAfterLastNumber)); return false; } } // Read in the number uint byteVal; if (!TryParseHex(guidString.Slice(numStart, numLen), out byteVal, ref overflow) || overflow || byteVal > byte.MaxValue) { // The previous implementation had some odd inconsistencies, which are carried forward here. // The byte values in the X format are treated as integers with regards to overflow, so // a "byte" value like 0xddd in Guid's ctor results in a FormatException but 0xddddddddd results // in OverflowException. result.SetFailure(overflow, overflow ? nameof(SR.Overflow_UInt32) : byteVal > byte.MaxValue ? nameof(SR.Overflow_Byte) : nameof(SR.Format_GuidInvalidChar)); return false; } Unsafe.Add(ref result._parsedGuid._d, i) = (byte)byteVal; } // Check for last '}' if (numStart + numLen + 1 >= guidString.Length || guidString[numStart + numLen + 1] != '}') { result.SetFailure(overflow: false, nameof(SR.Format_GuidEndBrace)); return false; } // Check if we have extra characters at the end if (numStart + numLen + 1 != guidString.Length - 1) { result.SetFailure(overflow: false, nameof(SR.Format_ExtraJunkAtEnd)); return false; } return true; } private static bool TryParseHex(ReadOnlySpan<char> guidString, out short result, ref bool overflow) { uint tmp; bool success = TryParseHex(guidString, out tmp, ref overflow); result = (short)tmp; return success; } private static bool TryParseHex(ReadOnlySpan<char> guidString, out uint result) { bool overflowIgnored = false; return TryParseHex(guidString, out result, ref overflowIgnored); } private static bool TryParseHex(ReadOnlySpan<char> guidString, out uint result, ref bool overflow) { if ((uint)guidString.Length > 0) { if (guidString[0] == '+') { guidString = guidString.Slice(1); } if ((uint)guidString.Length > 1 && guidString[0] == '0' && (guidString[1] | 0x20) == 'x') { guidString = guidString.Slice(2); } } // Skip past leading 0s. int i = 0; for (; i < guidString.Length && guidString[i] == '0'; i++) ; int processedDigits = 0; ReadOnlySpan<byte> charToHexLookup = Number.CharToHexLookup; uint tmp = 0; for (; i < guidString.Length; i++) { int numValue; char c = guidString[i]; if (c >= (uint)charToHexLookup.Length || (numValue = charToHexLookup[c]) == 0xFF) { if (processedDigits > 8) overflow = true; result = 0; return false; } tmp = (tmp * 16) + (uint)numValue; processedDigits++; } if (processedDigits > 8) overflow = true; result = tmp; return true; } private static ReadOnlySpan<char> EatAllWhitespace(ReadOnlySpan<char> str) { // Find the first whitespace character. If there is none, just return the input. int i; for (i = 0; i < str.Length && !char.IsWhiteSpace(str[i]); i++) ; if (i == str.Length) { return str; } // There was at least one whitespace. Copy over everything prior to it to a new array. var chArr = new char[str.Length]; int newLength = 0; if (i > 0) { newLength = i; str.Slice(0, i).CopyTo(chArr); } // Loop through the remaining chars, copying over non-whitespace. for (; i < str.Length; i++) { char c = str[i]; if (!char.IsWhiteSpace(c)) { chArr[newLength++] = c; } } // Return the string with the whitespace removed. return new ReadOnlySpan<char>(chArr, 0, newLength); } private static bool IsHexPrefix(ReadOnlySpan<char> str, int i) => i + 1 < str.Length && str[i] == '0' && (str[i + 1] | 0x20) == 'x'; // Returns an unsigned byte array containing the GUID. public byte[] ToByteArray() { var g = new byte[16]; if (BitConverter.IsLittleEndian) { MemoryMarshal.TryWrite<Guid>(g, ref this); } else { TryWriteBytes(g); } return g; } // Returns whether bytes are sucessfully written to given span. public bool TryWriteBytes(Span<byte> destination) { if (BitConverter.IsLittleEndian) { return MemoryMarshal.TryWrite(destination, ref this); } // slower path for BigEndian if (destination.Length < 16) return false; destination[15] = _k; // hoist bounds checks destination[0] = (byte)(_a); destination[1] = (byte)(_a >> 8); destination[2] = (byte)(_a >> 16); destination[3] = (byte)(_a >> 24); destination[4] = (byte)(_b); destination[5] = (byte)(_b >> 8); destination[6] = (byte)(_c); destination[7] = (byte)(_c >> 8); destination[8] = _d; destination[9] = _e; destination[10] = _f; destination[11] = _g; destination[12] = _h; destination[13] = _i; destination[14] = _j; return true; } // Returns the guid in "registry" format. public override string ToString() => ToString("D", null); public override int GetHashCode() { // Simply XOR all the bits of the GUID 32 bits at a time. return _a ^ Unsafe.Add(ref _a, 1) ^ Unsafe.Add(ref _a, 2) ^ Unsafe.Add(ref _a, 3); } // Returns true if and only if the guid represented // by o is the same as this instance. public override bool Equals(object? o) { Guid g; // Check that o is a Guid first if (o == null || !(o is Guid)) return false; else g = (Guid)o; // Now compare each of the elements return g._a == _a && Unsafe.Add(ref g._a, 1) == Unsafe.Add(ref _a, 1) && Unsafe.Add(ref g._a, 2) == Unsafe.Add(ref _a, 2) && Unsafe.Add(ref g._a, 3) == Unsafe.Add(ref _a, 3); } public bool Equals(Guid g) { // Now compare each of the elements return g._a == _a && Unsafe.Add(ref g._a, 1) == Unsafe.Add(ref _a, 1) && Unsafe.Add(ref g._a, 2) == Unsafe.Add(ref _a, 2) && Unsafe.Add(ref g._a, 3) == Unsafe.Add(ref _a, 3); } private int GetResult(uint me, uint them) => me < them ? -1 : 1; public int CompareTo(object? value) { if (value == null) { return 1; } if (!(value is Guid)) { throw new ArgumentException(SR.Arg_MustBeGuid, nameof(value)); } Guid g = (Guid)value; if (g._a != _a) { return GetResult((uint)_a, (uint)g._a); } if (g._b != _b) { return GetResult((uint)_b, (uint)g._b); } if (g._c != _c) { return GetResult((uint)_c, (uint)g._c); } if (g._d != _d) { return GetResult(_d, g._d); } if (g._e != _e) { return GetResult(_e, g._e); } if (g._f != _f) { return GetResult(_f, g._f); } if (g._g != _g) { return GetResult(_g, g._g); } if (g._h != _h) { return GetResult(_h, g._h); } if (g._i != _i) { return GetResult(_i, g._i); } if (g._j != _j) { return GetResult(_j, g._j); } if (g._k != _k) { return GetResult(_k, g._k); } return 0; } public int CompareTo(Guid value) { if (value._a != _a) { return GetResult((uint)_a, (uint)value._a); } if (value._b != _b) { return GetResult((uint)_b, (uint)value._b); } if (value._c != _c) { return GetResult((uint)_c, (uint)value._c); } if (value._d != _d) { return GetResult(_d, value._d); } if (value._e != _e) { return GetResult(_e, value._e); } if (value._f != _f) { return GetResult(_f, value._f); } if (value._g != _g) { return GetResult(_g, value._g); } if (value._h != _h) { return GetResult(_h, value._h); } if (value._i != _i) { return GetResult(_i, value._i); } if (value._j != _j) { return GetResult(_j, value._j); } if (value._k != _k) { return GetResult(_k, value._k); } return 0; } public static bool operator ==(Guid a, Guid b) => a._a == b._a && Unsafe.Add(ref a._a, 1) == Unsafe.Add(ref b._a, 1) && Unsafe.Add(ref a._a, 2) == Unsafe.Add(ref b._a, 2) && Unsafe.Add(ref a._a, 3) == Unsafe.Add(ref b._a, 3); public static bool operator !=(Guid a, Guid b) => // Now compare each of the elements a._a != b._a || Unsafe.Add(ref a._a, 1) != Unsafe.Add(ref b._a, 1) || Unsafe.Add(ref a._a, 2) != Unsafe.Add(ref b._a, 2) || Unsafe.Add(ref a._a, 3) != Unsafe.Add(ref b._a, 3); public string ToString(string? format) { return ToString(format, null); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static char HexToChar(int a) { a &= 0xf; return (char)((a > 9) ? a - 10 + 0x61 : a + 0x30); } private static unsafe int HexsToChars(char* guidChars, int a, int b) { guidChars[0] = HexToChar(a >> 4); guidChars[1] = HexToChar(a); guidChars[2] = HexToChar(b >> 4); guidChars[3] = HexToChar(b); return 4; } private static unsafe int HexsToCharsHexOutput(char* guidChars, int a, int b) { guidChars[0] = '0'; guidChars[1] = 'x'; guidChars[2] = HexToChar(a >> 4); guidChars[3] = HexToChar(a); guidChars[4] = ','; guidChars[5] = '0'; guidChars[6] = 'x'; guidChars[7] = HexToChar(b >> 4); guidChars[8] = HexToChar(b); return 9; } // IFormattable interface // We currently ignore provider public string ToString(string? format, IFormatProvider? provider) { if (string.IsNullOrEmpty(format)) { format = "D"; } // all acceptable format strings are of length 1 if (format.Length != 1) { throw new FormatException(SR.Format_InvalidGuidFormatSpecification); } int guidSize; switch (format[0]) { case 'D': case 'd': guidSize = 36; break; case 'N': case 'n': guidSize = 32; break; case 'B': case 'b': case 'P': case 'p': guidSize = 38; break; case 'X': case 'x': guidSize = 68; break; default: throw new FormatException(SR.Format_InvalidGuidFormatSpecification); } string guidString = string.FastAllocateString(guidSize); int bytesWritten; bool result = TryFormat(new Span<char>(ref guidString.GetRawStringData(), guidString.Length), out bytesWritten, format); Debug.Assert(result && bytesWritten == guidString.Length, "Formatting guid should have succeeded."); return guidString; } // Returns whether the guid is successfully formatted as a span. public bool TryFormat(Span<char> destination, out int charsWritten, ReadOnlySpan<char> format = default) { if (format.Length == 0) { format = "D"; } // all acceptable format strings are of length 1 if (format.Length != 1) { throw new FormatException(SR.Format_InvalidGuidFormatSpecification); } bool dash = true; bool hex = false; int braces = 0; int guidSize; switch (format[0]) { case 'D': case 'd': guidSize = 36; break; case 'N': case 'n': dash = false; guidSize = 32; break; case 'B': case 'b': braces = '{' + ('}' << 16); guidSize = 38; break; case 'P': case 'p': braces = '(' + (')' << 16); guidSize = 38; break; case 'X': case 'x': braces = '{' + ('}' << 16); dash = false; hex = true; guidSize = 68; break; default: throw new FormatException(SR.Format_InvalidGuidFormatSpecification); } if (destination.Length < guidSize) { charsWritten = 0; return false; } unsafe { fixed (char* guidChars = &MemoryMarshal.GetReference(destination)) { char* p = guidChars; if (braces != 0) *p++ = (char)braces; if (hex) { // {0xdddddddd,0xdddd,0xdddd,{0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd}} *p++ = '0'; *p++ = 'x'; p += HexsToChars(p, _a >> 24, _a >> 16); p += HexsToChars(p, _a >> 8, _a); *p++ = ','; *p++ = '0'; *p++ = 'x'; p += HexsToChars(p, _b >> 8, _b); *p++ = ','; *p++ = '0'; *p++ = 'x'; p += HexsToChars(p, _c >> 8, _c); *p++ = ','; *p++ = '{'; p += HexsToCharsHexOutput(p, _d, _e); *p++ = ','; p += HexsToCharsHexOutput(p, _f, _g); *p++ = ','; p += HexsToCharsHexOutput(p, _h, _i); *p++ = ','; p += HexsToCharsHexOutput(p, _j, _k); *p++ = '}'; } else { // [{|(]dddddddd[-]dddd[-]dddd[-]dddd[-]dddddddddddd[}|)] p += HexsToChars(p, _a >> 24, _a >> 16); p += HexsToChars(p, _a >> 8, _a); if (dash) *p++ = '-'; p += HexsToChars(p, _b >> 8, _b); if (dash) *p++ = '-'; p += HexsToChars(p, _c >> 8, _c); if (dash) *p++ = '-'; p += HexsToChars(p, _d, _e); if (dash) *p++ = '-'; p += HexsToChars(p, _f, _g); p += HexsToChars(p, _h, _i); p += HexsToChars(p, _j, _k); } if (braces != 0) *p++ = (char)(braces >> 16); Debug.Assert(p - guidChars == guidSize); } } charsWritten = guidSize; return true; } bool ISpanFormattable.TryFormat(Span<char> destination, out int charsWritten, ReadOnlySpan<char> format, IFormatProvider? provider) { // Like with the IFormattable implementation, provider is ignored. return TryFormat(destination, out charsWritten, format); } } }
// UndoRedoSurfaceBuffer.cs // Copyright (c) 2015 jeffrey.io using System; using System.Collections.Generic; namespace io.jeffrey.pixel { public class UndoRedoBuffer { public readonly PixelSurface Surface; public readonly bool ReadOnly; public readonly int Width; public readonly int Height; private readonly UndoEncoding Encoding; private readonly int RecordSize; private readonly int[] Buffer; private int Position; public UndoRedoBuffer(int width, int height) { this.Surface = null; this.ReadOnly = false; this.Width = width; this.Height = height; if (width * height < Int32.MaxValue / 4) { this.Encoding = UndoEncoding.Packed; this.RecordSize = 3; } else { this.Encoding = UndoEncoding.Unpacked; this.RecordSize = 4; } this.Buffer = new int[RecordSize * width * height]; this.Position = 0; } private UndoRedoBuffer(PixelSurface surface, UndoRedoBuffer parent) { this.Surface = surface; this.ReadOnly = true; this.Width = parent.Width; this.Height = parent.Height; this.Encoding = parent.Encoding; this.RecordSize = parent.RecordSize; this.Buffer = new int[parent.Position]; this.Position = parent.Position; for (int k = 0; k < parent.Position; k++) { Buffer[k] = parent.Buffer[k]; } } public int Size { get { return Buffer.Length; } } public bool HasChanges { get { return Position > 0; } } public UndoRedoBuffer Snap(PixelSurface surface) { return new UndoRedoBuffer(surface, this); } public void Reset() { this.Position = 0; } public void Walk(Action<int,int,int,int> delta) { for (int at = 0; at < Position; at+=RecordSize) { if (this.Encoding == UndoEncoding.Packed) { int v = Buffer[at]; int x = v % Width; delta(x, (v - x) / Width, Buffer[at+1], Buffer[at+2]); } else { delta(Buffer[at], Buffer[at+1], Buffer[at+2], Buffer[at+3]); } } } public void Write(int x, int y, int before, int after) { if (this.Encoding == UndoEncoding.Packed) { Buffer[Position] = y * Width + x; Buffer[Position+1] = before; Buffer[Position+2] = after; } else { Buffer[Position] = x; Buffer[Position+1] = y; Buffer[Position+2] = before; Buffer[Position+3] = after; } Position += RecordSize; } } public class UndoRedoSurfaceBuffer : PixelSurface { private readonly int MaximumStackSize; private PixelSurface CurrentSurface; private readonly UndoRedoBuffer Buffer; private readonly Stack<UndoRedoBuffer> UndoStack = new Stack<UndoRedoBuffer>(); private readonly Stack<UndoRedoBuffer> RedoStack = new Stack<UndoRedoBuffer>(); private readonly Stack<UndoRedoBuffer> Temp = new Stack<UndoRedoBuffer>(); private bool Allowed = false; public UndoRedoSurfaceBuffer(int width, int height) { this.Buffer = new UndoRedoBuffer(width, height); this.MaximumStackSize = (width * height * 4) * 5; } public void BeginRecord(PixelSurface Surface) { if (Allowed) EndRecord(); this.CurrentSurface = Surface; Allowed = true; } public void EndRecord() { Allowed = false; if (Buffer.HasChanges) { UndoStack.Push(Buffer.Snap(CurrentSurface)); Balance(); Buffer.Reset(); } if (RedoAvailable) { RedoStack.Clear(); } } private void Balance(Stack<UndoRedoBuffer> stack) { Temp.Clear(); int Score = 0; while(stack.Count > 0) { UndoRedoBuffer test = stack.Pop(); Score += test.Size; if (Score < MaximumStackSize) { Temp.Push(test); } } while (Temp.Count > 0) { stack.Push(Temp.Pop()); } } private void Balance() { Balance(UndoStack); Balance(RedoStack); } public bool UndoAvailable { get { return UndoStack.Count > 0; } } public bool RedoAvailable { get { return RedoStack.Count > 0; } } public void Undo() { if (UndoStack.Count == 0) return; UndoRedoBuffer undo = UndoStack.Pop(); RedoStack.Push(undo); Balance(); undo.Walk((x,y,before,after) => { undo.Surface.Put(x,y,before); }); } public void Redo() { if (RedoStack.Count == 0) return; UndoRedoBuffer redo = RedoStack.Pop(); UndoStack.Push(redo); Balance(); redo.Walk((x,y,before,after) => { redo.Surface.Put(x,y,after); }); } private void Record(int x, int y, int before, int after) { Buffer.Write(x, y, before, after); } public PixelSurface Put(int x, int y, int arba) { if (!Allowed) { throw new InvalidOperationException(); } SurfacePoint before = CurrentSurface.Get(x, y); if (before.Valid) { if (before.Color != arba) { Record(x, y, before.Color, arba); CurrentSurface.Put(x, y, arba); } return this; } else { return this; } } public SurfacePoint Get(int x, int y) { return CurrentSurface.Get(x, y); } public void Draw() { throw new NotSupportedException(); } public PixelSurface Kinkolate(Func<int, int, KinkolateAction> operation, Action<int, int, int, int> delta) { return CurrentSurface.Kinkolate(operation, (x,y,before,after) => { if (before != after) { Record(x, y, before, after); } // inspect it if (delta != null) { delta(x, y, before, after); } }); } public void Release() { throw new NotSupportedException(); } public PixelSurfaceType Type { get { return CurrentSurface.Type; } } public int Width { get { return CurrentSurface.Width; } } public int Height { get { return CurrentSurface.Height; } } public int TranslationX { get { return CurrentSurface.TranslationX; } set { CurrentSurface.TranslationX = value; } } public int TranslationY { get { return CurrentSurface.TranslationY; } set { CurrentSurface.TranslationY = value; } } public long LastChange { get { return CurrentSurface.LastChange; } } } }
// Copyright 2016 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. using Google.Api.Gax; using Google.Apis.Auth.OAuth2; using Google.Apis.Iam.v1; using Google.Apis.Iam.v1.Data; using Google.Apis.Services; using Google.Cloud.ClientTesting; using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading; using System.Threading.Tasks; using Xunit; namespace Google.Cloud.Storage.V1.Snippets { [SnippetOutputCollector] [Collection(nameof(StorageSnippetFixture))] public class UrlSignerSnippets { private readonly StorageSnippetFixture _fixture; public UrlSignerSnippets(StorageSnippetFixture fixture) { _fixture = fixture; } [Fact] public async Task SignedURLGet() { var bucketName = _fixture.BucketName; var objectName = _fixture.HelloStorageObjectName; var credential = (await GoogleCredential.GetApplicationDefaultAsync()).UnderlyingCredential as ServiceAccountCredential; var httpClient = new HttpClient(); // Sample: SignedURLGet // Additional: Sign(string,string,TimeSpan,*,*) // Create a signed URL which can be used to get a specific object for one hour. UrlSigner urlSigner = UrlSigner.FromServiceAccountCredential(credential); string url = urlSigner.Sign(bucketName, objectName, TimeSpan.FromHours(1)); // Get the content at the created URL. HttpResponseMessage response = await httpClient.GetAsync(url); string content = await response.Content.ReadAsStringAsync(); // End sample Assert.Equal(_fixture.HelloWorldContent, content); } // See-also: Sign(string,string,TimeSpan,*,*) // Member: Sign(UrlSigner.RequestTemplate, UrlSigner.Options) // See [Sign](ref) for an example using an alternative overload. // End see-also [Fact] public async Task WithSigningVersion() { var bucketName = _fixture.BucketName; var objectName = _fixture.HelloStorageObjectName; var credential = (await GoogleCredential.GetApplicationDefaultAsync()).UnderlyingCredential as ServiceAccountCredential; var httpClient = new HttpClient(); // Sample: WithSigningVersion // Create a signed URL which can be used to get a specific object for one hour, // using the V4 signing process. UrlSigner urlSigner = UrlSigner .FromServiceAccountCredential(credential); string url = urlSigner.Sign(bucketName, objectName, TimeSpan.FromHours(1), signingVersion: SigningVersion.V4); // Get the content at the created URL. HttpResponseMessage response = await httpClient.GetAsync(url); string content = await response.Content.ReadAsStringAsync(); // End sample Assert.Equal(_fixture.HelloWorldContent, content); } [Fact] public async Task SignedURLPut() { var bucketName = _fixture.BucketName; var credential = (await GoogleCredential.GetApplicationDefaultAsync()).UnderlyingCredential as ServiceAccountCredential; var httpClient = new HttpClient(); // Sample: SignedURLPut // Create a request template that will be used to create the signed URL. var destination = "places/world.txt"; UrlSigner.RequestTemplate requestTemplate = UrlSigner.RequestTemplate .FromBucket(bucketName) .WithObjectName(destination) .WithHttpMethod(HttpMethod.Put) .WithContentHeaders(new Dictionary<string, IEnumerable<string>> { { "Content-Type", new[] { "text/plain" } } }); // Create options specifying for how long the signer URL will be valid. UrlSigner.Options options = UrlSigner.Options.FromDuration(TimeSpan.FromHours(1)); // Create a signed URL which allows the requester to PUT data with the text/plain content-type. UrlSigner urlSigner = UrlSigner.FromServiceAccountCredential(credential); string url = urlSigner.Sign(requestTemplate, options); // Upload the content into the bucket using the signed URL. string source = "world.txt"; ByteArrayContent content; using (FileStream stream = File.OpenRead(source)) { byte[] data = new byte[stream.Length]; stream.Read(data, 0, data.Length); content = new ByteArrayContent(data) { Headers = { ContentType = new MediaTypeHeaderValue("text/plain") } }; } HttpResponseMessage response = await httpClient.PutAsync(url, content); // End sample Assert.True(response.IsSuccessStatusCode); var client = StorageClient.Create(); var result = new MemoryStream(); await client.DownloadObjectAsync(bucketName, destination, result); using (var stream = File.OpenRead(source)) { var data = new byte[stream.Length]; stream.Read(data, 0, data.Length); Assert.Equal(result.ToArray(), data); } await client.DeleteObjectAsync(bucketName, destination); } // Sample: IamServiceBlobSigner internal sealed class IamServiceBlobSigner : UrlSigner.IBlobSigner { private readonly IamService _iamService; public string Id { get; } internal IamServiceBlobSigner(IamService service, string id) { _iamService = service; Id = id; } public string CreateSignature(byte[] data) => CreateRequest(data).Execute().Signature; public async Task<string> CreateSignatureAsync(byte[] data, CancellationToken cancellationToken) { ProjectsResource.ServiceAccountsResource.SignBlobRequest request = CreateRequest(data); SignBlobResponse response = await request.ExecuteAsync(cancellationToken).ConfigureAwait(false); return response.Signature; } private ProjectsResource.ServiceAccountsResource.SignBlobRequest CreateRequest(byte[] data) { SignBlobRequest body = new SignBlobRequest { BytesToSign = Convert.ToBase64String(data) }; string account = $"projects/-/serviceAccounts/{Id}"; ProjectsResource.ServiceAccountsResource.SignBlobRequest request = _iamService.Projects.ServiceAccounts.SignBlob(body, account); return request; } } // End sample [SkippableFact] public async Task SignedUrlWithIamServiceBlobSigner() { _fixture.SkipIf(Platform.Instance().Type == PlatformType.Unknown); var bucketName = _fixture.BucketName; var objectName = _fixture.HelloStorageObjectName; var httpClient = new HttpClient(); // Sample: IamServiceBlobSignerUsage // First obtain the email address of the default service account for this instance from the metadata server. HttpRequestMessage serviceAccountRequest = new HttpRequestMessage { // Note: you could use 169.254.169.254 as the address to avoid a DNS lookup. RequestUri = new Uri("http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/email"), Headers = { { "Metadata-Flavor", "Google" } } }; HttpResponseMessage serviceAccountResponse = await httpClient.SendAsync(serviceAccountRequest).ConfigureAwait(false); serviceAccountResponse.EnsureSuccessStatusCode(); string serviceAccountId = await serviceAccountResponse.Content.ReadAsStringAsync(); // Create an IAM service client object using the default application credentials. GoogleCredential iamCredential = await GoogleCredential.GetApplicationDefaultAsync(); iamCredential = iamCredential.CreateScoped(IamService.Scope.CloudPlatform); IamService iamService = new IamService(new BaseClientService.Initializer { HttpClientInitializer = iamCredential }); // Create a request template that will be used to create the signed URL. UrlSigner.RequestTemplate requestTemplate = UrlSigner.RequestTemplate .FromBucket(bucketName) .WithObjectName(objectName) .WithHttpMethod(HttpMethod.Get); // Create options specifying for how long the signer URL will be valid. UrlSigner.Options options = UrlSigner.Options.FromDuration(TimeSpan.FromHours(1)); // Create a URL signer that will use the IAM service for signing. This signer is thread-safe, // and would typically occur as a dependency, e.g. in an ASP.NET Core controller, where the // same instance can be reused for each request. IamServiceBlobSigner blobSigner = new IamServiceBlobSigner(iamService, serviceAccountId); UrlSigner urlSigner = UrlSigner.FromBlobSigner(blobSigner); // Use the URL signer to sign a request for the test object for the next hour. string url = await urlSigner.SignAsync(requestTemplate, options); // Prove we can fetch the content of the test object with a simple unauthenticated GET request. HttpResponseMessage response = await httpClient.GetAsync(url); string content = await response.Content.ReadAsStringAsync(); // End sample Assert.Equal(_fixture.HelloWorldContent, content); } [Fact] public async Task PostPolicySimple() { var bucketName = _fixture.BucketName; var objectName = "places/world.txt"; var credential = (await GoogleCredential.GetApplicationDefaultAsync()).UnderlyingCredential as ServiceAccountCredential; // Sample: PostPolicySimple // [START storage_generate_signed_post_policy_v4] // Create a signed post policy which can be used to upload a specific object and // expires in 1 hour after creation. UrlSigner urlSigner = UrlSigner .FromServiceAccountCredential(credential); UrlSigner.Options options = UrlSigner.Options .FromDuration(TimeSpan.FromHours(1)) .WithSigningVersion(SigningVersion.V4) .WithScheme("https"); UrlSigner.PostPolicy postPolicy = UrlSigner.PostPolicy.ForBucketAndKey(bucketName, objectName); postPolicy.SetCustomField(UrlSigner.PostPolicyCustomElement.GoogleMetadata, "x-goog-meta-test", "data"); UrlSigner.SignedPostPolicy signedPostPolicy = await urlSigner.SignAsync(postPolicy, options); // Create an HTML form including all the fields in the signed post policy. StringBuilder form = new StringBuilder(); form.AppendLine($"<form action=\"{signedPostPolicy.PostUrl}\" method=\"post\" enctype=\"multipart/form-data\">"); foreach (var field in signedPostPolicy.Fields) { form.AppendLine($"<input type=\"hidden\" name=\"{field.Key}\" value=\"{field.Value}\">"); } // Include the file element. It should always be the last element in the form. form.AppendLine("<input name=\"file\" type=\"file\">"); form.AppendLine("<input type=\"submit\" value=\"Upload\">"); form.AppendLine("</form>"); // You can now save the form to file and serve it as static content // or send it as the response to a request made to your application. File.WriteAllText("PostPolicySimple.html", form.ToString()); // [END storage_generate_signed_post_policy_v4] //// End sample Assert.Contains(signedPostPolicy.PostUrl.ToString(), form.ToString()); File.Delete("PostPolicySimple.html"); } [Fact] public async Task PostPolicyCacheControl() { var bucketName = _fixture.BucketName; var objectName = "places/world.txt"; var credential = (await GoogleCredential.GetApplicationDefaultAsync()).UnderlyingCredential as ServiceAccountCredential; // Sample: PostPolicyCacheControl // Create a signed post policy which can be used to upload a specific object with a // specific cache-control value and expires in 1 hour after creation. UrlSigner urlSigner = UrlSigner .FromServiceAccountCredential(credential); UrlSigner.Options options = UrlSigner.Options .FromDuration(TimeSpan.FromHours(1)) .WithSigningVersion(SigningVersion.V4) .WithScheme("https"); UrlSigner.PostPolicy postPolicy = UrlSigner.PostPolicy.ForBucketAndKey(bucketName, objectName); postPolicy.SetField(UrlSigner.PostPolicyStandardElement.Acl, "public-read"); postPolicy.SetField(UrlSigner.PostPolicyStandardElement.CacheControl, "public,max-age=86400"); UrlSigner.SignedPostPolicy signedPostPolicy = await urlSigner.SignAsync(postPolicy, options); // Create an HTML form including all the fields in the signed post policy. StringBuilder form = new StringBuilder(); form.AppendLine($"<form action=\"{signedPostPolicy.PostUrl}\" method=\"post\" enctype=\"multipart/form-data\">"); foreach (var field in signedPostPolicy.Fields) { form.AppendLine($"<input type=\"hidden\" name=\"{field.Key}\" value=\"{field.Value}\">"); } // Include the file element. It should always be the last element in the form. form.AppendLine("<input name=\"file\" type=\"file\">"); form.AppendLine("<input type=\"submit\" value=\"Upload\">"); form.AppendLine("</form>"); // You can now save the form to file and serve it as static content // or send it as the response to a request made to your application. File.WriteAllText("PostPolicyCacheControl.html", form.ToString()); //// End sample Assert.Contains(signedPostPolicy.PostUrl.ToString(), form.ToString()); File.Delete("PostPolicyCacheControl.html"); } [Fact] public async Task PostPolicyAcl() { var bucketName = _fixture.BucketName; var objectName = "places/world.txt"; var credential = (await GoogleCredential.GetApplicationDefaultAsync()).UnderlyingCredential as ServiceAccountCredential; // Sample: PostPolicyAcl // Create a signed post policy which can be used to upload a specific object and // expires in 10 seconds after creation. // It also sets a starts-with condition on the acl form element, that should be met // by the actual form used for posting. UrlSigner urlSigner = UrlSigner .FromServiceAccountCredential(credential); UrlSigner.Options options = UrlSigner.Options .FromDuration(TimeSpan.FromHours(1)) .WithSigningVersion(SigningVersion.V4) .WithScheme("https"); UrlSigner.PostPolicy postPolicy = UrlSigner.PostPolicy.ForBucketAndKey(bucketName, objectName); postPolicy.SetStartsWith(UrlSigner.PostPolicyStandardElement.Acl, "public"); UrlSigner.SignedPostPolicy signedPostPolicy = await urlSigner.SignAsync(postPolicy, options); // Create an HTML form including all the fields in the signed post policy. StringBuilder form = new StringBuilder(); form.AppendLine($"<form action=\"{signedPostPolicy.PostUrl}\" method=\"post\" enctype=\"multipart/form-data\">"); foreach (var field in signedPostPolicy.Fields) { form.AppendLine($"<input type=\"hidden\" name=\"{field.Key}\" value=\"{field.Value}\">"); } // Include also an acl element with a value that meets the condition set in the policy. form.AppendLine("<input type=\"hidden\" name=\"acl\" value=\"public-read\">"); // Include the file element. It should always be the last element in the form. form.AppendLine("<input name=\"file\" type=\"file\">"); form.AppendLine("<input type=\"submit\" value=\"Upload\">"); form.AppendLine("</form>"); // You can now save the form to file and serve it as static content // or send it as the response to a request made to your application. File.WriteAllText("PostPolicyAcl.html", form.ToString()); //// End sample Assert.Contains(signedPostPolicy.PostUrl.ToString(), form.ToString()); File.Delete("PostPolicyAcl.html"); } [Fact] public async Task PostPolicySuccessStatus() { var bucketName = _fixture.BucketName; var objectName = "places/world.txt"; var credential = (await GoogleCredential.GetApplicationDefaultAsync()).UnderlyingCredential as ServiceAccountCredential; // Sample: PostPolicySuccessStatus // Create a signed post policy which can be used to upload a specific object and // expires in 1 hour after creation. // It also sets a specific HTTP success satus code that should be returned. // Only 200, 201 and 204 are allowed. UrlSigner urlSigner = UrlSigner .FromServiceAccountCredential(credential); UrlSigner.Options options = UrlSigner.Options .FromDuration(TimeSpan.FromHours(1)) .WithSigningVersion(SigningVersion.V4) .WithScheme("https"); UrlSigner.PostPolicy postPolicy = UrlSigner.PostPolicy.ForBucketAndKey(bucketName, objectName); postPolicy.SetField(UrlSigner.PostPolicyStandardElement.SuccessActionStatus, HttpStatusCode.OK); UrlSigner.SignedPostPolicy signedPostPolicy = await urlSigner.SignAsync(postPolicy, options); // Create an HTML form including all the fields in the signed post policy. StringBuilder form = new StringBuilder(); form.AppendLine($"<form action=\"{signedPostPolicy.PostUrl}\" method=\"post\" enctype=\"multipart/form-data\">"); foreach (var field in signedPostPolicy.Fields) { form.AppendLine($"<input type=\"hidden\" name=\"{field.Key}\" value=\"{field.Value}\">"); } // Include the file element. It should always be the last element in the form. form.AppendLine("<input name=\"file\" type=\"file\">"); form.AppendLine("<input type=\"submit\" value=\"Upload\">"); form.AppendLine("</form>"); // You can now save the form to file and serve it as static content // or send it as the response to a request made to your application. File.WriteAllText("PostPolicySuccessStatus.html", form.ToString()); //// End sample Assert.Contains(signedPostPolicy.PostUrl.ToString(), form.ToString()); File.Delete("PostPolicySuccessStatus.html"); } } }
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Text.RegularExpressions; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Orleans.CodeGenerator.Analyzers; using Orleans.CodeGenerator.Model; using Orleans.CodeGenerator.Utilities; using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; using ITypeSymbol = Microsoft.CodeAnalysis.ITypeSymbol; namespace Orleans.CodeGenerator.Generators { /// <summary> /// Code generator which generates serializers. /// Sample of generated serializer: /// [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Orleans-CodeGenerator", "2.0.0.0"), global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverageAttribute, global::Orleans.CodeGeneration.SerializerAttribute(typeof(global::MyType))] /// internal sealed class OrleansCodeGenUnitTests_GrainInterfaces_MyTypeSerializer /// { /// private readonly global::System.Func&lt;global::MyType, global::System.Int32&gt; getField0; /// private readonly global::System.Action&lt;global::MyType, global::System.Int32&gt; setField0; /// public OrleansCodeGenUnitTests_GrainInterfaces_MyTypeSerializer(global::Orleans.Serialization.IFieldUtils fieldUtils) /// { /// [...] /// } /// [global::Orleans.CodeGeneration.CopierMethodAttribute] /// public global::System.Object DeepCopier(global::System.Object original, global::Orleans.Serialization.ICopyContext context) /// { /// [...] /// } /// [global::Orleans.CodeGeneration.SerializerMethodAttribute] /// public void Serializer(global::System.Object untypedInput, global::Orleans.Serialization.ISerializationContext context, global::System.Type expected) /// { /// [...] /// } /// [global::Orleans.CodeGeneration.DeserializerMethodAttribute] /// public global::System.Object Deserializer(global::System.Type expected, global::Orleans.Serialization.IDeserializationContext context) /// { /// [...] /// } ///} /// </summary> internal class SerializerGenerator { /// <summary> /// The suffix appended to the name of generated classes. /// </summary> private const string ClassSuffix = "Serializer"; private readonly CodeGeneratorOptions options; private readonly WellKnownTypes wellKnownTypes; public SerializerGenerator(CodeGeneratorOptions options, WellKnownTypes wellKnownTypes) { this.options = options; this.wellKnownTypes = wellKnownTypes; } private readonly ConcurrentDictionary<ITypeSymbol, bool> ShallowCopyableTypes = new ConcurrentDictionary<ITypeSymbol, bool>(SymbolEqualityComparer.Default); /// <summary> /// Returns the name of the generated class for the provided type. /// </summary> /// <param name="type">The type.</param> /// <returns>The name of the generated class for the provided type.</returns> internal string GetGeneratedClassName(INamedTypeSymbol type) { var parts = type.ToDisplayParts(SymbolDisplayFormat.FullyQualifiedFormat .WithGlobalNamespaceStyle(SymbolDisplayGlobalNamespaceStyle.Omitted) .WithMiscellaneousOptions(SymbolDisplayMiscellaneousOptions.None) .WithGenericsOptions(SymbolDisplayGenericsOptions.None) .WithKindOptions(SymbolDisplayKindOptions.None) .WithLocalOptions(SymbolDisplayLocalOptions.None) .WithMemberOptions(SymbolDisplayMemberOptions.None) .WithParameterOptions(SymbolDisplayParameterOptions.None)); var b = new StringBuilder(); foreach (var part in parts) { // Add the class prefix after the type name. switch (part.Kind) { case SymbolDisplayPartKind.Punctuation: b.Append('_'); break; case SymbolDisplayPartKind.ClassName: case SymbolDisplayPartKind.InterfaceName: case SymbolDisplayPartKind.StructName: b.Append(part.ToString().TrimStart('@')); b.Append(ClassSuffix); break; default: b.Append(part.ToString().TrimStart('@')); break; } } return CodeGenerator.ToolName + b; } /// <summary> /// Generates the non serializer class for the provided grain types. /// </summary> internal (TypeDeclarationSyntax, TypeSyntax) GenerateClass(IGeneratorExecutionContext context, SemanticModel model, SerializerTypeDescription description) { var className = GetGeneratedClassName(description.Target); var type = description.Target; var genericTypes = type.GetHierarchyTypeParameters().Select(_ => TypeParameter(_.ToString())).ToArray(); var attributes = new List<AttributeSyntax> { GeneratedCodeAttributeGenerator.GetGeneratedCodeAttributeSyntax(wellKnownTypes), Attribute(wellKnownTypes.ExcludeFromCodeCoverageAttribute.ToNameSyntax()), Attribute(wellKnownTypes.SerializerAttribute.ToNameSyntax()) .AddArgumentListArguments( AttributeArgument(TypeOfExpression(type.WithoutTypeParameters().ToTypeSyntax()))) }; var fields = GetFields(context, model, type); var members = new List<MemberDeclarationSyntax>(GenerateFields(fields)) { GenerateConstructor(className, fields), GenerateDeepCopierMethod(type, fields, model), GenerateSerializerMethod(type, fields, model), GenerateDeserializerMethod(type, fields, model), }; var classDeclaration = ClassDeclaration(className) .AddModifiers(Token(SyntaxKind.InternalKeyword)) .AddModifiers(Token(SyntaxKind.SealedKeyword)) .AddAttributeLists(AttributeList().AddAttributes(attributes.ToArray())) .AddMembers(members.ToArray()) .AddConstraintClauses(type.GetTypeConstraintSyntax()); if (genericTypes.Length > 0) { classDeclaration = classDeclaration.AddTypeParameterListParameters(genericTypes); } if (this.options.DebuggerStepThrough) { var debuggerStepThroughAttribute = Attribute(this.wellKnownTypes.DebuggerStepThroughAttribute.ToNameSyntax()); classDeclaration = classDeclaration.AddAttributeLists(AttributeList().AddAttributes(debuggerStepThroughAttribute)); } return (classDeclaration, ParseTypeName(type.GetParsableReplacementName(className))); } private MemberDeclarationSyntax GenerateConstructor(string className, List<FieldInfoMember> fields) { var body = new List<StatementSyntax>(); // Expressions for specifying binding flags. var bindingFlags = SymbolSyntaxExtensions.GetBindingFlagsParenthesizedExpressionSyntax( SyntaxKind.BitwiseOrExpression, BindingFlags.Instance, BindingFlags.NonPublic, BindingFlags.Public); var fieldUtils = IdentifierName("fieldUtils"); foreach (var field in fields) { // Get the field var fieldInfoField = IdentifierName(field.InfoFieldName); var fieldInfo = InvocationExpression(TypeOfExpression(field.Field.ContainingType.ToTypeSyntax()).Member("GetField")) .AddArgumentListArguments( Argument(field.Field.Name.ToLiteralExpression()), Argument(bindingFlags)); var fieldInfoVariable = VariableDeclarator(field.InfoFieldName).WithInitializer(EqualsValueClause(fieldInfo)); if (!field.IsGettableProperty || !field.IsSettableProperty) { body.Add(LocalDeclarationStatement( VariableDeclaration(wellKnownTypes.FieldInfo.ToTypeSyntax()).AddVariables(fieldInfoVariable))); } // Set the getter/setter of the field if (!field.IsGettableProperty) { var getterType = wellKnownTypes.Func_2.Construct(field.Field.ContainingType, field.SafeType).ToTypeSyntax(); var getterInvoke = CastExpression( getterType, InvocationExpression(fieldUtils.Member("GetGetter")).AddArgumentListArguments(Argument(fieldInfoField))); body.Add(ExpressionStatement( AssignmentExpression(SyntaxKind.SimpleAssignmentExpression, IdentifierName(field.GetterFieldName), getterInvoke))); } if (!field.IsSettableProperty) { if (field.Field.ContainingType != null && field.Field.ContainingType.IsValueType) { var setterType = wellKnownTypes.ValueTypeSetter_2.Construct(field.Field.ContainingType, field.SafeType).ToTypeSyntax(); var getValueSetterInvoke = CastExpression( setterType, InvocationExpression(fieldUtils.Member("GetValueSetter")) .AddArgumentListArguments(Argument(fieldInfoField))); body.Add(ExpressionStatement( AssignmentExpression(SyntaxKind.SimpleAssignmentExpression, IdentifierName(field.SetterFieldName), getValueSetterInvoke))); } else { var setterType = wellKnownTypes.Action_2.Construct(field.Field.ContainingType, field.SafeType).ToTypeSyntax(); var getReferenceSetterInvoke = CastExpression( setterType, InvocationExpression(fieldUtils.Member("GetReferenceSetter")) .AddArgumentListArguments(Argument(fieldInfoField))); body.Add(ExpressionStatement( AssignmentExpression(SyntaxKind.SimpleAssignmentExpression, IdentifierName(field.SetterFieldName), getReferenceSetterInvoke))); } } } return ConstructorDeclaration(className) .AddModifiers(Token(SyntaxKind.PublicKeyword)) .AddParameterListParameters( Parameter(fieldUtils.Identifier).WithType(wellKnownTypes.IFieldUtils.ToTypeSyntax())) .AddBodyStatements(body.ToArray()); } /// <summary> /// Returns syntax for the deserializer method. /// </summary> private MemberDeclarationSyntax GenerateDeserializerMethod(INamedTypeSymbol type, List<FieldInfoMember> fields, SemanticModel model) { var contextParameter = IdentifierName("context"); var resultDeclaration = LocalDeclarationStatement( VariableDeclaration(type.ToTypeSyntax()) .AddVariables( VariableDeclarator("result") .WithInitializer(EqualsValueClause(GetObjectCreationExpressionSyntax(type, model))))); var resultVariable = IdentifierName("result"); var body = new List<StatementSyntax> { resultDeclaration }; // Value types cannot be referenced, only copied, so there is no need to box & record instances of value types. if (!type.IsValueType) { // Record the result for cyclic deserialization. var currentSerializationContext = contextParameter; body.Add( ExpressionStatement( InvocationExpression(currentSerializationContext.Member("RecordObject")) .AddArgumentListArguments(Argument(resultVariable)))); } // Deserialize all fields. foreach (var field in fields) { var deserialized = InvocationExpression(contextParameter.Member("DeserializeInner")) .AddArgumentListArguments( Argument(TypeOfExpression(field.Type))); body.Add( ExpressionStatement( field.GetSetter( resultVariable, CastExpression(field.Type, deserialized)))); } // If the type implements the internal IOnDeserialized lifecycle method, invoke it's method now. if (type.HasInterface(wellKnownTypes.IOnDeserialized)) { // C#: ((IOnDeserialized)result).OnDeserialized(context); var typedResult = ParenthesizedExpression(CastExpression(wellKnownTypes.IOnDeserialized.ToTypeSyntax(), resultVariable)); var invokeOnDeserialized = InvocationExpression(typedResult.Member("OnDeserialized")) .AddArgumentListArguments(Argument(contextParameter)); body.Add(ExpressionStatement(invokeOnDeserialized)); } body.Add(ReturnStatement(CastExpression(type.ToTypeSyntax(), resultVariable))); return MethodDeclaration(wellKnownTypes.Object.ToTypeSyntax(), "Deserializer") .AddModifiers(Token(SyntaxKind.PublicKeyword)) .AddParameterListParameters( Parameter(Identifier("expected")).WithType(wellKnownTypes.Type.ToTypeSyntax()), Parameter(Identifier("context")).WithType(wellKnownTypes.IDeserializationContext.ToTypeSyntax())) .AddBodyStatements(body.ToArray()) .AddAttributeLists( AttributeList() .AddAttributes(Attribute(wellKnownTypes.DeserializerMethodAttribute.ToNameSyntax()))); } private MemberDeclarationSyntax GenerateSerializerMethod(INamedTypeSymbol type, List<FieldInfoMember> fields, SemanticModel model) { var contextParameter = IdentifierName("context"); var body = new List<StatementSyntax> { LocalDeclarationStatement( VariableDeclaration(type.ToTypeSyntax()) .AddVariables( VariableDeclarator("input") .WithInitializer( EqualsValueClause( CastExpression(type.ToTypeSyntax(), IdentifierName("untypedInput")))))) }; var inputExpression = IdentifierName("input"); // Serialize all members. foreach (var field in fields) { body.Add( ExpressionStatement( InvocationExpression(contextParameter.Member("SerializeInner")) .AddArgumentListArguments( Argument(field.GetGetter(inputExpression, forceAvoidCopy: true)), Argument(TypeOfExpression(field.Type))))); } return MethodDeclaration(wellKnownTypes.Void.ToTypeSyntax(), "Serializer") .AddModifiers(Token(SyntaxKind.PublicKeyword)) .AddParameterListParameters( Parameter(Identifier("untypedInput")).WithType(wellKnownTypes.Object.ToTypeSyntax()), Parameter(Identifier("context")).WithType(wellKnownTypes.ISerializationContext.ToTypeSyntax()), Parameter(Identifier("expected")).WithType(wellKnownTypes.Type.ToTypeSyntax())) .AddBodyStatements(body.ToArray()) .AddAttributeLists( AttributeList() .AddAttributes(Attribute(wellKnownTypes.SerializerMethodAttribute.ToNameSyntax()))); } /// <summary> /// Returns syntax for the deep copy method. /// </summary> private MemberDeclarationSyntax GenerateDeepCopierMethod(INamedTypeSymbol type, List<FieldInfoMember> fields, SemanticModel model) { var originalVariable = IdentifierName("original"); var body = new List<StatementSyntax>(); if (type.HasAttribute(wellKnownTypes.ImmutableAttribute) || SymbolEqualityComparer.Default.Equals(wellKnownTypes.Immutable_1, type)) { // Immutable types do not require copying. var typeName = type.ToDisplayString(); var comment = Comment($"// No deep copy required since {typeName} is marked with the [Immutable] attribute."); body.Add(ReturnStatement(originalVariable).WithLeadingTrivia(comment)); } else { var inputVariable = IdentifierName("input"); body.Add( LocalDeclarationStatement( VariableDeclaration(type.ToTypeSyntax()) .AddVariables( VariableDeclarator("input") .WithInitializer( EqualsValueClause( ParenthesizedExpression( CastExpression(type.ToTypeSyntax(), originalVariable))))))); if (IsOrleansShallowCopyable(type)) { var comment = Comment($"// {type.ToDisplayString()} needs only a shallow copy."); body.Add(ReturnStatement(inputVariable).WithLeadingTrivia(comment)); } else { var resultVariable = IdentifierName("result"); body.Add( LocalDeclarationStatement( VariableDeclaration(type.ToTypeSyntax()) .AddVariables( VariableDeclarator("result") .WithInitializer(EqualsValueClause(GetObjectCreationExpressionSyntax(type, model)))))); var context = IdentifierName("context"); if (!type.IsValueType) { // Record this serialization. body.Add( ExpressionStatement( InvocationExpression(context.Member("RecordCopy")) .AddArgumentListArguments(Argument(originalVariable), Argument(resultVariable)))); } // Copy all members from the input to the result. foreach (var field in fields) { body.Add(ExpressionStatement(field.GetSetter(resultVariable, field.GetGetter(inputVariable, context)))); } body.Add(ReturnStatement(resultVariable)); } } return MethodDeclaration(wellKnownTypes.Object.ToTypeSyntax(), "DeepCopier") .AddModifiers(Token(SyntaxKind.PublicKeyword)) .AddParameterListParameters( Parameter(Identifier("original")).WithType(wellKnownTypes.Object.ToTypeSyntax()), Parameter(Identifier("context")).WithType(wellKnownTypes.ICopyContext.ToTypeSyntax())) .AddBodyStatements(body.ToArray()) .AddAttributeLists( AttributeList().AddAttributes(Attribute(wellKnownTypes.CopierMethodAttribute.ToNameSyntax()))); } /// <summary> /// Returns syntax for the fields of the serializer class. /// </summary> private MemberDeclarationSyntax[] GenerateFields(List<FieldInfoMember> fields) { var result = new List<MemberDeclarationSyntax>(); // Add each field and initialize it. foreach (var field in fields) { // Declare the getter for this field. if (!field.IsGettableProperty) { var getterType = wellKnownTypes.Func_2.Construct(field.Field.ContainingType, field.SafeType).ToTypeSyntax(); var fieldGetterVariable = VariableDeclarator(field.GetterFieldName); result.Add( FieldDeclaration(VariableDeclaration(getterType).AddVariables(fieldGetterVariable)) .AddModifiers( Token(SyntaxKind.PrivateKeyword), Token(SyntaxKind.ReadOnlyKeyword))); } if (!field.IsSettableProperty) { if (field.Field.ContainingType != null && field.Field.ContainingType.IsValueType) { var setterType = wellKnownTypes.ValueTypeSetter_2.Construct(field.Field.ContainingType, field.SafeType).ToTypeSyntax(); var fieldSetterVariable = VariableDeclarator(field.SetterFieldName); result.Add( FieldDeclaration(VariableDeclaration(setterType).AddVariables(fieldSetterVariable)) .AddModifiers( Token(SyntaxKind.PrivateKeyword), Token(SyntaxKind.ReadOnlyKeyword))); } else { var setterType = wellKnownTypes.Action_2.Construct(field.Field.ContainingType, field.SafeType).ToTypeSyntax(); var fieldSetterVariable = VariableDeclarator(field.SetterFieldName); result.Add( FieldDeclaration(VariableDeclaration(setterType).AddVariables(fieldSetterVariable)) .AddModifiers( Token(SyntaxKind.PrivateKeyword), Token(SyntaxKind.ReadOnlyKeyword))); } } } return result.ToArray(); } /// <summary> /// Returns syntax for initializing a new instance of the provided type. /// </summary> private ExpressionSyntax GetObjectCreationExpressionSyntax(INamedTypeSymbol type, SemanticModel model) { ExpressionSyntax result; if (type.IsValueType) { // Use the default value. result = DefaultExpression(type.ToTypeSyntax()); } else if (GetEmptyConstructor(type, model) != null) { // Use the default constructor. result = ObjectCreationExpression(type.ToTypeSyntax()).AddArgumentListArguments(); } else { // Create an unformatted object. result = CastExpression( type.ToTypeSyntax(), InvocationExpression(wellKnownTypes.FormatterServices.ToTypeSyntax().Member("GetUninitializedObject")) .AddArgumentListArguments( Argument(TypeOfExpression(type.ToTypeSyntax())))); } return result; } /// <summary> /// Return the default constructor on <paramref name="type"/> if found or null if not found. /// </summary> private IMethodSymbol GetEmptyConstructor(INamedTypeSymbol type, SemanticModel model) { return type.GetDeclaredInstanceMembers<IMethodSymbol>() .FirstOrDefault(method => method.MethodKind == MethodKind.Constructor && method.Parameters.Length == 0 && model.IsAccessible(0, method)); } /// <summary> /// Returns a sorted list of the fields of the provided type. /// </summary> private List<FieldInfoMember> GetFields(IGeneratorExecutionContext context, SemanticModel model, INamedTypeSymbol type) { var result = new List<FieldInfoMember>(); foreach (var field in type.GetDeclaredInstanceMembers<IFieldSymbol>()) { if (ShouldSerializeField(field)) { result.Add(new FieldInfoMember(this, model, type, field, result.Count)); } } if (type.TypeKind == TypeKind.Class) { // Some reference assemblies are compiled without private fields. // Warn the user if they are inheriting from a type in one of these assemblies using a heuristic: // If the type inherits from a type in a reference assembly and there are no fields declared on those // base types, emit a warning. var hasUnsupportedRefAsmBase = false; var referenceAssemblyHasFields = false; var baseType = type.BaseType; while (baseType != null && !SymbolEqualityComparer.Default.Equals(baseType, wellKnownTypes.Object) && !SymbolEqualityComparer.Default.Equals(baseType, wellKnownTypes.Attribute)) { if (!hasUnsupportedRefAsmBase && baseType.ContainingAssembly.HasAttribute("ReferenceAssemblyAttribute") && !IsSupportedRefAsmType(baseType)) { hasUnsupportedRefAsmBase = true; } foreach (var field in baseType.GetDeclaredInstanceMembers<IFieldSymbol>()) { if (hasUnsupportedRefAsmBase) referenceAssemblyHasFields = true; if (ShouldSerializeField(field)) { result.Add(new FieldInfoMember(this, model, type, field, result.Count)); } } baseType = baseType.BaseType; } if (hasUnsupportedRefAsmBase && !referenceAssemblyHasFields) { var declaration = type.DeclaringSyntaxReferences.FirstOrDefault()?.GetSyntax() as TypeDeclarationSyntax; context.ReportDiagnostic(RefAssemblyBaseTypeDiagnosticAnalyzer.CreateDiagnostic(declaration)); } bool IsSupportedRefAsmType(INamedTypeSymbol t) { INamedTypeSymbol baseDefinition; if (t.IsGenericType && !t.IsUnboundGenericType) { baseDefinition = t.ConstructUnboundGenericType().OriginalDefinition; } else { baseDefinition = t.OriginalDefinition; } foreach (var refAsmType in wellKnownTypes.SupportedRefAsmBaseTypes) { if (SymbolEqualityComparer.Default.Equals(baseDefinition, refAsmType)) return true; } return false; } } result.Sort(FieldInfoMember.Comparer.Instance); return result; } /// <summary> /// Returns <see langowrd="true"/> if the provided field should be serialized, <see langword="false"/> otherwise. /// </summary> public bool ShouldSerializeField(IFieldSymbol symbol) { if (symbol.IsStatic) return false; if (symbol.HasAttribute(wellKnownTypes.NonSerializedAttribute)) return false; ITypeSymbol fieldType = symbol.Type; if (fieldType.TypeKind == TypeKind.Pointer) return false; if (fieldType.TypeKind == TypeKind.Delegate) return false; if (fieldType.SpecialType == SpecialType.System_IntPtr) return false; if (fieldType.SpecialType == SpecialType.System_UIntPtr) return false; if (symbol.ContainingType.HasBaseType(wellKnownTypes.MarshalByRefObject)) return false; return true; } internal bool IsOrleansShallowCopyable(ITypeSymbol type) { switch (type.SpecialType) { case SpecialType.System_Boolean: case SpecialType.System_Char: case SpecialType.System_SByte: case SpecialType.System_Byte: case SpecialType.System_Int16: case SpecialType.System_UInt16: case SpecialType.System_Int32: case SpecialType.System_UInt32: case SpecialType.System_Int64: case SpecialType.System_UInt64: case SpecialType.System_Decimal: case SpecialType.System_Single: case SpecialType.System_Double: case SpecialType.System_String: case SpecialType.System_DateTime: return true; } if (SymbolEqualityComparer.Default.Equals(wellKnownTypes.TimeSpan, type) || SymbolEqualityComparer.Default.Equals(wellKnownTypes.IPAddress, type) || SymbolEqualityComparer.Default.Equals(wellKnownTypes.IPEndPoint, type) || SymbolEqualityComparer.Default.Equals(wellKnownTypes.SiloAddress, type) || SymbolEqualityComparer.Default.Equals(wellKnownTypes.GrainId, type) || SymbolEqualityComparer.Default.Equals(wellKnownTypes.ActivationId, type) || SymbolEqualityComparer.Default.Equals(wellKnownTypes.ActivationAddress, type) || wellKnownTypes.CorrelationId is WellKnownTypes.Some correlationIdType && SymbolEqualityComparer.Default.Equals(correlationIdType.Value, type) || SymbolEqualityComparer.Default.Equals(wellKnownTypes.CancellationToken, type) || SymbolEqualityComparer.Default.Equals(wellKnownTypes.Type, type)) return true; if (ShallowCopyableTypes.TryGetValue(type, out var result)) return result; if (type.HasAttribute(wellKnownTypes.ImmutableAttribute)) { return ShallowCopyableTypes[type] = true; } if (type.HasBaseType(wellKnownTypes.Exception)) { return ShallowCopyableTypes[type] = true; } if (!(type is INamedTypeSymbol namedType)) { return ShallowCopyableTypes[type] = false; } if (namedType.IsTupleType) { return ShallowCopyableTypes[type] = namedType.TupleElements.All(f => IsOrleansShallowCopyable(f.Type)); } else if (namedType.IsGenericType) { var def = namedType.ConstructedFrom; if (def.SpecialType == SpecialType.System_Nullable_T) { return ShallowCopyableTypes[type] = IsOrleansShallowCopyable(namedType.TypeArguments.Single()); } if (SymbolEqualityComparer.Default.Equals(wellKnownTypes.Immutable_1, def)) { return ShallowCopyableTypes[type] = true; } if (wellKnownTypes.TupleTypes.Any(t => SymbolEqualityComparer.Default.Equals(t, def))) { return ShallowCopyableTypes[type] = namedType.TypeArguments.All(IsOrleansShallowCopyable); } } else { if (type.TypeKind == TypeKind.Enum) { return ShallowCopyableTypes[type] = true; } if (type.TypeKind == TypeKind.Struct && !namedType.IsUnboundGenericType) { return ShallowCopyableTypes[type] = IsValueTypeFieldsShallowCopyable(type); } } return ShallowCopyableTypes[type] = false; } private bool IsValueTypeFieldsShallowCopyable(ITypeSymbol type) { foreach (var field in type.GetInstanceMembers<IFieldSymbol>()) { if (field.IsStatic) continue; if (!(field.Type is INamedTypeSymbol fieldType)) { return false; } if (SymbolEqualityComparer.Default.Equals(type, fieldType)) return false; if (!IsOrleansShallowCopyable(fieldType)) return false; } return true; } /// <summary> /// Represents a field. /// </summary> private class FieldInfoMember { private readonly SerializerGenerator generator; private readonly SemanticModel model; private readonly WellKnownTypes wellKnownTypes; private readonly INamedTypeSymbol targetType; private IPropertySymbol property; /// <summary> /// The ordinal assigned to this field. /// </summary> private readonly int ordinal; public FieldInfoMember(SerializerGenerator generator, SemanticModel model, INamedTypeSymbol targetType, IFieldSymbol field, int ordinal) { this.generator = generator; this.wellKnownTypes = generator.wellKnownTypes; this.model = model; this.targetType = targetType; this.Field = field; this.ordinal = ordinal; } /// <summary> /// Gets the underlying <see cref="Field"/> instance. /// </summary> public IFieldSymbol Field { get; } /// <summary> /// Gets a usable representation of the field type. /// </summary> /// <remarks> /// If the field is of type 'dynamic', we represent it as 'object' because 'dynamic' cannot appear in typeof expressions. /// </remarks> public ITypeSymbol SafeType => this.Field.Type.TypeKind == TypeKind.Dynamic ? this.wellKnownTypes.Object : this.Field.Type; /// <summary> /// Gets the name of the field info field. /// </summary> public string InfoFieldName => "field" + this.ordinal; /// <summary> /// Gets the name of the getter field. /// </summary> public string GetterFieldName => "getField" + this.ordinal; /// <summary> /// Gets the name of the setter field. /// </summary> public string SetterFieldName => "setField" + this.ordinal; /// <summary> /// Gets a value indicating whether or not this field represents a property with an accessible, non-obsolete getter. /// </summary> public bool IsGettableProperty => this.Property?.GetMethod != null && this.model.IsAccessible(0, this.Property.GetMethod) && !this.IsObsolete; /// <summary> /// Gets a value indicating whether or not this field represents a property with an accessible, non-obsolete setter. /// </summary> public bool IsSettableProperty => this.Property?.SetMethod != null && this.model.IsAccessible(0, this.Property.SetMethod) && !this.IsObsolete; /// <summary> /// Gets syntax representing the type of this field. /// </summary> public TypeSyntax Type => this.SafeType.ToTypeSyntax(); /// <summary> /// Gets the <see cref="Property"/> which this field is the backing property for, or /// <see langword="null" /> if this is not the backing field of an auto-property. /// </summary> private IPropertySymbol Property { get { if (this.property != null) { return this.property; } var propertyName = Regex.Match(this.Field.Name, "^<([^>]+)>.*$"); if (!propertyName.Success || this.Field.ContainingType == null) return null; var name = propertyName.Groups[1].Value; var candidates = this.targetType .GetInstanceMembers<IPropertySymbol>() .Where(p => string.Equals(name, p.Name, StringComparison.Ordinal) && !p.IsAbstract) .ToArray(); if (candidates.Length > 1) return null; if (!SymbolEqualityComparer.Default.Equals(this.SafeType, candidates[0].Type)) return null; return this.property = candidates[0]; } } /// <summary> /// Gets a value indicating whether or not this field is obsolete. /// </summary> private bool IsObsolete => this.Field.HasAttribute(this.wellKnownTypes.ObsoleteAttribute) || this.Property != null && this.Property.HasAttribute(this.wellKnownTypes.ObsoleteAttribute); /// <summary> /// Returns syntax for retrieving the value of this field, deep copying it if necessary. /// </summary> /// <param name="instance">The instance of the containing type.</param> /// <param name="serializationContextExpression">The expression used to retrieve the serialization context.</param> /// <param name="forceAvoidCopy">Whether or not to ensure that no copy of the field is made.</param> /// <returns>Syntax for retrieving the value of this field.</returns> public ExpressionSyntax GetGetter(ExpressionSyntax instance, ExpressionSyntax serializationContextExpression = null, bool forceAvoidCopy = false) { // Retrieve the value of the field. var getValueExpression = this.GetValueExpression(instance); // Avoid deep-copying the field if possible. if (forceAvoidCopy || generator.IsOrleansShallowCopyable(this.SafeType)) { // Return the value without deep-copying it. return getValueExpression; } // Addressable arguments must be converted to references before passing. // IGrainObserver instances cannot be directly converted to references, therefore they are not included. ExpressionSyntax deepCopyValueExpression; if (this.SafeType.HasInterface(this.wellKnownTypes.IAddressable) && this.SafeType.TypeKind == TypeKind.Interface && !this.SafeType.HasInterface(this.wellKnownTypes.IGrainObserver)) { var getAsReference = getValueExpression.Member("AsReference".ToGenericName().AddTypeArgumentListArguments(this.Type)); // If the value is not a GrainReference, convert it to a strongly-typed GrainReference. // C#: (value == null || value is GrainReference) ? value : value.AsReference<TInterface>() deepCopyValueExpression = ConditionalExpression( ParenthesizedExpression( BinaryExpression( SyntaxKind.LogicalOrExpression, BinaryExpression( SyntaxKind.EqualsExpression, getValueExpression, LiteralExpression(SyntaxKind.NullLiteralExpression)), BinaryExpression( SyntaxKind.IsExpression, getValueExpression, this.wellKnownTypes.GrainReference.ToTypeSyntax()))), getValueExpression, InvocationExpression(getAsReference)); } else { deepCopyValueExpression = getValueExpression; } // Deep-copy the value. return CastExpression( this.Type, InvocationExpression(serializationContextExpression.Member("DeepCopyInner")) .AddArgumentListArguments( Argument(deepCopyValueExpression))); } /// <summary> /// Returns syntax for setting the value of this field. /// </summary> /// <param name="instance">The instance of the containing type.</param> /// <param name="value">Syntax for the new value.</param> /// <returns>Syntax for setting the value of this field.</returns> public ExpressionSyntax GetSetter(ExpressionSyntax instance, ExpressionSyntax value) { // If the field is the backing field for an accessible auto-property use the property directly. if (this.IsSettableProperty) { return AssignmentExpression( SyntaxKind.SimpleAssignmentExpression, instance.Member(this.Property.Name), value); } var instanceArg = Argument(instance); if (this.Field.ContainingType != null && this.Field.ContainingType.IsValueType) { instanceArg = instanceArg.WithRefOrOutKeyword(Token(SyntaxKind.RefKeyword)); } return InvocationExpression(IdentifierName(this.SetterFieldName)) .AddArgumentListArguments(instanceArg, Argument(value)); } /// <summary> /// Returns syntax for retrieving the value of this field. /// </summary> /// <param name="instance">The instance of the containing type.</param> /// <returns>Syntax for retrieving the value of this field.</returns> private ExpressionSyntax GetValueExpression(ExpressionSyntax instance) { // If the field is the backing field for an accessible auto-property use the property directly. ExpressionSyntax result; if (this.IsGettableProperty) { result = instance.Member(this.Property.Name); } else { // Retrieve the field using the generated getter. result = InvocationExpression(IdentifierName(this.GetterFieldName)) .AddArgumentListArguments(Argument(instance)); } return result; } /// <summary> /// A comparer for <see cref="FieldInfoMember"/> which compares by name. /// </summary> public class Comparer : IComparer<FieldInfoMember> { /// <summary> /// Gets the singleton instance of this class. /// </summary> public static Comparer Instance { get; } = new Comparer(); public int Compare(FieldInfoMember x, FieldInfoMember y) { return string.Compare(x?.Field.Name, y?.Field.Name, StringComparison.Ordinal); } } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.AcceptanceTestsBodyDate { 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 Models; /// <summary> /// Date operations. /// </summary> public partial class Date : IServiceOperations<AutoRestDateTestService>, IDate { /// <summary> /// Initializes a new instance of the Date class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> public Date(AutoRestDateTestService client) { if (client == null) { throw new ArgumentNullException("client"); } this.Client = client; } /// <summary> /// Gets a reference to the AutoRestDateTestService /// </summary> public AutoRestDateTestService Client { get; private set; } /// <summary> /// Get null date value /// </summary> /// <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<HttpOperationResponse<DateTime?>> GetNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetNull", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "date/null").ToString(); // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers 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; // 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 ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.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 HttpOperationResponse<DateTime?>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<DateTime?>(_responseContent, new DateJsonConverter()); } 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> /// Get invalid date value /// </summary> /// <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<HttpOperationResponse<DateTime?>> GetInvalidDateWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetInvalidDate", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "date/invaliddate").ToString(); // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers 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; // 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 ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.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 HttpOperationResponse<DateTime?>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<DateTime?>(_responseContent, new DateJsonConverter()); } 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> /// Get overflow date value /// </summary> /// <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<HttpOperationResponse<DateTime?>> GetOverflowDateWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetOverflowDate", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "date/overflowdate").ToString(); // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers 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; // 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 ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.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 HttpOperationResponse<DateTime?>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<DateTime?>(_responseContent, new DateJsonConverter()); } 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> /// Get underflow date value /// </summary> /// <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<HttpOperationResponse<DateTime?>> GetUnderflowDateWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetUnderflowDate", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "date/underflowdate").ToString(); // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers 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; // 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 ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.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 HttpOperationResponse<DateTime?>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<DateTime?>(_responseContent, new DateJsonConverter()); } 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> /// Put max date value 9999-12-31 /// </summary> /// <param name='dateBody'> /// </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<HttpOperationResponse> PutMaxDateWithHttpMessagesAsync(DateTime dateBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("dateBody", dateBody); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "PutMaxDate", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "date/max").ToString(); // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new Uri(_url); // Set Headers 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(dateBody, new DateJsonConverter()); _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); // 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 ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.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 HttpOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get max date value 9999-12-31 /// </summary> /// <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<HttpOperationResponse<DateTime?>> GetMaxDateWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetMaxDate", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "date/max").ToString(); // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers 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; // 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 ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.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 HttpOperationResponse<DateTime?>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<DateTime?>(_responseContent, new DateJsonConverter()); } 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> /// Put min date value 0000-01-01 /// </summary> /// <param name='dateBody'> /// </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<HttpOperationResponse> PutMinDateWithHttpMessagesAsync(DateTime dateBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("dateBody", dateBody); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "PutMinDate", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "date/min").ToString(); // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new Uri(_url); // Set Headers 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(dateBody, new DateJsonConverter()); _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); // 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 ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.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 HttpOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get min date value 0000-01-01 /// </summary> /// <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<HttpOperationResponse<DateTime?>> GetMinDateWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetMinDate", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "date/min").ToString(); // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers 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; // 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 ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.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 HttpOperationResponse<DateTime?>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<DateTime?>(_responseContent, new DateJsonConverter()); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
// *********************************************************************** // Copyright (c) 2004 Charlie Poole, Rob Prouse // // 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 NET20 || NET35 || NET40 || NET45 using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Security; using System.Security.Permissions; using System.Security.Policy; namespace NUnit.Framework.Assertions { [TestFixture] [Platform(Exclude = "Mono,MonoTouch", Reason = "Mono does not implement Code Access Security")] public class LowTrustFixture { private TestSandBox _sandBox; [OneTimeSetUp] public void CreateSandBox() { _sandBox = new TestSandBox(); } [OneTimeTearDown] public void DisposeSandBox() { if (_sandBox != null) { _sandBox.Dispose(); _sandBox = null; } } [Test] public void AssertEqualityInLowTrustSandBox() { _sandBox.Run(() => { Assert.That(1, Is.EqualTo(1)); }); } [Test] public void AssertEqualityWithToleranceInLowTrustSandBox() { _sandBox.Run(() => { Assert.That(10.5, Is.EqualTo(10.5)); }); } [Test] public void AssertThrowsInLowTrustSandBox() { _sandBox.Run(() => { Assert.Throws<SecurityException>(() => new SecurityPermission(SecurityPermissionFlag.Infrastructure).Demand()); }); } } /// <summary> /// A facade for an <see cref="AppDomain"/> with partial trust privileges. /// </summary> public class TestSandBox : IDisposable { private AppDomain _appDomain; #region Constructor(s) /// <summary> /// Creates a low trust <see cref="TestSandBox"/> instance. /// </summary> /// <param name="fullTrustAssemblies">Strong named assemblies that will have full trust in the sandbox.</param> public TestSandBox(params Assembly[] fullTrustAssemblies) : this(null, fullTrustAssemblies) { } /// <summary> /// Creates a partial trust <see cref="TestSandBox"/> instance with a given set of permissions. /// </summary> /// <param name="permissions">Optional <see cref="TestSandBox"/> permission set. By default a minimal trust /// permission set is used.</param> /// <param name="fullTrustAssemblies">Strong named assemblies that will have full trust in the sandbox.</param> public TestSandBox(PermissionSet permissions, params Assembly[] fullTrustAssemblies) { var setup = new AppDomainSetup { ApplicationBase = AppDomain.CurrentDomain.BaseDirectory }; var strongNames = new HashSet<StrongName>(); // Grant full trust to NUnit.Framework assembly to enable use of NUnit assertions in sandboxed test code. strongNames.Add(GetStrongName(typeof(TestAttribute).Assembly)); if (fullTrustAssemblies != null) { foreach (var assembly in fullTrustAssemblies) { strongNames.Add(GetStrongName(assembly)); } } _appDomain = AppDomain.CreateDomain( "TestSandBox" + DateTime.Now.Ticks, null, setup, permissions ?? GetLowTrustPermissionSet(), strongNames.ToArray()); } #endregion #region Finalizer and Dispose methods /// <summary> /// The <see cref="TestSandBox"/> finalizer. /// </summary> ~TestSandBox() { Dispose(false); } /// <summary> /// Unloads the <see cref="AppDomain"/>. /// </summary> public void Dispose() { Dispose(true); } /// <summary> /// Unloads the <see cref="AppDomain"/>. /// </summary> /// <param name="disposing">Indicates whether this method is called from <see cref="Dispose()"/>.</param> protected virtual void Dispose(bool disposing) { if (_appDomain != null) { AppDomain.Unload(_appDomain); _appDomain = null; } } #endregion #region PermissionSet factory methods public static PermissionSet GetLowTrustPermissionSet() { var permissions = new PermissionSet(PermissionState.None); permissions.AddPermission(new SecurityPermission( SecurityPermissionFlag.Execution | // Required to execute test code SecurityPermissionFlag.SerializationFormatter)); // Required to support cross-appdomain test result formatting by NUnit TestContext permissions.AddPermission(new ReflectionPermission( ReflectionPermissionFlag.MemberAccess)); // Required to instantiate classes that contain test code and to get cross-appdomain communication to work. return permissions; } #endregion #region Run methods public T Run<T>(Func<T> func) { return (T)Run(func.Method); } public void Run(Action action) { Run(action.Method); } public object Run(MethodInfo method, params object[] parameters) { if (method == null) throw new ArgumentNullException(nameof(method)); if (_appDomain == null) throw new ObjectDisposedException(null); var methodRunnerType = typeof(MethodRunner); var methodRunnerProxy = (MethodRunner)_appDomain.CreateInstanceAndUnwrap( methodRunnerType.Assembly.FullName, methodRunnerType.FullName); try { return methodRunnerProxy.Run(method, parameters); } catch (Exception e) { throw e is TargetInvocationException ? e.InnerException : e; } } #endregion #region Private methods private static StrongName GetStrongName(Assembly assembly) { AssemblyName assemblyName = assembly.GetName(); byte[] publicKey = assembly.GetName().GetPublicKey(); if (publicKey == null || publicKey.Length == 0) { throw new InvalidOperationException("Assembly is not strongly named"); } return new StrongName(new StrongNamePublicKeyBlob(publicKey), assemblyName.Name, assemblyName.Version); } #endregion #region Inner classes [Serializable] internal class MethodRunner : MarshalByRefObject { public object Run(MethodInfo method, params object[] parameters) { var instance = method.IsStatic ? null : Activator.CreateInstance(method.ReflectedType); try { return method.Invoke(instance, parameters); } catch (TargetInvocationException e) { if (e.InnerException == null) throw; throw e.InnerException; } } } #endregion } } #endif
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using BugLoggingSystem.Api.Areas.HelpPage.ModelDescriptions; using BugLoggingSystem.Api.Areas.HelpPage.Models; namespace BugLoggingSystem.Api.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
#region Using Statements using System; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Storage; using Microsoft.Xna.Framework.Input; using MonoFlixel; #endregion namespace MonoFlixel.Examples { public class Enemy : FlxSprite { protected String ImgBot = "Mode/bot.png"; protected String ImgJet = "Mode/jet.png"; protected String SndExplode = "Mode/asplode.mp3"; protected String SndHit = "Mode/hit.mp3"; protected String SndJet = "Mode/jet.mp3"; //References to other game objects: protected Player _player; //The player object protected FlxGroup _bullets; //A group of enemy bullet objects (Enemies shoot these out) protected FlxEmitter _gibs; //A group of bits and pieces that explode when the Enemy dies. //We use this number to figure out how fast the ship is flying protected float _thrust; //A special effect - little poofs shoot out the back of the ship protected FlxEmitter _jets; //These are "timers" - numbers that count down until we want something interesting to happen. protected float _timer; //Helps us decide when to fly and when to stop flying. protected float _shotClock; //Helps us decide when to shoot. //This object isn't strictly necessary, and is only used with getMidpoint(). //By passing this object, we can avoid a potentially costly allocation of //a new FlxPoint() object by the getMidpoint() function. protected FlxPoint _playerMidpoint; private FlxSound _sfxExplode; private FlxSound _sfxHit; private FlxSound _sfxJet; //This is the constructor for the enemy class. Because we are //recycling enemies, we don't want our constructor to have any //required parameters. public Enemy() : base() { loadRotatedGraphic(ImgBot,64,0,false,true); //We want the enemy's "hit box" or actual size to be //smaller than the enemy graphic itself, just by a few pixels. Width = 12; Height = 12; centerOffsets(); //Here we are setting up the jet particles // that shoot out the back of the ship. _jets = new FlxEmitter(); _jets.setRotation(); //_jets.MakeParticles(ImgJet,15,0,false,0); //These parameters help control the ship's //speed and direction during the update() loop. MaxAngular = 120; AngularDrag = 400; Drag.X = 35; _thrust = 0; _playerMidpoint = new FlxPoint(); _sfxExplode = new FlxSound().loadEmbedded(SndExplode, false, false); _sfxHit = new FlxSound().loadEmbedded(SndHit, false, false); _sfxJet = new FlxSound().loadEmbedded(SndJet, false, false); } //Each time an Enemy is recycled (in this game, by the Spawner object) //we call init() on it afterward. That allows us to set critical parameters //like references to the player object and the ship's new position. public void init(int xPos,int yPos,FlxGroup Bullets,FlxEmitter Gibs,Player ThePlayer) { _player = ThePlayer; _bullets = Bullets; _gibs = Gibs; reset(xPos - Width/2,yPos - Height/2); Angle = angleTowardPlayer(); Health = 2; //Enemies take 2 shots to kill _timer = 0; _shotClock = 0; } //Called by flixel to help clean up memory. public override void destroy() { base.destroy(); _player = null; _bullets = null; _gibs = null; _jets.destroy(); _jets = null; _playerMidpoint = null; } //This is the main flixel update function or loop function. //Most of the enemy's logic or behavior is in this function here. public override void update() { //Then, rotate toward that angle. //We could rotate instantly toward the player by simply calling: //angle = angleTowardPlayer(); //However, we want some less predictable, more wobbly behavior. float da = angleTowardPlayer(); if(da < Angle) AngularAcceleration = -AngularDrag; else if(da > Angle) AngularAcceleration = AngularDrag; else AngularAcceleration = 0; //Figure out if we want the jets on or not. _timer += FlxG.elapsed; if(_timer > 8) _timer = 0; bool jetsOn = _timer < 6; //Set the bot's movement speed and direction //based on angle and whether the jets are on. _thrust = FlxU.computeVelocity(_thrust,(jetsOn?90:0),Drag.X,60); FlxU.rotatePoint(0,(int) _thrust,0,0,Angle,Velocity); //Shooting - three shots every few seconds if(onScreen()) { bool shoot = false; float os = _shotClock; _shotClock += FlxG.elapsed; if((os < 4.0) && (_shotClock >= 4.0)) { _shotClock = 0; shoot = true; } else if((os < 3.5) && (_shotClock >= 3.5)) shoot = true; else if((os < 3.0) && (_shotClock >= 3.0)) shoot = true; //If we rolled over one of those time thresholds, //shoot a bullet out along the angle we're currently facing. if(shoot) { //First, recycle a bullet from the bullet pile. //If there are none, recycle will automatically create one for us. EnemyBullet b = (EnemyBullet) _bullets.recycle(typeof(EnemyBullet)); //Then, shoot it from our midpoint out along our angle. b.shoot(getMidpoint(_tagPoint),Angle); } } //Then call FlxSprite's update() function, to automate // our motion and animation and stuff. base.update(); //Finally, update the jet particles shooting out the back of the ship. if(jetsOn) { if(!_jets.on) { //If they're supposed to be on and they're not, //turn em on and play a little sound. _jets.start(false,0.5f,0.01f); if(onScreen()) _sfxJet.play(true); } //Then, position the jets at the center of the Enemy, //and point the jets the opposite way from where we're moving. _jets.at(this); _jets.setXSpeed(-Velocity.X-30,-Velocity.X+30); _jets.setYSpeed(-Velocity.Y-30,-Velocity.Y+30); } else //If jets are supposed to be off, just turn em off. _jets.on = false; //Finally, update the jet emitter and all its member sprites. _jets.update(); } //Even though we updated the jets after we updated the Enemy, //we want to draw the jets below the Enemy, so we call _jets.draw() first. public override void draw() { _jets.draw(); base.draw(); } //This function is called when player bullets hit the Enemy. //The enemy is told to flicker, points are awarded to the player, //and damage is dealt to the Enemy. public void hurt(float Damage) { _sfxHit.play(true); flicker(0.2f); FlxG.score += 10; base.hurt(Damage); } //Called to kill the enemy. A cool sound is played, //the jets are turned off, bits are exploded, and points are rewarded. public override void kill() { if(!Alive) return; _sfxExplode.play(true); base.kill(); flicker(0); _jets.kill(); _gibs.at(this); _gibs.start(true,3,0,20); FlxG.score += 200; } //A helper function that returns the angle between //the Enemy's midpoint and the player's midpoint. protected float angleTowardPlayer() { return FlxU.getAngle(getMidpoint(_tagPoint),_player.getMidpoint(_playerMidpoint)); //return FlxU.getAngle(getMidpoint(_tagPoint),_player.getMidpoint(_playerMidpoint)); } } }
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics.Contracts; using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; using LanguageExt.Common; using LanguageExt.Effects.Traits; namespace LanguageExt.Pipes { /// <summary> /// Pipes both can both be `await` and can `yield` /// </summary> /// <remarks> /// Upstream | Downstream /// +---------+ /// | | /// Unit <== <== Unit /// | | /// IN ==> ==> OUT /// | | | /// +----|----+ /// | /// A /// </remarks> public class Pipe<RT, IN, OUT, A> : Proxy<RT, Unit, IN, Unit, OUT, A> where RT : struct, HasCancel<RT> { public readonly Proxy<RT, Unit, IN, Unit, OUT, A> Value; /// <summary> /// Constructor /// </summary> /// <param name="value">Correctly shaped `Proxy` that represents a `Pipe`</param> public Pipe(Proxy<RT, Unit, IN, Unit, OUT, A> value) => Value = value; /// <summary> /// Calling this will effectively cast the sub-type to the base. /// </summary> /// <remarks>This type wraps up a `Proxy` for convenience, and so it's a `Proxy` proxy. So calling this method /// isn't exactly the same as a cast operation, as it unwraps the `Proxy` from within. It has the same effect /// however, and removes a level of indirection</remarks> /// <returns>A general `Proxy` type from a more specialised type</returns> [Pure] public override Proxy<RT, Unit, IN, Unit, OUT, A> ToProxy() => Value.ToProxy(); /// <summary> /// Monadic bind operation, for chaining `Proxy` computations together. /// </summary> /// <param name="f">The bind function</param> /// <typeparam name="B">The mapped bound value type</typeparam> /// <returns>A new `Proxy` that represents the composition of this `Proxy` and the result of the bind operation</returns> [Pure] public override Proxy<RT, Unit, IN, Unit, OUT, S> Bind<S>(Func<A, Proxy<RT, Unit, IN, Unit, OUT, S>> f) => Value.Bind(f); /// <summary> /// Lifts a pure function into the `Proxy` domain, causing it to map the bound value within /// </summary> /// <param name="f">The map function</param> /// <typeparam name="B">The mapped bound value type</typeparam> /// <returns>A new `Proxy` that represents the composition of this `Proxy` and the result of the map operation</returns> [Pure] public override Proxy<RT, Unit, IN, Unit, OUT, S> Map<S>(Func<A, S> f) => Value.Map(f); /// <summary> /// Monadic bind operation, for chaining `Proxy` computations together. /// </summary> /// <param name="f">The bind function</param> /// <typeparam name="B">The mapped bound value type</typeparam> /// <returns>A new `Proxy` that represents the composition of this `Proxy` and the result of the bind operation</returns> [Pure] public Pipe<RT, IN, OUT, B> Bind<B>(Func<A, Pipe<RT, IN, OUT, B>> f) => Value.Bind(f).ToPipe(); /// <summary> /// Lifts a pure function into the `Proxy` domain, causing it to map the bound value within /// </summary> /// <param name="f">The map function</param> /// <typeparam name="B">The mapped bound value type</typeparam> /// <returns>A new `Proxy` that represents the composition of this `Proxy` and the result of the map operation</returns> [Pure] public new Pipe<RT, IN, OUT, B> Select<B>(Func<A, B> f) => Value.Map(f).ToPipe(); /// <summary> /// `For(body)` loops over the `Proxy p` replacing each `yield` with `body` /// </summary> /// <param name="body">Any `yield` found in the `Proxy` will be replaced with this function. It will be composed so /// that the value yielded will be passed to the argument of the function. That returns a `Proxy` to continue the /// processing of the computation</param> /// <returns>A new `Proxy` that represents the composition of this `Proxy` and the function provided</returns> [Pure] public override Proxy<RT, Unit, IN, C1, C, A> For<C1, C>(Func<OUT, Proxy<RT, Unit, IN, C1, C, Unit>> body) => Value.For(body); /// <summary> /// Applicative action /// /// Invokes this `Proxy`, then the `Proxy r` /// </summary> /// <param name="r">`Proxy` to run after this one</param> [Pure] public override Proxy<RT, Unit, IN, Unit, OUT, S> Action<S>(Proxy<RT, Unit, IN, Unit, OUT, S> r) => Value.Action(r); /// <summary> /// Used by the various composition functions and when composing proxies with the `|` operator. You usually /// wouldn't need to call this directly, instead either pipe them using `|` or call `Proxy.compose(lhs, rhs)` /// </summary> [Pure] public override Proxy<RT, UOutA, AUInA, Unit, OUT, A> ComposeRight<UOutA, AUInA>(Func<Unit, Proxy<RT, UOutA, AUInA, Unit, IN, A>> lhs) => Value.ComposeRight(lhs); /// <summary> /// Used by the various composition functions and when composing proxies with the `|` operator. You usually /// wouldn't need to call this directly, instead either pipe them using `|` or call `Proxy.compose(lhs, rhs)` /// </summary> [Pure] public override Proxy<RT, UOutA, AUInA, Unit, OUT, A> ComposeRight<UOutA, AUInA>(Func<Unit, Proxy<RT, UOutA, AUInA, Unit, OUT, IN>> lhs) => Value.ComposeRight(lhs); /// <summary> /// Used by the various composition functions and when composing proxies with the `|` operator. You usually /// wouldn't need to call this directly, instead either pipe them using `|` or call `Proxy.compose(lhs, rhs)` /// </summary> [Pure] public override Proxy<RT, Unit, IN, DInC, DOutC, A> ComposeLeft<DInC, DOutC>(Func<OUT, Proxy<RT, Unit, OUT, DInC, DOutC, A>> rhs) => Value.ComposeLeft(rhs); /// <summary> /// Used by the various composition functions and when composing proxies with the `|` operator. You usually /// wouldn't need to call this directly, instead either pipe them using `|` or call `Proxy.compose(lhs, rhs)` /// </summary> [Pure] public override Proxy<RT, Unit, IN, DInC, DOutC, A> ComposeLeft<DInC, DOutC>(Func<OUT, Proxy<RT, Unit, IN, DInC, DOutC, Unit>> rhs) => Value.ComposeLeft(rhs); /// <summary> /// Reverse the arrows of the `Proxy` to find its dual. /// </summary> /// <returns>The dual of `this`</returns> [Pure] public override Proxy<RT, OUT, Unit, IN, Unit, A> Reflect() => Value.Reflect(); /// <summary> /// /// Observe(lift (Pure(r))) = Observe(Pure(r)) /// Observe(lift (m.Bind(f))) = Observe(lift(m.Bind(x => lift(f(x))))) /// /// This correctness comes at a small cost to performance, so use this function sparingly. /// This function is a convenience for low-level pipes implementers. You do not need to /// use observe if you stick to the safe API. /// </summary> [Pure] public override Proxy<RT, Unit, IN, Unit, OUT, A> Observe() => Value.Observe(); [Pure] public void Deconstruct(out Proxy<RT, Unit, IN, Unit, OUT, A> value) => value = Value; /// <summary> /// Compose a `Producer` and a `Pipe` together into a `Producer`. /// </summary> /// <param name="p1">`Producer`</param> /// <param name="p2">`Pipe`</param> /// <returns>`Producer`</returns> [Pure] public static Producer<RT, OUT, A> operator |(Producer<RT, IN, A> p1, Pipe<RT, IN, OUT, A> p2) => Proxy.compose(p1, p2); /// <summary> /// Compose a `Producer` and a `Pipe` together into a `Producer`. /// </summary> /// <param name="p1">`Producer`</param> /// <param name="p2">`Pipe`</param> /// <returns>`Producer`</returns> [Pure] public static Producer<RT, OUT, A> operator |(Producer<IN, A> p1, Pipe<RT, IN, OUT, A> p2) => Proxy.compose(p1, p2); /// <summary> /// Compose a `Producer` and a `Pipe` together into a `Producer`. /// </summary> /// <param name="p1">`Producer`</param> /// <param name="p2">`Pipe`</param> /// <returns>`Producer`</returns> [Pure] public static Producer<RT, OUT, A> operator |(Producer<OUT, IN> p1, Pipe<RT, IN, OUT, A> p2) => Proxy.compose(p1, p2); /// <summary> /// Compose a `Pipe` and a `Consumer` together into a `Consumer`. /// </summary> /// <param name="p1">`Pipe`</param> /// <param name="p2">`Consumer`</param> /// <returns>`Consumer`</returns> [Pure] public static Consumer<RT, IN, A> operator |(Pipe<RT, IN, OUT, A> p1, Consumer<OUT, A> p2) => Proxy.compose(p1, p2); /// <summary> /// Compose a `Pipe` and a `Consumer` together into a `Consumer`. /// </summary> /// <param name="p1">`Pipe`</param> /// <param name="p2">`Consumer`</param> /// <returns>`Consumer`</returns> [Pure] public static Consumer<RT, IN, A> operator |(Pipe<RT, IN, OUT, A> p1, Consumer<RT, OUT, A> p2) => Proxy.compose(p1, p2); /// <summary> /// Composition chaining of two pipes. /// </summary> /// <remarks> /// We can't provide the operator overloading to chain two pipes together, because operators don't have /// generics of their own. And so we can use this method to chain to pipes together. /// </remarks> /// <param name="pipe">Right hand side `Pipe`</param> /// <typeparam name="C">Type of value that the right hand side pipe yields</typeparam> /// <returns>A composition of this pipe and the `Pipe` provided</returns> [Pure] public Pipe<RT, IN, C, A> Then<C>(Pipe<RT, OUT, C, A> pipe) => Proxy.compose(this, pipe); /// <summary> /// Conversion operator from the _pure_ `Pipe` type, to the `Aff` monad transformer version of the `Pipe` /// </summary> /// <param name="p">Pure `Pipe`</param> /// <returns>Monad transformer version of the `Pipe` that supports `Aff`</returns> [Pure] public static implicit operator Pipe<RT, IN, OUT, A>(Pipe<IN, OUT, A> p) => p.Interpret<RT>(); /// <summary> /// Conversion operator from the `Pure` type, to the `Aff` monad transformer version of the `Pipe` /// </summary> /// <param name="p">`Pure` value</param> /// <returns>Monad transformer version of the `Pipe` that supports `Aff`</returns> [Pure] public static implicit operator Pipe<RT, IN, OUT, A>(Pure<A> p) => Pipe.Pure<RT, IN, OUT, A>(p.Value); /// <summary> /// Monadic bind operation, for chaining `Proxy` computations together. /// </summary> /// <param name="f">The bind function</param> /// <typeparam name="B">The mapped bound value type</typeparam> /// <returns>A new `Proxy` that represents the composition of this `Proxy` and the result of the bind operation</returns> [Pure] public Pipe<RT, IN, OUT, B> SelectMany<B>(Func<A, Release<B>> bind) => Value.Bind(a => bind(a).InterpretPipe<RT, IN, OUT>()).ToPipe(); /// <summary> /// Monadic bind operation, for chaining `Proxy` computations together. /// </summary> /// <param name="f">The bind function</param> /// <typeparam name="B">The mapped bound value type</typeparam> /// <returns>A new `Proxy` that represents the composition of this `Proxy` and the result of the bind operation</returns> [Pure] public Pipe<RT, IN, OUT, C> SelectMany<B, C>(Func<A, Release<B>> bind, Func<A, B, C> project) => SelectMany(a => bind(a).Select(b => project(a, b))); /// <summary> /// Monadic bind operation, for chaining `Proxy` computations together. /// </summary> /// <param name="f">The bind function</param> /// <typeparam name="B">The mapped bound value type</typeparam> /// <returns>A new `Proxy` that represents the composition of this `Proxy` and the result of the bind operation</returns> [Pure] public Pipe<RT, IN, OUT, B> SelectMany<B>(Func<A, Pipe<IN, OUT, B>> bind) => Value.Bind(a => bind(a).Interpret<RT>()).ToPipe(); /// <summary> /// Monadic bind operation, for chaining `Proxy` computations together. /// </summary> /// <param name="f">The bind function</param> /// <typeparam name="B">The mapped bound value type</typeparam> /// <returns>A new `Proxy` that represents the composition of this `Proxy` and the result of the bind operation</returns> [Pure] public Pipe<RT, IN, OUT, C> SelectMany<B, C>(Func<A, Pipe<IN, OUT, B>> bind, Func<A, B, C> project) => SelectMany(a => bind(a).Select(b => project(a, b))); /// <summary> /// Monadic bind operation, for chaining `Proxy` computations together. /// </summary> /// <param name="f">The bind function</param> /// <typeparam name="B">The mapped bound value type</typeparam> /// <returns>A new `Proxy` that represents the composition of this `Proxy` and the result of the bind operation</returns> [Pure] public Pipe<RT, IN, OUT, B> SelectMany<B>(Func<A, Pipe<RT, IN, OUT, B>> f) => Value.Bind(f).ToPipe(); /// <summary> /// Monadic bind operation, for chaining `Proxy` computations together. /// </summary> /// <param name="f">The bind function</param> /// <typeparam name="B">The mapped bound value type</typeparam> /// <returns>A new `Proxy` that represents the composition of this `Proxy` and the result of the bind operation</returns> [Pure] public Pipe<RT, IN, OUT, C> SelectMany<B, C>(Func<A, Pipe<RT, IN, OUT, B>> f, Func<A, B, C> project) => Value.Bind(a => f(a).Map(b => project(a, b))).ToPipe(); } }
using System; using System.Collections.Generic; using YesSql.Utils; namespace YesSql.Sql { public class SqlBuilder : ISqlBuilder { protected ISqlDialect _dialect; protected string _tablePrefix; protected string _clause; protected string _table; protected List<string> _select; protected List<string> _from; protected List<string> _join; protected List<List<string>> _or; protected List<string> _where; protected List<string> _group; protected List<string> _having; protected List<string> _order; protected List<string> _trail; protected bool _distinct; protected string _skip; protected string _count; protected List<string> SelectSegments => _select ??= new List<string>(); protected List<string> FromSegments => _from ??= new List<string>(); protected List<string> JoinSegments => _join ??= new List<string>(); protected List<List<string>> OrSegments => _or ??= new List<List<string>>(); protected List<string> WhereSegments => _where ??= new List<string>(); protected List<string> GroupSegments => _group ??= new List<string>(); protected List<string> HavingSegments => _having ??= new List<string>(); protected List<string> OrderSegments => _order ??= new List<string>(); protected List<string> TrailSegments => _trail ??= new List<string>(); public Dictionary<string, object> Parameters { get; protected set; } = new Dictionary<string, object>(); public SqlBuilder(string tablePrefix, ISqlDialect dialect) { _tablePrefix = tablePrefix; _dialect = dialect; } public string Clause { get { return _clause; } } public void Table(string table, string alias = null) { FromSegments.Clear(); FromSegments.Add(_dialect.QuoteForTableName(_tablePrefix + table)); if (!String.IsNullOrEmpty(alias)) { FromSegments.Add(" AS "); FromSegments.Add(_dialect.QuoteForTableName(alias)); } } public void From(string from) { FromSegments.Add(from); } public bool HasPaging => _skip != null || _count != null; public void Skip(string skip) { _skip = skip; } public void Take(string take) { _count = take; } public virtual void InnerJoin(string table, string onTable, string onColumn, string toTable, string toColumn, string alias = null, string toAlias = null) { // Don't prefix if alias is used if (alias != onTable) { onTable = _tablePrefix + onTable; } if (toTable != toAlias) { toTable = _tablePrefix + toTable; } if (!String.IsNullOrEmpty(toAlias)) { toTable = toAlias; } JoinSegments.Add(" INNER JOIN "); JoinSegments.Add(_dialect.QuoteForTableName(_tablePrefix + table)); if (!String.IsNullOrEmpty(alias)) { JoinSegments.AddRange(new[] { " AS ", _dialect.QuoteForTableName(alias) }); } JoinSegments.AddRange(new[] { " ON ", _dialect.QuoteForTableName(onTable), ".", _dialect.QuoteForColumnName(onColumn), " = ", _dialect.QuoteForTableName(toTable), ".", _dialect.QuoteForColumnName(toColumn) } ); } public void Select() { _clause = "SELECT"; } public void Selector(string selector) { SelectSegments.Clear(); SelectSegments.Add(selector); } public void Selector(string table, string column) { Selector(FormatColumn(table, column)); } public void AddSelector(string select) { SelectSegments.Add(select); } public void InsertSelector(string select) { SelectSegments.Insert(0, select); } public string GetSelector() { if (SelectSegments.Count == 1) { return SelectSegments[0]; } else { return string.Join("", SelectSegments); } } public void Distinct() { _distinct = true; } public virtual string FormatColumn(string table, string column, bool isAlias = false) { if (column != "*") { column = _dialect.QuoteForColumnName(column); } if (!isAlias) { table = _tablePrefix + table; } return _dialect.QuoteForTableName(table) + "." + column; } public virtual void AndAlso(string where) { if (String.IsNullOrWhiteSpace(where)) { return; } if (WhereSegments.Count > 0) { WhereSegments.Add(" AND "); } WhereSegments.Add(where); } public virtual void WhereOr(string where) { if (String.IsNullOrWhiteSpace(where)) { return; } if (WhereSegments.Count > 0) { WhereSegments.Add(" OR "); } WhereSegments.Add(where); } public virtual void WhereAnd(string where) { if (String.IsNullOrWhiteSpace(where)) { return; } if (WhereSegments.Count > 0) { WhereSegments.Add(" AND "); } WhereSegments.Add(where); } public bool HasJoin => _join != null && _join.Count > 0; public bool HasOrder => _order != null && _order.Count > 0; public void ClearOrder() { _order = null; } public virtual void OrderBy(string orderBy) { OrderSegments.Clear(); OrderSegments.Add(orderBy); } public virtual void OrderByDescending(string orderBy) { OrderSegments.Clear(); OrderSegments.Add(orderBy); OrderSegments.Add(" DESC"); } public virtual void OrderByRandom() { OrderSegments.Clear(); OrderSegments.Add(_dialect.RandomOrderByClause); } public virtual void ThenOrderBy(string orderBy) { OrderSegments.Add(", "); OrderSegments.Add(orderBy); } public virtual void ThenOrderByDescending(string orderBy) { OrderSegments.Add(", "); OrderSegments.Add(orderBy); OrderSegments.Add(" DESC"); } public virtual void ThenOrderByRandom() { OrderSegments.Add(", "); OrderSegments.Add(_dialect.RandomOrderByClause); } public virtual void GroupBy(string orderBy) { GroupSegments.Add(orderBy); } public virtual void Having(string orderBy) { HavingSegments.Add(orderBy); } public virtual void Trail(string segment) { TrailSegments.Add(segment); } public virtual void ClearTrail() { TrailSegments.Clear(); } public virtual string ToSqlString() { if (!String.Equals(_clause, "SELECT", StringComparison.OrdinalIgnoreCase)) { return ""; } if (_skip != null || _count != null) { _dialect.Page(this, _skip, _count); } var sb = new RentedStringBuilder(Store.LargeBufferSize); sb.Append("SELECT "); if (_distinct) { sb.Append("DISTINCT "); if (_order != null) { _select = _dialect.GetDistinctOrderBySelectString(_select, _order); } } foreach (var s in _select) { sb.Append(s); } if (_from != null) { sb.Append(" FROM "); foreach (var s in _from) { sb.Append(s); } } if (_join != null) { foreach (var s in _join) { sb.Append(s); } } if (_where != null) { sb.Append(" WHERE "); foreach (var s in _where) { sb.Append(s); } } if (_group != null) { sb.Append(" GROUP BY "); foreach (var s in _group) { sb.Append(s); } } if (_having != null) { sb.Append(" HAVING "); foreach (var s in _having) { sb.Append(s); } } if (_order != null) { sb.Append(" ORDER BY "); foreach (var s in _order) { sb.Append(s); } } if (_trail != null) { foreach (var s in _trail) { sb.Append(s); } } var result = sb.ToString(); sb.Dispose(); return result; } public ISqlBuilder Clone() { var clone = new SqlBuilder(_tablePrefix, _dialect); clone._clause = _clause; clone._table = _table; clone._select = _select == null ? null : new List<string>(_select); clone._from = _from == null ? null : new List<string>(_from); clone._join = _join == null ? null : new List<string>(_join); clone._where = _where == null ? null : new List<string>(_where); clone._group = _group == null ? null : new List<string>(_group); clone._having = _having == null ? null : new List<string>(_having); clone._order = _order == null ? null : new List<string>(_order); clone._trail = _trail == null ? null : new List<string>(_trail); clone._skip = _skip; clone._count = _count; clone.Parameters = new Dictionary<string, object>(Parameters); return clone; } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using Hyak.Common; using Microsoft.Azure; using Microsoft.Azure.Management.HDInsight; using Microsoft.Azure.Management.HDInsight.Models; using Newtonsoft.Json.Linq; namespace Microsoft.Azure.Management.HDInsight { /// <summary> /// The HDInsight Management Client. /// </summary> public partial class HDInsightManagementClient : ServiceClient<HDInsightManagementClient>, IHDInsightManagementClient { private string _apiVersion; /// <summary> /// Gets the API version. /// </summary> public string ApiVersion { get { return this._apiVersion; } } private Uri _baseUri; /// <summary> /// Gets the URI used as the base for all cloud service requests. /// </summary> public Uri BaseUri { get { return this._baseUri; } } private SubscriptionCloudCredentials _credentials; /// <summary> /// Gets subscription credentials which uniquely identify Microsoft /// Azure subscription. The subscription ID forms part of the URI for /// every service call. /// </summary> public SubscriptionCloudCredentials Credentials { get { return this._credentials; } } private int _longRunningOperationInitialTimeout; /// <summary> /// Gets or sets the initial timeout for Long Running Operations. /// </summary> public int LongRunningOperationInitialTimeout { get { return this._longRunningOperationInitialTimeout; } set { this._longRunningOperationInitialTimeout = value; } } private int _longRunningOperationRetryTimeout; /// <summary> /// Gets or sets the retry timeout for Long Running Operations. /// </summary> public int LongRunningOperationRetryTimeout { get { return this._longRunningOperationRetryTimeout; } set { this._longRunningOperationRetryTimeout = value; } } private IClusterOperations _clusters; /// <summary> /// Contains all the cluster operations. /// </summary> public virtual IClusterOperations Clusters { get { return this._clusters; } } /// <summary> /// Initializes a new instance of the HDInsightManagementClient class. /// </summary> public HDInsightManagementClient() : base() { this._clusters = new ClusterOperations(this); this._apiVersion = "2015-03-01-preview"; this._longRunningOperationInitialTimeout = -1; this._longRunningOperationRetryTimeout = -1; this.HttpClient.Timeout = TimeSpan.FromSeconds(300); } /// <summary> /// Initializes a new instance of the HDInsightManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Gets subscription credentials which uniquely identify /// Microsoft Azure subscription. The subscription ID forms part of /// the URI for every service call. /// </param> /// <param name='baseUri'> /// Optional. Gets the URI used as the base for all cloud service /// requests. /// </param> public HDInsightManagementClient(SubscriptionCloudCredentials credentials, Uri baseUri) : this() { if (credentials == null) { throw new ArgumentNullException("credentials"); } if (baseUri == null) { throw new ArgumentNullException("baseUri"); } this._credentials = credentials; this._baseUri = baseUri; this.Credentials.InitializeServiceClient(this); } /// <summary> /// Initializes a new instance of the HDInsightManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Gets subscription credentials which uniquely identify /// Microsoft Azure subscription. The subscription ID forms part of /// the URI for every service call. /// </param> public HDInsightManagementClient(SubscriptionCloudCredentials credentials) : this() { if (credentials == null) { throw new ArgumentNullException("credentials"); } this._credentials = credentials; this._baseUri = new Uri("https://management.azure.com"); this.Credentials.InitializeServiceClient(this); } /// <summary> /// Initializes a new instance of the HDInsightManagementClient class. /// </summary> /// <param name='httpClient'> /// The Http client /// </param> public HDInsightManagementClient(HttpClient httpClient) : base(httpClient) { this._clusters = new ClusterOperations(this); this._apiVersion = "2015-03-01-preview"; this._longRunningOperationInitialTimeout = -1; this._longRunningOperationRetryTimeout = -1; this.HttpClient.Timeout = TimeSpan.FromSeconds(300); } /// <summary> /// Initializes a new instance of the HDInsightManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Gets subscription credentials which uniquely identify /// Microsoft Azure subscription. The subscription ID forms part of /// the URI for every service call. /// </param> /// <param name='baseUri'> /// Optional. Gets the URI used as the base for all cloud service /// requests. /// </param> /// <param name='httpClient'> /// The Http client /// </param> public HDInsightManagementClient(SubscriptionCloudCredentials credentials, Uri baseUri, HttpClient httpClient) : this(httpClient) { if (credentials == null) { throw new ArgumentNullException("credentials"); } if (baseUri == null) { throw new ArgumentNullException("baseUri"); } this._credentials = credentials; this._baseUri = baseUri; this.Credentials.InitializeServiceClient(this); } /// <summary> /// Initializes a new instance of the HDInsightManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Gets subscription credentials which uniquely identify /// Microsoft Azure subscription. The subscription ID forms part of /// the URI for every service call. /// </param> /// <param name='httpClient'> /// The Http client /// </param> public HDInsightManagementClient(SubscriptionCloudCredentials credentials, HttpClient httpClient) : this(httpClient) { if (credentials == null) { throw new ArgumentNullException("credentials"); } this._credentials = credentials; this._baseUri = new Uri("https://management.azure.com"); this.Credentials.InitializeServiceClient(this); } /// <summary> /// Clones properties from current instance to another /// HDInsightManagementClient instance /// </summary> /// <param name='client'> /// Instance of HDInsightManagementClient to clone to /// </param> protected override void Clone(ServiceClient<HDInsightManagementClient> client) { base.Clone(client); if (client is HDInsightManagementClient) { HDInsightManagementClient clonedClient = ((HDInsightManagementClient)client); clonedClient._credentials = this._credentials; clonedClient._baseUri = this._baseUri; clonedClient._apiVersion = this._apiVersion; clonedClient._longRunningOperationInitialTimeout = this._longRunningOperationInitialTimeout; clonedClient._longRunningOperationRetryTimeout = this._longRunningOperationRetryTimeout; clonedClient.Credentials.InitializeServiceClient(clonedClient); } } /// <summary> /// The Get Operation Status operation returns the status of the /// specified operation. After calling an asynchronous operation, you /// can call Get Operation Status to determine whether the operation /// has succeeded, failed, or is still in progress. /// </summary> /// <param name='operationStatusLink'> /// Required. Location value returned by the Begin operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The cluster long running operation response. /// </returns> public async Task<HDInsightLongRunningOperationResponse> GetLongRunningOperationStatusAsync(string operationStatusLink, CancellationToken cancellationToken) { // Validate if (operationStatusLink == null) { throw new ArgumentNullException("operationStatusLink"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("operationStatusLink", operationStatusLink); TracingAdapter.Enter(invocationId, this, "GetLongRunningOperationStatusAsync", tracingParameters); } // Construct URL string url = ""; url = url + operationStatusLink; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("User-Agent", "ARM SDK v1.5.6-preview"); httpRequest.Headers.Add("x-ms-version", "2015-03-01-preview"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Accepted) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result HDInsightLongRunningOperationResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK || statusCode == HttpStatusCode.Accepted) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new HDInsightLongRunningOperationResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JToken errorValue = responseDoc["error"]; if (errorValue != null && errorValue.Type != JTokenType.Null) { ErrorInfo errorInstance = new ErrorInfo(); result.Error = errorInstance; JToken codeValue = errorValue["code"]; if (codeValue != null && codeValue.Type != JTokenType.Null) { string codeInstance = ((string)codeValue); errorInstance.Code = codeInstance; } JToken messageValue = errorValue["message"]; if (messageValue != null && messageValue.Type != JTokenType.Null) { string messageInstance = ((string)messageValue); errorInstance.Message = messageInstance; } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("RetryAfter")) { result.RetryAfter = int.Parse(httpResponse.Headers.GetValues("RetryAfter").FirstOrDefault(), CultureInfo.InvariantCulture); } if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (statusCode == HttpStatusCode.Accepted) { result.Status = OperationStatus.InProgress; } if (statusCode == HttpStatusCode.OK) { result.Status = OperationStatus.Succeeded; } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } } }
namespace Bynnies { using System; using System.Text; using Wintellect.PowerCollections; internal class Event : IComparable { private DateTime date; private string title; private string location; public Event(DateTime date, string title, string location) { this.date = date; this.title = title; this.location = location; } public int CompareTo(object obj) { Event other = obj as Event; int byDate = this.date.CompareTo(other.date); int byTitle = this.title.CompareTo(other.title); int byLocation = this.location.CompareTo(other.location); if (byDate == 0) { if (byTitle == 0) { return byLocation; } else { return byTitle; } } else { return byDate; } } public override string ToString() { StringBuilder toString = new StringBuilder(); toString.Append(this.date.ToString("yyyy-MM-ddTHH:mm:ss")); toString.Append(" | " + this.title); if (this.location != null && this.location != string.Empty) { toString.Append(" | " + this.location); } return toString.ToString(); } } internal class Program { private static StringBuilder output = new StringBuilder(); private static EventHolder events = new EventHolder(); public static void Main(string[] args) { while (ExecuteNextCommand()) { } Console.WriteLine(output); } private static bool ExecuteNextCommand() { string command = Console.ReadLine(); if (command[0] == 'A') { AddEvent(command); return true; } if (command[0] == 'D') { DeleteEvents(command); return true; } if (command[0] == 'L') { ListEvents(command); return true; } if (command[0] == 'E') { return false; } return false; } private static void ListEvents(string command) { int pipeIndex = command.IndexOf('|'); DateTime date = GetDate(command, "ListEvents"); string countString = command.Substring(pipeIndex + 1); int count = int.Parse(countString); events.ListEvents(date, count); } private static void DeleteEvents(string command) { string title = command.Substring("DeleteEvents".Length + 1); events.DeleteEvents(title); } private static void AddEvent(string command) { DateTime date; string title; string location; GetParameters(command, "AddEvent", out date, out title, out location); events.AddEvent(date, title, location); } private static void GetParameters( string commandForExecution, string commandType, out DateTime dateAndTime, out string eventTitle, out string eventLocation) { dateAndTime = GetDate(commandForExecution, commandType); int firstPipeIndex = commandForExecution.IndexOf('|'); int lastPipeIndex = commandForExecution.LastIndexOf('|'); if (firstPipeIndex == lastPipeIndex) { eventTitle = commandForExecution.Substring(firstPipeIndex + 1).Trim(); eventLocation = string.Empty; } else { eventTitle = commandForExecution .Substring(firstPipeIndex + 1, lastPipeIndex - firstPipeIndex - 1) .Trim(); eventLocation = commandForExecution.Substring(lastPipeIndex + 1) .Trim(); } } private static DateTime GetDate(string command, string commandType) { DateTime date = DateTime.Parse(command.Substring(commandType.Length + 1, 20)); return date; } internal static class Messages { public static void EventAdded() { output.Append("Event added\n"); } public static void EventDeleted(int x) { if (x == 0) { NoEventsFound(); } else { output.AppendFormat("{0} events deleted\n", x); } } public static void NoEventsFound() { output.Append("No events found\n"); } public static void PrintEvent(Event eventToPrint) { if (eventToPrint != null) { output.Append(eventToPrint + "\n"); } } } internal class EventHolder { private MultiDictionary<string, Event> byTitle = new MultiDictionary<string, Event>(true); private OrderedBag<Event> byDate = new OrderedBag<Event>(); public void AddEvent(DateTime date, string title, string location) { Event newEvent = new Event(date, title, location); this.byTitle.Add(title.ToLower(), newEvent); this.byDate.Add(newEvent); Messages.EventAdded(); } public void DeleteEvents(string titleToDelete) { string title = titleToDelete.ToLower(); int removed = 0; foreach (var eventToRemove in this.byTitle[title]) { removed++; this.byDate.Remove(eventToRemove); } this.byTitle.Remove(title); Messages.EventDeleted(removed); } public void ListEvents(DateTime date, int count) { OrderedBag<Event>.View eventsToShow = this.byDate.RangeFrom(new Event(date, string.Empty, string.Empty), true); int showed = 0; foreach (var eventToShow in eventsToShow) { if (showed == count) { break; } Messages.PrintEvent(eventToShow); showed++; } if (showed == 0) { Messages.NoEventsFound(); } } } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Threading.Tasks; using Microsoft.Azure.Cosmos.Table; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging.Abstractions; using Microsoft.Extensions.Options; using Newtonsoft.Json; using Orleans; using Orleans.Configuration; using Orleans.Internal; using Orleans.Providers; using Orleans.Runtime; using Orleans.Storage; using Orleans.Streams; using Samples.StorageProviders; using TestExtensions; using UnitTests.Persistence; using UnitTests.StorageTests; using Xunit; using Xunit.Abstractions; namespace Tester.AzureUtils.Persistence { [Collection(TestEnvironmentFixture.DefaultCollection)] [TestCategory("Persistence")] public class PersistenceProviderTests_Local { private readonly IProviderRuntime providerRuntime; private readonly Dictionary<string, string> providerCfgProps = new Dictionary<string, string>(); private readonly ITestOutputHelper output; private readonly TestEnvironmentFixture fixture; public PersistenceProviderTests_Local(ITestOutputHelper output, TestEnvironmentFixture fixture) { this.output = output; this.fixture = fixture; this.providerRuntime = new ClientProviderRuntime( fixture.InternalGrainFactory, fixture.Services, fixture.Services.GetRequiredService<ClientGrainContext>()); this.providerCfgProps.Clear(); } [Fact, TestCategory("Functional")] public async Task PersistenceProvider_Mock_WriteRead() { const string testName = nameof(PersistenceProvider_Mock_WriteRead); var store = ActivatorUtilities.CreateInstance<MockStorageProvider>(fixture.Services, testName); await Test_PersistenceProvider_WriteRead(testName, store); } [Fact, TestCategory("Functional")] public async Task PersistenceProvider_FileStore_WriteRead() { const string testName = nameof(PersistenceProvider_FileStore_WriteRead); var store = new OrleansFileStorage("Data"); await Test_PersistenceProvider_WriteRead(testName, store); } [SkippableFact, TestCategory("Functional"), TestCategory("Azure")] public async Task PersistenceProvider_Azure_Read() { TestUtils.CheckForAzureStorage(); const string testName = nameof(PersistenceProvider_Azure_Read); AzureTableGrainStorage store = await InitAzureTableGrainStorage(); await Test_PersistenceProvider_Read(testName, store); } [SkippableTheory, TestCategory("Functional"), TestCategory("Azure")] [InlineData(null, false)] [InlineData(null, true)] [InlineData(15 * 64 * 1024 - 256, false)] [InlineData(15 * 32 * 1024 - 256, true)] public async Task PersistenceProvider_Azure_WriteRead(int? stringLength, bool useJson) { var testName = string.Format("{0}({1} = {2}, {3} = {4})", nameof(PersistenceProvider_Azure_WriteRead), nameof(stringLength), stringLength == null ? "default" : stringLength.ToString(), nameof(useJson), useJson); var grainState = TestStoreGrainState.NewRandomState(stringLength); EnsureEnvironmentSupportsState(grainState); var store = await InitAzureTableGrainStorage(useJson); await Test_PersistenceProvider_WriteRead(testName, store, grainState); } [SkippableTheory, TestCategory("Functional"), TestCategory("Azure")] [InlineData(null, false)] [InlineData(null, true)] [InlineData(15 * 64 * 1024 - 256, false)] [InlineData(15 * 32 * 1024 - 256, true)] public async Task PersistenceProvider_Azure_WriteClearRead(int? stringLength, bool useJson) { var testName = string.Format("{0}({1} = {2}, {3} = {4})", nameof(PersistenceProvider_Azure_WriteClearRead), nameof(stringLength), stringLength == null ? "default" : stringLength.ToString(), nameof(useJson), useJson); var grainState = TestStoreGrainState.NewRandomState(stringLength); EnsureEnvironmentSupportsState(grainState); var store = await InitAzureTableGrainStorage(useJson); await Test_PersistenceProvider_WriteClearRead(testName, store, grainState); } [SkippableTheory, TestCategory("Functional"), TestCategory("Azure")] [InlineData(null, true, false)] [InlineData(null, false, true)] [InlineData(15 * 32 * 1024 - 256, true, false)] [InlineData(15 * 32 * 1024 - 256, false, true)] public async Task PersistenceProvider_Azure_ChangeReadFormat(int? stringLength, bool useJsonForWrite, bool useJsonForRead) { var testName = string.Format("{0}({1} = {2}, {3} = {4}, {5} = {6})", nameof(PersistenceProvider_Azure_ChangeReadFormat), nameof(stringLength), stringLength == null ? "default" : stringLength.ToString(), nameof(useJsonForWrite), useJsonForWrite, nameof(useJsonForRead), useJsonForRead); var grainState = TestStoreGrainState.NewRandomState(stringLength); EnsureEnvironmentSupportsState(grainState); var grainId = LegacyGrainId.NewId(); var store = await InitAzureTableGrainStorage(useJsonForWrite); grainState = await Test_PersistenceProvider_WriteRead(testName, store, grainState, grainId); store = await InitAzureTableGrainStorage(useJsonForRead); await Test_PersistenceProvider_Read(testName, store, grainState, grainId); } [SkippableTheory, TestCategory("Functional"), TestCategory("Azure")] [InlineData(null, true, false)] [InlineData(null, false, true)] [InlineData(15 * 32 * 1024 - 256, true, false)] [InlineData(15 * 32 * 1024 - 256, false, true)] public async Task PersistenceProvider_Azure_ChangeWriteFormat(int? stringLength, bool useJsonForFirstWrite, bool useJsonForSecondWrite) { var testName = string.Format("{0}({1}={2},{3}={4},{5}={6})", nameof(PersistenceProvider_Azure_ChangeWriteFormat), nameof(stringLength), stringLength == null ? "default" : stringLength.ToString(), "json1stW", useJsonForFirstWrite, "json2ndW", useJsonForSecondWrite); var grainState = TestStoreGrainState.NewRandomState(stringLength); EnsureEnvironmentSupportsState(grainState); var grainId = LegacyGrainId.NewId(); var store = await InitAzureTableGrainStorage(useJsonForFirstWrite); await Test_PersistenceProvider_WriteRead(testName, store, grainState, grainId); grainState = TestStoreGrainState.NewRandomState(stringLength); grainState.ETag = "*"; store = await InitAzureTableGrainStorage(useJsonForSecondWrite); await Test_PersistenceProvider_WriteRead(testName, store, grainState, grainId); } [SkippableTheory, TestCategory("Functional"), TestCategory("Azure")] [InlineData(null, false)] [InlineData(null, true)] [InlineData(15 * 64 * 1024 - 256, false)] [InlineData(15 * 32 * 1024 - 256, true)] public async Task AzureTableStorage_ConvertToFromStorageFormat(int? stringLength, bool useJson) { var testName = string.Format("{0}({1} = {2}, {3} = {4})", nameof(AzureTableStorage_ConvertToFromStorageFormat), nameof(stringLength), stringLength == null ? "default" : stringLength.ToString(), nameof(useJson), useJson); var state = TestStoreGrainState.NewRandomState(stringLength); EnsureEnvironmentSupportsState(state); var storage = await InitAzureTableGrainStorage(useJson); var initialState = state.State; var entity = new DynamicTableEntity(); storage.ConvertToStorageFormat(initialState, entity); var convertedState = (TestStoreGrainState)storage.ConvertFromStorageFormat(entity, typeof(TestStoreGrainState)); Assert.NotNull(convertedState); Assert.Equal(initialState.A, convertedState.A); Assert.Equal(initialState.B, convertedState.B); Assert.Equal(initialState.C, convertedState.C); } [SkippableFact, TestCategory("Functional"), TestCategory("Azure")] public async Task AzureTableStorage_ConvertJsonToFromStorageFormatWithCustomJsonProperties() { TestUtils.CheckForAzureStorage(); var state = TestStoreGrainStateWithCustomJsonProperties.NewRandomState(null); var storage = await InitAzureTableGrainStorage(useJson: true, typeNameHandling: TypeNameHandling.None); var initialState = state.State; var entity = new DynamicTableEntity(); storage.ConvertToStorageFormat(initialState, entity); var convertedState = (TestStoreGrainStateWithCustomJsonProperties)storage.ConvertFromStorageFormat(entity, typeof(TestStoreGrainStateWithCustomJsonProperties)); Assert.NotNull(convertedState); Assert.Equal(initialState.String, convertedState.String); } [Fact, TestCategory("Functional"), TestCategory("MemoryStore")] public async Task PersistenceProvider_Memory_FixedLatency_WriteRead() { const string testName = nameof(PersistenceProvider_Memory_FixedLatency_WriteRead); TimeSpan expectedLatency = TimeSpan.FromMilliseconds(200); MemoryGrainStorageWithLatency store = new MemoryGrainStorageWithLatency(testName, new MemoryStorageWithLatencyOptions() { Latency = expectedLatency, MockCallsOnly = true }, NullLoggerFactory.Instance, this.providerRuntime.ServiceProvider.GetService<IGrainFactory>()); GrainReference reference = (GrainReference)this.fixture.InternalGrainFactory.GetGrain(LegacyGrainId.NewId()); var state = TestStoreGrainState.NewRandomState(); Stopwatch sw = new Stopwatch(); sw.Start(); await store.WriteStateAsync(testName, reference, state); TimeSpan writeTime = sw.Elapsed; this.output.WriteLine("{0} - Write time = {1}", store.GetType().FullName, writeTime); Assert.True(writeTime >= expectedLatency, $"Write: Expected minimum latency = {expectedLatency} Actual = {writeTime}"); sw.Restart(); var storedState = new GrainState<TestStoreGrainState>(); await store.ReadStateAsync(testName, reference, storedState); TimeSpan readTime = sw.Elapsed; this.output.WriteLine("{0} - Read time = {1}", store.GetType().FullName, readTime); Assert.True(readTime >= expectedLatency, $"Read: Expected minimum latency = {expectedLatency} Actual = {readTime}"); } [Fact, TestCategory("Functional")] public void LoadClassByName() { string className = typeof(MockStorageProvider).FullName; Type classType = new CachedTypeResolver().ResolveType(className); Assert.NotNull(classType); // Type Assert.True(typeof(IGrainStorage).IsAssignableFrom(classType), $"Is an IStorageProvider : {classType.FullName}"); } private async Task<AzureTableGrainStorage> InitAzureTableGrainStorage(AzureTableStorageOptions options) { AzureTableGrainStorage store = ActivatorUtilities.CreateInstance<AzureTableGrainStorage>(this.providerRuntime.ServiceProvider, options, "TestStorage"); ISiloLifecycleSubject lifecycle = ActivatorUtilities.CreateInstance<SiloLifecycleSubject>(this.providerRuntime.ServiceProvider); store.Participate(lifecycle); await lifecycle.OnStart(); return store; } private Task<AzureTableGrainStorage> InitAzureTableGrainStorage(bool useJson = false, TypeNameHandling? typeNameHandling = null) { var options = new AzureTableStorageOptions { UseJson = useJson, TypeNameHandling = typeNameHandling }; options.ConfigureTestDefaults(); return InitAzureTableGrainStorage(options); } private async Task Test_PersistenceProvider_Read(string grainTypeName, IGrainStorage store, GrainState<TestStoreGrainState> grainState = null, GrainId grainId = default) { var reference = (GrainReference)this.fixture.InternalGrainFactory.GetGrain(grainId.IsDefault ? (GrainId)LegacyGrainId.NewId() : grainId); if (grainState == null) { grainState = new GrainState<TestStoreGrainState>(new TestStoreGrainState()); } var storedGrainState = new GrainState<TestStoreGrainState>(new TestStoreGrainState()); Stopwatch sw = new Stopwatch(); sw.Start(); await store.ReadStateAsync(grainTypeName, reference, storedGrainState); TimeSpan readTime = sw.Elapsed; this.output.WriteLine("{0} - Read time = {1}", store.GetType().FullName, readTime); var storedState = storedGrainState.State; Assert.Equal(grainState.State.A, storedState.A); Assert.Equal(grainState.State.B, storedState.B); Assert.Equal(grainState.State.C, storedState.C); } private async Task<GrainState<TestStoreGrainState>> Test_PersistenceProvider_WriteRead(string grainTypeName, IGrainStorage store, GrainState<TestStoreGrainState> grainState = null, GrainId grainId = default) { GrainReference reference = (GrainReference)this.fixture.InternalGrainFactory.GetGrain(grainId.IsDefault ? (GrainId)LegacyGrainId.NewId() : grainId); if (grainState == null) { grainState = TestStoreGrainState.NewRandomState(); } Stopwatch sw = new Stopwatch(); sw.Start(); await store.WriteStateAsync(grainTypeName, reference, grainState); TimeSpan writeTime = sw.Elapsed; sw.Restart(); var storedGrainState = new GrainState<TestStoreGrainState> { State = new TestStoreGrainState() }; await store.ReadStateAsync(grainTypeName, reference, storedGrainState); TimeSpan readTime = sw.Elapsed; this.output.WriteLine("{0} - Write time = {1} Read time = {2}", store.GetType().FullName, writeTime, readTime); Assert.Equal(grainState.State.A, storedGrainState.State.A); Assert.Equal(grainState.State.B, storedGrainState.State.B); Assert.Equal(grainState.State.C, storedGrainState.State.C); return storedGrainState; } private async Task<GrainState<TestStoreGrainState>> Test_PersistenceProvider_WriteClearRead(string grainTypeName, IGrainStorage store, GrainState<TestStoreGrainState> grainState = null, GrainId grainId = default) { GrainReference reference = (GrainReference)this.fixture.InternalGrainFactory.GetGrain(grainId.IsDefault ? (GrainId)LegacyGrainId.NewId() : grainId); if (grainState == null) { grainState = TestStoreGrainState.NewRandomState(); } Stopwatch sw = new Stopwatch(); sw.Start(); await store.WriteStateAsync(grainTypeName, reference, grainState); TimeSpan writeTime = sw.Elapsed; sw.Restart(); await store.ClearStateAsync(grainTypeName, reference, grainState); var storedGrainState = new GrainState<TestStoreGrainState> { State = new TestStoreGrainState() }; await store.ReadStateAsync(grainTypeName, reference, storedGrainState); TimeSpan readTime = sw.Elapsed; this.output.WriteLine("{0} - Write time = {1} Read time = {2}", store.GetType().FullName, writeTime, readTime); Assert.NotNull(storedGrainState.State); Assert.Equal(default(string), storedGrainState.State.A); Assert.Equal(default(int), storedGrainState.State.B); Assert.Equal(default(long), storedGrainState.State.C); return storedGrainState; } private static void EnsureEnvironmentSupportsState(GrainState<TestStoreGrainState> grainState) { if (grainState.State.A.Length > 400 * 1024) { StorageEmulatorUtilities.EnsureEmulatorIsNotUsed(); } TestUtils.CheckForAzureStorage(); } public class TestStoreGrainStateWithCustomJsonProperties { [JsonProperty("s")] public string String { get; set; } internal static GrainState<TestStoreGrainStateWithCustomJsonProperties> NewRandomState(int? aPropertyLength = null) { return new GrainState<TestStoreGrainStateWithCustomJsonProperties> { State = new TestStoreGrainStateWithCustomJsonProperties { String = aPropertyLength == null ? ThreadSafeRandom.Next().ToString(CultureInfo.InvariantCulture) : GenerateRandomDigitString(aPropertyLength.Value) } }; } private static string GenerateRandomDigitString(int stringLength) { var characters = new char[stringLength]; for (var i = 0; i < stringLength; ++i) { characters[i] = (char)ThreadSafeRandom.Next('0', '9' + 1); } return new string(characters); } } } }
// -- FILE ------------------------------------------------------------------ // name : DateDiff.cs // project : Itenso Time Period // created : Jani Giannoudis - 2011.03.19 // language : C# 4.0 // environment: .NET 2.0 // copyright : (c) 2011-2012 by Itenso GmbH, Switzerland // -------------------------------------------------------------------------- using System; using System.Globalization; namespace Itenso.TimePeriod { // ------------------------------------------------------------------------ public sealed class DateDiff { // ---------------------------------------------------------------------- public DateDiff( DateTime date ) : this( date, SafeCurrentInfo.Calendar, SafeCurrentInfo.FirstDayOfWeek ) { } // DateDiff // ---------------------------------------------------------------------- public DateDiff( DateTime date, Calendar calendar, DayOfWeek firstDayOfWeek, YearMonth yearBaseMonth = TimeSpec.CalendarYearStartMonth ) : this( date, ClockProxy.Clock.Now, calendar, firstDayOfWeek, yearBaseMonth ) { } // DateDiff // ---------------------------------------------------------------------- public DateDiff( DateTime date1, DateTime date2 ) : this( date1, date2, SafeCurrentInfo.Calendar, SafeCurrentInfo.FirstDayOfWeek ) { } // DateDiff // ---------------------------------------------------------------------- public DateDiff( DateTime date1, DateTime date2, Calendar calendar, DayOfWeek firstDayOfWeek, YearMonth yearBaseMonth = TimeSpec.CalendarYearStartMonth ) { if ( calendar == null ) { throw new ArgumentNullException( "calendar" ); } this.calendar = calendar; this.yearBaseMonth = yearBaseMonth; this.firstDayOfWeek = firstDayOfWeek; this.date1 = date1; this.date2 = date2; difference = date2.Subtract( date1 ); } // DateDiff // ---------------------------------------------------------------------- public DateDiff( TimeSpan difference ) : this( ClockProxy.Clock.Now, difference, SafeCurrentInfo.Calendar, SafeCurrentInfo.FirstDayOfWeek ) { } // DateDiff // ---------------------------------------------------------------------- public DateDiff( TimeSpan difference, Calendar calendar, DayOfWeek firstDayOfWeek, YearMonth yearBaseMonth = TimeSpec.CalendarYearStartMonth ) : this( ClockProxy.Clock.Now, difference, calendar, firstDayOfWeek, yearBaseMonth ) { } // DateDiff // ---------------------------------------------------------------------- public DateDiff( DateTime date1, TimeSpan difference ) : this( date1, difference, SafeCurrentInfo.Calendar, SafeCurrentInfo.FirstDayOfWeek ) { } // DateDiff // ---------------------------------------------------------------------- public DateDiff( DateTime date1, TimeSpan difference, Calendar calendar, DayOfWeek firstDayOfWeek, YearMonth yearBaseMonth = TimeSpec.CalendarYearStartMonth ) { if ( calendar == null ) { throw new ArgumentNullException( "calendar" ); } this.calendar = calendar; this.yearBaseMonth = yearBaseMonth; this.firstDayOfWeek = firstDayOfWeek; this.date1 = date1; date2 = date1.Add( difference ); this.difference = difference; } // DateDiff public static DateTimeFormatInfo SafeCurrentInfo { get { return ( DateTimeFormatInfo.CurrentInfo ?? DateTimeFormatInfo.InvariantInfo ); } } // SafeCurrentInfo // ---------------------------------------------------------------------- public Calendar Calendar { get { return calendar; } } // Calendar // ---------------------------------------------------------------------- public YearMonth YearBaseMonth { get { return yearBaseMonth; } } // YearBaseMonth // ---------------------------------------------------------------------- public DayOfWeek FirstDayOfWeek { get { return firstDayOfWeek; } } // FirstDayOfWeek // ---------------------------------------------------------------------- public DateTime Date1 { get { return date1; } } // Date1 // ---------------------------------------------------------------------- public DateTime Date2 { get { return date2; } } // Date2 // ---------------------------------------------------------------------- public TimeSpan Difference { get { return difference; } } // Difference // ---------------------------------------------------------------------- public bool IsEmpty { get { return difference == TimeSpan.Zero; } } // IsEmpty // ---------------------------------------------------------------------- private int Year1 { get { return calendar.GetYear( Date1 ); } } // Year1 // ---------------------------------------------------------------------- private int Year2 { get { return calendar.GetYear( Date2 ); } } // Year2 // ---------------------------------------------------------------------- public int Years { get { if ( !years.HasValue ) { years = CalcYears(); } return years.Value; } } // Years // ---------------------------------------------------------------------- public int ElapsedYears { get { if ( !elapsedYears.HasValue ) { elapsedYears = Years; } return elapsedYears.Value; } } // ElapsedYears // ---------------------------------------------------------------------- public int Quarters { get { if ( !quarters.HasValue ) { quarters = CalcQuarters(); } return quarters.Value; } } // Quarters // ---------------------------------------------------------------------- private int Month1 { get { return calendar.GetMonth( Date1 ); } } // Month1 // ---------------------------------------------------------------------- private int Month2 { get { return calendar.GetMonth( Date2 ); } } // Month2 // ---------------------------------------------------------------------- public int Months { get { if ( !months.HasValue ) { months = CalcMonths(); } return months.Value; } } // Months // ---------------------------------------------------------------------- public int ElapsedMonths { get { if ( !elapsedMonths.HasValue ) { elapsedMonths = Months - ( ElapsedYears * TimeSpec.MonthsPerYear ); } return elapsedMonths.Value; } } // ElapsedMonths // ---------------------------------------------------------------------- public int Weeks { get { if ( !weeks.HasValue ) { weeks = CalcWeeks(); } return weeks.Value; } } // Weeks // ---------------------------------------------------------------------- public int Days { get { return (int)Math.Round( Round( difference.TotalDays ) ); } } // Days // ---------------------------------------------------------------------- public int Weekdays { get { return ( (int)Math.Round( Round( difference.TotalDays ) ) ) / TimeSpec.DaysPerWeek; } } // Weekdays // ---------------------------------------------------------------------- public int ElapsedDays { get { if ( !elapsedDays.HasValue ) { DateTime compareDate = date1.AddYears( ElapsedYears ).AddMonths( ElapsedMonths ); elapsedDays = (int)date2.Subtract( compareDate ).TotalDays; } return elapsedDays.Value; } } // ElapsedDays // ---------------------------------------------------------------------- public int Hours { get { return (int)Math.Round( Round( difference.TotalHours ) ); } } // Hours // ---------------------------------------------------------------------- public int ElapsedHours { get { if ( !elapsedHours.HasValue ) { DateTime compareDate = date1.AddYears( ElapsedYears ).AddMonths( ElapsedMonths ).AddDays( ElapsedDays ); elapsedHours = (int)date2.Subtract( compareDate ).TotalHours; } return elapsedHours.Value; } } // ElapsedHours // ---------------------------------------------------------------------- public int Minutes { get { return (int)Math.Round( Round( difference.TotalMinutes ) ); } } // Minutes // ---------------------------------------------------------------------- public int ElapsedMinutes { get { if ( !elapsedMinutes.HasValue ) { DateTime compareDate = date1.AddYears( ElapsedYears ).AddMonths( ElapsedMonths ).AddDays( ElapsedDays ).AddHours( ElapsedHours ); elapsedMinutes = (int)date2.Subtract( compareDate ).TotalMinutes; } return elapsedMinutes.Value; } } // ElapsedMinutes // ---------------------------------------------------------------------- public int Seconds { get { return (int)Math.Round( Round( difference.TotalSeconds ) ); } } // Seconds // ---------------------------------------------------------------------- public int ElapsedSeconds { get { if ( !elapsedSeconds.HasValue ) { DateTime compareDate = date1.AddYears( ElapsedYears ).AddMonths( ElapsedMonths ).AddDays( ElapsedDays ).AddHours( ElapsedHours ).AddMinutes( ElapsedMinutes ); elapsedSeconds = (int)date2.Subtract( compareDate ).TotalSeconds; } return elapsedSeconds.Value; } } // ElapsedSeconds // ---------------------------------------------------------------------- public string GetDescription( int precision = int.MaxValue, ITimeFormatter formatter = null ) { if ( precision < 1 ) { throw new ArgumentOutOfRangeException( "precision" ); } formatter = formatter ?? TimeFormatter.Instance; int[] elapsedItems = new int[ 6 ]; elapsedItems[ 0 ] = ElapsedYears; elapsedItems[ 1 ] = ElapsedMonths; elapsedItems[ 2 ] = ElapsedDays; elapsedItems[ 3 ] = ElapsedHours; elapsedItems[ 4 ] = ElapsedMinutes; elapsedItems[ 5 ] = ElapsedSeconds; if ( precision <= elapsedItems.Length - 1 ) { for ( int i = precision; i < elapsedItems.Length; i++ ) { elapsedItems[ i ] = 0; } } return formatter.GetDuration( elapsedItems[ 0 ], elapsedItems[ 1 ], elapsedItems[ 2 ], elapsedItems[ 3 ], elapsedItems[ 4 ], elapsedItems[ 5 ] ); } // GetDescription // ---------------------------------------------------------------------- public override string ToString() { return GetDescription(); } // ToString // ---------------------------------------------------------------------- public override bool Equals( object obj ) { if ( obj == this ) { return true; } if ( obj == null || GetType() != obj.GetType() ) { return false; } DateDiff comp = (DateDiff)obj; return calendar == comp.calendar && yearBaseMonth == comp.yearBaseMonth && firstDayOfWeek == comp.firstDayOfWeek && date1 == comp.date1 && date2 == comp.date2 && difference == comp.difference; } // Equals // ---------------------------------------------------------------------- public override int GetHashCode() { return HashTool.ComputeHashCode( GetType().GetHashCode(), calendar, yearBaseMonth, firstDayOfWeek, date1, date2, difference ); } // GetHashCode // ---------------------------------------------------------------------- private static double Round( double number ) { if ( number >= 0.0 ) { return Math.Floor( number ); } return -Math.Floor( -number ); } // Round // ---------------------------------------------------------------------- private int CalcYears() { if ( TimeCompare.IsSameMonth( date1, date2 ) ) { return 0; } int compareDay = date2.Day; int compareDaysPerMonth = calendar.GetDaysInMonth( Year1, Month2 ); if ( compareDay > compareDaysPerMonth ) { compareDay = compareDaysPerMonth; } DateTime compareDate = new DateTime( Year1, Month2, compareDay, date2.Hour, date2.Minute, date2.Second, date2.Millisecond ); if ( date2 > date1 ) { if ( compareDate < date1 ) { compareDate = compareDate.AddYears( 1 ); } } else { if ( compareDate > date1 ) { compareDate = compareDate.AddYears( -1 ); } } return Year2 - calendar.GetYear( compareDate ); } // CalcYears // ---------------------------------------------------------------------- private int CalcQuarters() { if ( TimeCompare.IsSameMonth( date1, date2 ) ) { return 0; } int year1 = TimeTool.GetYearOf( yearBaseMonth, Year1, Month1 ); YearQuarter quarter1 = TimeTool.GetQuarterOfMonth( yearBaseMonth, (YearMonth)Month1 ); int year2 = TimeTool.GetYearOf( yearBaseMonth, Year2, Month2 ); YearQuarter quarter2 = TimeTool.GetQuarterOfMonth( yearBaseMonth, (YearMonth)Month2 ); return ( ( year2 * TimeSpec.QuartersPerYear ) + quarter2 ) - ( ( year1 * TimeSpec.QuartersPerYear ) + quarter1 ); } // CalcQuarters // ---------------------------------------------------------------------- private int CalcMonths() { if ( TimeCompare.IsSameDay( date1, date2 ) ) { return 0; } int compareDay = date2.Day; int compareDaysPerMonth = calendar.GetDaysInMonth( Year1, Month1 ); if ( compareDay > compareDaysPerMonth ) { compareDay = compareDaysPerMonth; } DateTime compareDate = new DateTime( Year1, Month1, compareDay, date2.Hour, date2.Minute, date2.Second, date2.Millisecond ); if ( date2 > date1 ) { if ( compareDate < date1 ) { compareDate = compareDate.AddMonths( 1 ); } } else { if ( compareDate > date1 ) { compareDate = compareDate.AddMonths( -1 ); } } return ( ( Year2 * TimeSpec.MonthsPerYear ) + Month2 ) - ( ( calendar.GetYear( compareDate ) * TimeSpec.MonthsPerYear ) + calendar.GetMonth( compareDate ) ); } // CalcMonths // ---------------------------------------------------------------------- private int CalcWeeks() { if ( TimeCompare.IsSameDay( date1, date2 ) ) { return 0; } DateTime week1 = TimeTool.GetStartOfWeek( date1, firstDayOfWeek ); DateTime week2 = TimeTool.GetStartOfWeek( date2, firstDayOfWeek ); if ( week1.Equals( week2 ) ) { return 0; } return (int)( week2.Subtract( week1 ).TotalDays / TimeSpec.DaysPerWeek ); } // CalcWeeks // ---------------------------------------------------------------------- // members private readonly Calendar calendar; private readonly YearMonth yearBaseMonth; private readonly DayOfWeek firstDayOfWeek; private readonly DateTime date1; private readonly DateTime date2; private readonly TimeSpan difference; // cached values private int? years; private int? quarters; private int? months; private int? weeks; private int? elapsedYears; private int? elapsedMonths; private int? elapsedDays; private int? elapsedHours; private int? elapsedMinutes; private int? elapsedSeconds; } // class DateDiff } // namespace Itenso.TimePeriod // -- EOF -------------------------------------------------------------------
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Reflection; using Xunit; namespace System.Linq.Expressions.Tests { public static class BinaryNullablePowerTests { #region Test methods [Theory, ClassData(typeof(CompilationTypes))] public static void CheckNullableBytePowerTest(bool useInterpreter) { byte?[] array = new byte?[] { null, 0, 1, byte.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableBytePower(array[i], array[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckNullableSBytePowerTest(bool useInterpreter) { sbyte?[] array = new sbyte?[] { null, 0, 1, -1, sbyte.MinValue, sbyte.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableSBytePower(array[i], array[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckNullableUShortPowerTest(bool useInterpreter) { ushort?[] array = new ushort?[] { null, 0, 1, ushort.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableUShortPower(array[i], array[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckNullableShortPowerTest(bool useInterpreter) { short?[] array = new short?[] { null, 0, 1, -1, short.MinValue, short.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableShortPower(array[i], array[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckNullableUIntPowerTest(bool useInterpreter) { uint?[] array = new uint?[] { null, 0, 1, uint.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableUIntPower(array[i], array[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckNullableIntPowerTest(bool useInterpreter) { int?[] array = new int?[] { null, 0, 1, -1, int.MinValue, int.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableIntPower(array[i], array[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckNullableULongPowerTest(bool useInterpreter) { ulong?[] array = new ulong?[] { null, 0, 1, ulong.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableULongPower(array[i], array[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckNullableLongPowerTest(bool useInterpreter) { long?[] array = new long?[] { null, 0, 1, -1, long.MinValue, long.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableLongPower(array[i], array[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckNullableFloatPowerTest(bool useInterpreter) { float?[] array = new float?[] { null, 0, 1, -1, float.MinValue, float.MaxValue, float.Epsilon, float.NegativeInfinity, float.PositiveInfinity, float.NaN }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableFloatPower(array[i], array[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckNullableDoublePowerTest(bool useInterpreter) { double?[] array = new double?[] { null, 0, 1, -1, double.MinValue, double.MaxValue, double.Epsilon, double.NegativeInfinity, double.PositiveInfinity, double.NaN }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableDoublePower(array[i], array[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckNullableDecimalPowerTest(bool useInterpreter) { decimal?[] array = new decimal?[] { null, decimal.Zero, decimal.One, decimal.MinusOne, decimal.MinValue, decimal.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableDecimalPower(array[i], array[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckNullableCharPowerTest(bool useInterpreter) { char?[] array = new char?[] { null, '\0', '\b', 'A', '\uffff' }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableCharPower(array[i], array[j], useInterpreter); } } } #endregion #region Test verifiers private static void VerifyNullableBytePower(byte? a, byte? b, bool useInterpreter) { Expression<Func<byte?>> e = Expression.Lambda<Func<byte?>>( Expression.Power( Expression.Constant(a, typeof(byte?)), Expression.Constant(b, typeof(byte?)), typeof(BinaryNullablePowerTests).GetTypeInfo().GetDeclaredMethod("PowerByte") )); Func<byte?> f = e.Compile(useInterpreter); if (a.HasValue & b.HasValue) Assert.Equal(PowerByte(a.GetValueOrDefault(), b.GetValueOrDefault()), f()); else Assert.Null(f()); } private static void VerifyNullableSBytePower(sbyte? a, sbyte? b, bool useInterpreter) { Expression<Func<sbyte?>> e = Expression.Lambda<Func<sbyte?>>( Expression.Power( Expression.Constant(a, typeof(sbyte?)), Expression.Constant(b, typeof(sbyte?)), typeof(BinaryNullablePowerTests).GetTypeInfo().GetDeclaredMethod("PowerSByte") )); Func<sbyte?> f = e.Compile(useInterpreter); if (a.HasValue & b.HasValue) Assert.Equal(PowerSByte(a.GetValueOrDefault(), b.GetValueOrDefault()), f()); else Assert.Null(f()); } private static void VerifyNullableUShortPower(ushort? a, ushort? b, bool useInterpreter) { Expression<Func<ushort?>> e = Expression.Lambda<Func<ushort?>>( Expression.Power( Expression.Constant(a, typeof(ushort?)), Expression.Constant(b, typeof(ushort?)), typeof(BinaryNullablePowerTests).GetTypeInfo().GetDeclaredMethod("PowerUShort") )); Func<ushort?> f = e.Compile(useInterpreter); if (a.HasValue & b.HasValue) Assert.Equal(PowerUShort(a.GetValueOrDefault(), b.GetValueOrDefault()), f()); else Assert.Null(f()); } private static void VerifyNullableShortPower(short? a, short? b, bool useInterpreter) { Expression<Func<short?>> e = Expression.Lambda<Func<short?>>( Expression.Power( Expression.Constant(a, typeof(short?)), Expression.Constant(b, typeof(short?)), typeof(BinaryNullablePowerTests).GetTypeInfo().GetDeclaredMethod("PowerShort") )); Func<short?> f = e.Compile(useInterpreter); if (a.HasValue & b.HasValue) Assert.Equal(PowerShort(a.GetValueOrDefault(), b.GetValueOrDefault()), f()); else Assert.Null(f()); } private static void VerifyNullableUIntPower(uint? a, uint? b, bool useInterpreter) { Expression<Func<uint?>> e = Expression.Lambda<Func<uint?>>( Expression.Power( Expression.Constant(a, typeof(uint?)), Expression.Constant(b, typeof(uint?)), typeof(BinaryNullablePowerTests).GetTypeInfo().GetDeclaredMethod("PowerUInt") )); Func<uint?> f = e.Compile(useInterpreter); if (a.HasValue & b.HasValue) Assert.Equal(PowerUInt(a.GetValueOrDefault(), b.GetValueOrDefault()), f()); else Assert.Null(f()); } private static void VerifyNullableIntPower(int? a, int? b, bool useInterpreter) { Expression<Func<int?>> e = Expression.Lambda<Func<int?>>( Expression.Power( Expression.Constant(a, typeof(int?)), Expression.Constant(b, typeof(int?)), typeof(BinaryNullablePowerTests).GetTypeInfo().GetDeclaredMethod("PowerInt") )); Func<int?> f = e.Compile(useInterpreter); if (a.HasValue & b.HasValue) Assert.Equal(PowerInt(a.GetValueOrDefault(), b.GetValueOrDefault()), f()); else Assert.Null(f()); } private static void VerifyNullableULongPower(ulong? a, ulong? b, bool useInterpreter) { Expression<Func<ulong?>> e = Expression.Lambda<Func<ulong?>>( Expression.Power( Expression.Constant(a, typeof(ulong?)), Expression.Constant(b, typeof(ulong?)), typeof(BinaryNullablePowerTests).GetTypeInfo().GetDeclaredMethod("PowerULong") )); Func<ulong?> f = e.Compile(useInterpreter); if (a.HasValue & b.HasValue) Assert.Equal(PowerULong(a.GetValueOrDefault(), b.GetValueOrDefault()), f()); else Assert.Null(f()); } private static void VerifyNullableLongPower(long? a, long? b, bool useInterpreter) { Expression<Func<long?>> e = Expression.Lambda<Func<long?>>( Expression.Power( Expression.Constant(a, typeof(long?)), Expression.Constant(b, typeof(long?)), typeof(BinaryNullablePowerTests).GetTypeInfo().GetDeclaredMethod("PowerLong") )); Func<long?> f = e.Compile(useInterpreter); if (a.HasValue & b.HasValue) Assert.Equal(PowerLong(a.GetValueOrDefault(), b.GetValueOrDefault()), f()); else Assert.Null(f()); } private static void VerifyNullableFloatPower(float? a, float? b, bool useInterpreter) { Expression<Func<float?>> e = Expression.Lambda<Func<float?>>( Expression.Power( Expression.Constant(a, typeof(float?)), Expression.Constant(b, typeof(float?)), typeof(BinaryNullablePowerTests).GetTypeInfo().GetDeclaredMethod("PowerFloat") )); Func<float?> f = e.Compile(useInterpreter); if (a.HasValue & b.HasValue) Assert.Equal(PowerFloat(a.GetValueOrDefault(), b.GetValueOrDefault()), f()); else Assert.Null(f()); } private static void VerifyNullableDoublePower(double? a, double? b, bool useInterpreter) { Expression<Func<double?>> e = Expression.Lambda<Func<double?>>( Expression.Power( Expression.Constant(a, typeof(double?)), Expression.Constant(b, typeof(double?)), typeof(BinaryNullablePowerTests).GetTypeInfo().GetDeclaredMethod("PowerDouble") )); Func<double?> f = e.Compile(useInterpreter); if (a.HasValue & b.HasValue) Assert.Equal(PowerDouble(a.GetValueOrDefault(), b.GetValueOrDefault()), f()); else Assert.Null(f()); } private static void VerifyNullableDecimalPower(decimal? a, decimal? b, bool useInterpreter) { Expression<Func<decimal?>> e = Expression.Lambda<Func<decimal?>>( Expression.Power( Expression.Constant(a, typeof(decimal?)), Expression.Constant(b, typeof(decimal?)), typeof(BinaryNullablePowerTests).GetTypeInfo().GetDeclaredMethod("PowerDecimal") )); Func<decimal?> f = e.Compile(useInterpreter); if (a.HasValue & b.HasValue) { decimal expected = 0; try { expected = PowerDecimal(a.GetValueOrDefault(), b.GetValueOrDefault()); } catch (OverflowException) { Assert.Throws<OverflowException>(() => f()); return; } Assert.Equal(expected, f()); } else Assert.Null(f()); } private static void VerifyNullableCharPower(char? a, char? b, bool useInterpreter) { Expression<Func<char?>> e = Expression.Lambda<Func<char?>>( Expression.Power( Expression.Constant(a, typeof(char?)), Expression.Constant(b, typeof(char?)), typeof(BinaryNullablePowerTests).GetTypeInfo().GetDeclaredMethod("PowerChar") )); Func<char?> f = e.Compile(useInterpreter); if (a.HasValue & b.HasValue) Assert.Equal(PowerChar(a.GetValueOrDefault(), b.GetValueOrDefault()), f()); else Assert.Null(f()); } #endregion #region Helper methods public static byte PowerByte(byte a, byte b) { return unchecked((byte)Math.Pow(a, b)); } public static sbyte PowerSByte(sbyte a, sbyte b) { return unchecked((sbyte)Math.Pow(a, b)); } public static ushort PowerUShort(ushort a, ushort b) { return unchecked((ushort)Math.Pow(a, b)); } public static short PowerShort(short a, short b) { return unchecked((short)Math.Pow(a, b)); } public static uint PowerUInt(uint a, uint b) { return unchecked((uint)Math.Pow(a, b)); } public static int PowerInt(int a, int b) { return unchecked((int)Math.Pow(a, b)); } public static ulong PowerULong(ulong a, ulong b) { return unchecked((ulong)Math.Pow(a, b)); } public static long PowerLong(long a, long b) { return unchecked((long)Math.Pow(a, b)); } public static float PowerFloat(float a, float b) { return (float)Math.Pow(a, b); } public static double PowerDouble(double a, double b) { return Math.Pow(a, b); } public static decimal PowerDecimal(decimal a, decimal b) { return (decimal)Math.Pow((double)a, (double)b); } public static char PowerChar(char a, char b) { return unchecked((char)Math.Pow(a, b)); } #endregion } }
//********************************************************* // // Copyright (c) Microsoft. All rights reserved. // This code is licensed under the MIT License (MIT). // 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.Threading.Tasks; using Windows.Foundation.Collections; using Windows.UI.Xaml.Controls; using Windows.ApplicationModel.Activation; using Windows.ApplicationModel.Background; using Windows.Storage; using Windows.UI.Xaml; namespace SDKTemplate { public partial class MainPage : Page { public const string FEATURE_NAME = "Background Activation"; List<Scenario> scenarios = new List<Scenario> { new Scenario() { Title="Background Task", ClassType=typeof(SampleBackgroundTask)}, new Scenario() { Title="Background Task with Condition", ClassType=typeof(SampleBackgroundTaskWithCondition)}, new Scenario() { Title="Servicing Complete Task", ClassType=typeof(ServicingCompleteTask)}, new Scenario() { Title="Background Task with Time Trigger", ClassType=typeof(TimeTriggeredTask) }, new Scenario() { Title="Background Task with Application Trigger", ClassType=typeof(ApplicationTriggerTask) } }; } public class Scenario { public string Title { get; set; } public Type ClassType { get; set; } } } namespace SDKTemplate { class BackgroundTaskSample { public const string SampleBackgroundTaskName = "SampleBackgroundTask"; public static string SampleBackgroundTaskProgress = ""; public static bool SampleBackgroundTaskRegistered = false; public const string SampleBackgroundTaskWithConditionName = "SampleBackgroundTaskWithCondition"; public static string SampleBackgroundTaskWithConditionProgress = ""; public static bool SampleBackgroundTaskWithConditionRegistered = false; public const string ServicingCompleteTaskName = "ServicingCompleteTask"; public static string ServicingCompleteTaskProgress = ""; public static bool ServicingCompleteTaskRegistered = false; public const string TimeTriggeredTaskName = "TimeTriggeredTask"; public static string TimeTriggeredTaskProgress = ""; public static bool TimeTriggeredTaskRegistered = false; public const string ApplicationTriggerTaskName = "ApplicationTriggerTask"; public static string ApplicationTriggerTaskProgress = ""; public static string ApplicationTriggerTaskResult = ""; public static bool ApplicationTriggerTaskRegistered = false; // These strings are manipulated by multiple threads, so we must // use a thread-safe container. public static PropertySet TaskStatuses = new PropertySet(); /// <summary> /// Register a background task with the specified taskEntryPoint, name, trigger, /// and condition (optional). /// </summary> /// <param name="taskEntryPoint">Task entry point for the background task.</param> /// <param name="name">A name for the background task.</param> /// <param name="trigger">The trigger for the background task.</param> /// <param name="condition">An optional conditional event that must be true for the task to fire.</param> public static BackgroundTaskRegistration RegisterBackgroundTask(String taskEntryPoint, String name, IBackgroundTrigger trigger, IBackgroundCondition condition) { if (TaskRequiresBackgroundAccess(name)) { // If the user denies access, the task will not run. var requestTask = BackgroundExecutionManager.RequestAccessAsync(); } var builder = new BackgroundTaskBuilder(); builder.Name = name; if (taskEntryPoint != null) { // If you leave the TaskEntryPoint at its default value, then the task runs // inside the main process from OnBackgroundActivated rather than as a separate process. builder.TaskEntryPoint = taskEntryPoint; } builder.SetTrigger(trigger); if (condition != null) { builder.AddCondition(condition); // // If the condition changes while the background task is executing then it will // be canceled. // builder.CancelOnConditionLoss = true; } BackgroundTaskRegistration task = builder.Register(); UpdateBackgroundTaskRegistrationStatus(name, true); // // Remove previous completion status. // TaskStatuses.Remove(name); return task; } /// <summary> /// Unregister background tasks with specified name. /// </summary> /// <param name="name">Name of the background task to unregister.</param> public static void UnregisterBackgroundTasks(String name) { // // Loop through all background tasks and unregister any with SampleBackgroundTaskName or // SampleBackgroundTaskWithConditionName. // foreach (var cur in BackgroundTaskRegistration.AllTasks) { if (cur.Value.Name == name) { cur.Value.Unregister(true); } } UpdateBackgroundTaskRegistrationStatus(name, false); } /// <summary> /// Store the registration status of a background task with a given name. /// </summary> /// <param name="name">Name of background task to store registration status for.</param> /// <param name="registered">TRUE if registered, FALSE if unregistered.</param> public static void UpdateBackgroundTaskRegistrationStatus(String name, bool registered) { switch (name) { case SampleBackgroundTaskName: SampleBackgroundTaskRegistered = registered; break; case SampleBackgroundTaskWithConditionName: SampleBackgroundTaskWithConditionRegistered = registered; break; case ServicingCompleteTaskName: ServicingCompleteTaskRegistered = registered; break; case TimeTriggeredTaskName: TimeTriggeredTaskRegistered = registered; break; case ApplicationTriggerTaskName: ApplicationTriggerTaskRegistered = registered; break; } } /// <summary> /// Get the registration / completion status of the background task with /// given name. /// </summary> /// <param name="name">Name of background task to retreive registration status.</param> public static String GetBackgroundTaskStatus(String name) { var registered = false; switch (name) { case SampleBackgroundTaskName: registered = SampleBackgroundTaskRegistered; break; case SampleBackgroundTaskWithConditionName: registered = SampleBackgroundTaskWithConditionRegistered; break; case ServicingCompleteTaskName: registered = ServicingCompleteTaskRegistered; break; case TimeTriggeredTaskName: registered = TimeTriggeredTaskRegistered; break; case ApplicationTriggerTaskName: registered = ApplicationTriggerTaskRegistered; break; } var status = registered ? "Registered" : "Unregistered"; object taskStatus; if (TaskStatuses.TryGetValue(name, out taskStatus)) { status += " - " + taskStatus.ToString(); } return status; } /// <summary> /// Determine if task with given name requires background access. /// </summary> /// <param name="name">Name of background task to query background access requirement.</param> public static bool TaskRequiresBackgroundAccess(String name) { if ((name == TimeTriggeredTaskName) || (name == ApplicationTriggerTaskName)) { return true; } else { return false; } } } } namespace SDKTemplate { sealed partial class App : Application { /// <summary> /// Override the Application.OnBackgroundActivated method to handle background activation in /// the main process. This entry point is used when BackgroundTaskBuilder.TaskEntryPoint is /// not set during background task registration. /// </summary> /// <param name="args"></param> protected override void OnBackgroundActivated(BackgroundActivatedEventArgs args) { BackgroundActivity.Start(args.TaskInstance); } } }
// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. namespace Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters { using System; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Reflection; using System.Reflection.Emit; using Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters.CodeBuilders; using Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters.SimpleAST; using Telerik.JustMock.Core.Castle.DynamicProxy.Internal; [DebuggerDisplay("{builder.Name}")] internal class MethodEmitter : IMemberEmitter { private readonly MethodBuilder builder; private readonly GenericTypeParameterBuilder[] genericTypeParams; private ArgumentReference[] arguments; private MethodCodeBuilder codebuilder; protected internal MethodEmitter(MethodBuilder builder) { this.builder = builder; } internal MethodEmitter(AbstractTypeEmitter owner, String name, MethodAttributes attributes) : this(owner.TypeBuilder.DefineMethod(name, attributes)) { } internal MethodEmitter(AbstractTypeEmitter owner, String name, MethodAttributes attributes, Type returnType, params Type[] argumentTypes) : this(owner, name, attributes) { SetParameters(argumentTypes); SetReturnType(returnType); } internal MethodEmitter(AbstractTypeEmitter owner, String name, MethodAttributes attributes, MethodInfo methodToUseAsATemplate) : this(owner, name, attributes) { var name2GenericType = GenericUtil.GetGenericArgumentsMap(owner); var returnType = GenericUtil.ExtractCorrectType(methodToUseAsATemplate.ReturnType, name2GenericType); var baseMethodParameters = methodToUseAsATemplate.GetParameters(); var parameters = GenericUtil.ExtractParametersTypes(baseMethodParameters, name2GenericType); genericTypeParams = GenericUtil.CopyGenericArguments(methodToUseAsATemplate, builder, name2GenericType); SetParameters(parameters); SetReturnType(returnType); SetSignature(returnType, methodToUseAsATemplate.ReturnParameter, parameters, baseMethodParameters); DefineParameters(baseMethodParameters); } public ArgumentReference[] Arguments { get { return arguments; } } public virtual MethodCodeBuilder CodeBuilder { get { if (codebuilder == null) { codebuilder = new MethodCodeBuilder(builder.GetILGenerator()); } return codebuilder; } } public GenericTypeParameterBuilder[] GenericTypeParams { get { return genericTypeParams; } } public MethodBuilder MethodBuilder { get { return builder; } } public MemberInfo Member { get { return builder; } } public Type ReturnType { get { return builder.ReturnType; } } private bool ImplementedByRuntime { get { #if FEATURE_LEGACY_REFLECTION_API var attributes = builder.GetMethodImplementationFlags(); #else var attributes = builder.MethodImplementationFlags; #endif return (attributes & MethodImplAttributes.Runtime) != 0; } } public void DefineCustomAttribute(CustomAttributeBuilder attribute) { builder.SetCustomAttribute(attribute); } public void SetParameters(Type[] paramTypes) { builder.SetParameters(paramTypes); arguments = ArgumentsUtil.ConvertToArgumentReference(paramTypes); ArgumentsUtil.InitializeArgumentsByPosition(arguments, MethodBuilder.IsStatic); } public virtual void EnsureValidCodeBlock() { if (ImplementedByRuntime == false && CodeBuilder.IsEmpty) { CodeBuilder.AddStatement(new NopStatement()); CodeBuilder.AddStatement(new ReturnStatement()); } } public virtual void Generate() { if (ImplementedByRuntime) { return; } codebuilder.Generate(this, builder.GetILGenerator()); } private void DefineParameters(ParameterInfo[] parameters) { foreach (var parameter in parameters) { var parameterBuilder = builder.DefineParameter(parameter.Position + 1, parameter.Attributes, parameter.Name); foreach (var attribute in parameter.GetNonInheritableAttributes()) { parameterBuilder.SetCustomAttribute(attribute.Builder); } // If a parameter has a default value, that default value needs to be replicated. // Default values as reported by `ParameterInfo.[Raw]DefaultValue` have two possible origins: // // 1. A `[DecimalConstant]` or `[DateTimeConstant]` custom attribute attached to the parameter. // Attribute-based default values have already been copied above. // (Note that another attribute type, `[DefaultParameterValue]`, only appears in source // code. The compiler replaces it with another metadata construct:) // // 2. A `Constant` metadata table entry whose parent is the parameter. // Constant-based default values need more work. We can detect this case by checking // whether the `ParameterAttributes.HasDefault` flag is set. (NB: This is not the same // as querying `ParameterInfo.HasDefault`, which would also return true for case (1)!) if ((parameter.Attributes & ParameterAttributes.HasDefault) != 0) { try { CopyDefaultValueConstant(from: parameter, to: parameterBuilder); } catch { // Default value replication is a nice-to-have feature but not essential, // so if it goes wrong for one parameter, just continue. } } } } private void CopyDefaultValueConstant(ParameterInfo from, ParameterBuilder to) { Debug.Assert(from != null); Debug.Assert(to != null); Debug.Assert((from.Attributes & ParameterAttributes.HasDefault) != 0); object defaultValue; try { defaultValue = from.DefaultValue; } catch (FormatException) when (from.ParameterType == typeof(DateTime)) { // This catch clause guards against a CLR bug that makes it impossible to query // the default value of an optional DateTime parameter. For the CoreCLR, see // https://github.com/dotnet/corefx/issues/26164. // If this bug is present, it is caused by a `null` default value: defaultValue = null; } catch (FormatException) when (from.ParameterType.GetTypeInfo().IsEnum) { // This catch clause guards against a CLR bug that makes it impossible to query // the default value of a (closed generic) enum parameter. For the CoreCLR, see // https://github.com/dotnet/corefx/issues/29570. // If this bug is present, it is caused by a `null` default value: defaultValue = null; } if (defaultValue is Missing) { // It is likely that we are reflecting over invalid metadata if we end up here. // At this point, `to.Attributes` will have the `HasDefault` flag set. If we do // not call `to.SetConstant`, that flag will be reset when creating the dynamic // type, so `to` will at least end up having valid metadata. It is quite likely // that the `Missing.Value` will still be reproduced because the `Parameter- // Builder`'s `ParameterAttributes.Optional` is likely set. (If it isn't set, // we'll be causing a default value of `DBNull.Value`, but there's nothing that // can be done about that, short of recreating a new `ParameterBuilder`.) return; } try { to.SetConstant(defaultValue); } catch (ArgumentException) { var parameterType = from.ParameterType; var parameterNonNullableType = parameterType; if (defaultValue == null) { if (parameterType.IsNullableType()) { // This guards against a Mono bug that prohibits setting default value `null` // for a `Nullable<T>` parameter. See https://github.com/mono/mono/issues/8504. // // If this bug is present, luckily we still get `null` as the default value if // we do nothing more (which is probably itself yet another bug, as the CLR // would "produce" a default value of `Missing.Value` in this situation). return; } else if (parameterType.GetTypeInfo().IsValueType) { // This guards against a CLR bug that prohibits replicating `null` default // values for non-nullable value types (which, despite the apparent type // mismatch, is perfectly legal and something that the Roslyn compilers do). // For the CoreCLR, see https://github.com/dotnet/corefx/issues/26184. // If this bug is present, the best we can do is to not set the default value. // This will cause a default value of `Missing.Value` (if `ParameterAttributes- // .Optional` is set) or `DBNull.Value` (otherwise, unlikely). return; } } else if (parameterType.IsNullableType()) { parameterNonNullableType = from.ParameterType.GetGenericArguments()[0]; if (parameterNonNullableType.GetTypeInfo().IsEnum || parameterNonNullableType.IsAssignableFrom(defaultValue.GetType())) { // This guards against two bugs: // // * On the CLR and CoreCLR, a bug that makes it impossible to use `ParameterBuilder- // .SetConstant` on parameters of a nullable enum type. For CoreCLR, see // https://github.com/dotnet/coreclr/issues/17893. // // If this bug is present, there is no way to faithfully reproduce the default // value. This will most likely cause a default value of `Missing.Value` or // `DBNull.Value`. (To better understand which of these, see comment above). // // * On Mono, a bug that performs a too-strict type check for nullable types. The // value passed to `ParameterBuilder.SetConstant` must have a type matching that // of the parameter precisely. See https://github.com/mono/mono/issues/8597. // // If this bug is present, there's no way to reproduce the default value because // we cannot actually create a value of type `Nullable<>`. return; } } // Finally, we might have got here because the metadata constant simply doesn't match // the parameter type exactly. Some code generators other than the .NET compilers // might produce such metadata. Make a final attempt to coerce it to the required type: try { var coercedDefaultValue = Convert.ChangeType(defaultValue, parameterNonNullableType, CultureInfo.InvariantCulture); to.SetConstant(coercedDefaultValue); return; } catch { // We don't care about the error thrown by an unsuccessful type coercion. } throw; } } private void SetReturnType(Type returnType) { builder.SetReturnType(returnType); } private void SetSignature(Type returnType, ParameterInfo returnParameter, Type[] parameters, ParameterInfo[] baseMethodParameters) { Type[] returnRequiredCustomModifiers; Type[] returnOptionalCustomModifiers; Type[][] parametersRequiredCustomModifiers; Type[][] parametersOptionalCustomModifiers; #if FEATURE_EMIT_CUSTOMMODIFIERS returnRequiredCustomModifiers = returnParameter.GetRequiredCustomModifiers(); Array.Reverse(returnRequiredCustomModifiers); returnOptionalCustomModifiers = returnParameter.GetOptionalCustomModifiers(); Array.Reverse(returnOptionalCustomModifiers); int parameterCount = baseMethodParameters.Length; parametersRequiredCustomModifiers = new Type[parameterCount][]; parametersOptionalCustomModifiers = new Type[parameterCount][]; for (int i = 0; i < parameterCount; ++i) { parametersRequiredCustomModifiers[i] = baseMethodParameters[i].GetRequiredCustomModifiers(); Array.Reverse(parametersRequiredCustomModifiers[i]); parametersOptionalCustomModifiers[i] = baseMethodParameters[i].GetOptionalCustomModifiers(); Array.Reverse(parametersOptionalCustomModifiers[i]); } #else returnRequiredCustomModifiers = null; returnOptionalCustomModifiers = null; parametersRequiredCustomModifiers = null; parametersOptionalCustomModifiers = null; #endif builder.SetSignature( returnType, returnRequiredCustomModifiers, returnOptionalCustomModifiers, parameters, parametersRequiredCustomModifiers, parametersOptionalCustomModifiers); } } }
#region License /* Illusory Studios C# Crypto Library (CryptSharp) Copyright (c) 2010 James F. Bellinger <[email protected]> Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #endregion namespace CryptSharp.Utility { public partial class BlowfishCipher { // Change this if you want a special but incompatible version of BCrypt. private const int N = 16; private static readonly uint[][] S0 = new[] { new uint[] { 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7, 0xb8e1afed, 0x6a267e96, 0xba7c9045, 0xf12c7f99, 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16, 0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e, 0x0d95748f, 0x728eb658, 0x718bcd58, 0x82154aee, 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013, 0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef, 0x8e79dcb0, 0x603a180e, 0x6c9e0e8b, 0xb01e8a3e, 0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60, 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440, 0x55ca396a, 0x2aab10b6, 0xb4cc5c34, 0x1141e8ce, 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a, 0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e, 0xafd6ba33, 0x6c24cf5c, 0x7a325381, 0x28958677, 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193, 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032, 0xef845d5d, 0xe98575b1, 0xdc262302, 0xeb651b88, 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239, 0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e, 0x21c66842, 0xf6e96c9a, 0x670c9c61, 0xabd388f0, 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3, 0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98, 0xa1f1651d, 0x39af0176, 0x66ca593e, 0x82430e88, 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe, 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6, 0x4ed3aa62, 0x363f7706, 0x1bfedf72, 0x429b023d, 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b, 0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7, 0xe3fe501a, 0xb6794c3b, 0x976ce0bd, 0x04c006ba, 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463, 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f, 0x6dfc511f, 0x9b30952c, 0xcc814544, 0xaf5ebd09, 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3, 0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb, 0x5579c0bd, 0x1a60320a, 0xd6a100c6, 0x402c7279, 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8, 0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab, 0x323db5fa, 0xfd238760, 0x53317b48, 0x3e00df82, 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db, 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573, 0x695b27b0, 0xbbca58c8, 0xe1ffa35d, 0xb8f011a0, 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b, 0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790, 0xe1ddf2da, 0xa4cb7e33, 0x62fb1341, 0xcee4c6e8, 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4, 0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0, 0xd08ed1d0, 0xafc725e0, 0x8e3c5b2f, 0x8e7594b7, 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c, 0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad, 0x2f2f2218, 0xbe0e1777, 0xea752dfe, 0x8b021fa1, 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299, 0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9, 0x165fa266, 0x80957705, 0x93cc7314, 0x211a1477, 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf, 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49, 0x00250e2d, 0x2071b35e, 0x226800bb, 0x57b8e0af, 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa, 0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5, 0x83260376, 0x6295cfa9, 0x11c81968, 0x4e734a41, 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915, 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400, 0x08ba6fb5, 0x571be91f, 0xf296ec6b, 0x2a0dd915, 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664, 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a }, new uint[] { 0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623, 0xad6ea6b0, 0x49a7df7d, 0x9cee60b8, 0x8fedb266, 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1, 0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e, 0x3f54989a, 0x5b429d65, 0x6b8fe4d6, 0x99f73fd6, 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1, 0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e, 0x09686b3f, 0x3ebaefc9, 0x3c971814, 0x6b6a70a1, 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737, 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8, 0xb03ada37, 0xf0500c0d, 0xf01c1f04, 0x0200b3ff, 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd, 0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701, 0x3ae5e581, 0x37c2dadc, 0xc8b57634, 0x9af3dda7, 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41, 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331, 0x4e548b38, 0x4f6db908, 0x6f420d03, 0xf60a04bf, 0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af, 0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e, 0x5512721f, 0x2e6b7124, 0x501adde6, 0x9f84cd87, 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c, 0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2, 0xef1c1847, 0x3215d908, 0xdd433b37, 0x24c2ba16, 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd, 0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b, 0x043556f1, 0xd7a3c76b, 0x3c11183b, 0x5924a509, 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e, 0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3, 0x771fe71c, 0x4e3d06fa, 0x2965dcb9, 0x99e71d0f, 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a, 0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4, 0xf2f74ea7, 0x361d2b3d, 0x1939260f, 0x19c27960, 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66, 0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28, 0xc332ddef, 0xbe6c5aa5, 0x65582185, 0x68ab9802, 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84, 0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510, 0x13cca830, 0xeb61bd96, 0x0334fe1e, 0xaa0363cf, 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14, 0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e, 0x648b1eaf, 0x19bdf0ca, 0xa02369b9, 0x655abb50, 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7, 0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8, 0xf837889a, 0x97e32d77, 0x11ed935f, 0x16681281, 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99, 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696, 0xcdb30aeb, 0x532e3054, 0x8fd948e4, 0x6dbc3128, 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73, 0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0, 0x45eee2b6, 0xa3aaabea, 0xdb6c4f15, 0xfacb4fd0, 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105, 0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250, 0xcf62a1f2, 0x5b8d2646, 0xfc8883a0, 0xc1c7b6a3, 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285, 0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00, 0x58428d2a, 0x0c55f5ea, 0x1dadf43e, 0x233f7061, 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb, 0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e, 0xa6078084, 0x19f8509e, 0xe8efd855, 0x61d99735, 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc, 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9, 0xdb73dbd3, 0x105588cd, 0x675fda79, 0xe3674340, 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20, 0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7 }, new uint[] { 0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934, 0x411520f7, 0x7602d4f7, 0xbcf46b2e, 0xd4a20068, 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af, 0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840, 0x4d95fc1d, 0x96b591af, 0x70f4ddd3, 0x66a02f45, 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504, 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a, 0x28507825, 0x530429f4, 0x0a2c86da, 0xe9b66dfb, 0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee, 0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6, 0xaace1e7c, 0xd3375fec, 0xce78a399, 0x406b2a42, 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b, 0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2, 0x3a6efa74, 0xdd5b4332, 0x6841e7f7, 0xca7820fb, 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527, 0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b, 0x55a867bc, 0xa1159a58, 0xcca92963, 0x99e1db33, 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c, 0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3, 0x95c11548, 0xe4c66d22, 0x48c1133f, 0xc70f86dc, 0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17, 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564, 0x257b7834, 0x602a9c60, 0xdff8e8a3, 0x1f636c1b, 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115, 0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922, 0x85b2a20e, 0xe6ba0d99, 0xde720c8c, 0x2da2f728, 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0, 0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e, 0x0a476341, 0x992eff74, 0x3a6f6eab, 0xf4f8fd37, 0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d, 0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804, 0xf1290dc7, 0xcc00ffa3, 0xb5390f92, 0x690fed0b, 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3, 0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb, 0x37392eb3, 0xcc115979, 0x8026e297, 0xf42e312d, 0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c, 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350, 0x1a6b1018, 0x11caedfa, 0x3d25bdd8, 0xe2e1c3c9, 0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a, 0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe, 0x9dbc8057, 0xf0f7c086, 0x60787bf8, 0x6003604d, 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc, 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f, 0x77a057be, 0xbde8ae24, 0x55464299, 0xbf582e61, 0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2, 0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9, 0x7aeb2661, 0x8b1ddf84, 0x846a0e79, 0x915f95e2, 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c, 0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e, 0xb77f19b6, 0xe0a9dc09, 0x662d09a1, 0xc4324633, 0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10, 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169, 0xdcb7da83, 0x573906fe, 0xa1e2ce9b, 0x4fcd7f52, 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027, 0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5, 0xf0177a28, 0xc0f586e0, 0x006058aa, 0x30dc7d62, 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634, 0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76, 0x6f05e409, 0x4b7c0188, 0x39720a3d, 0x7c927c24, 0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc, 0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4, 0x1e50ef5e, 0xb161e6f8, 0xa28514d9, 0x6c51133c, 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837, 0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0 }, new uint[] { 0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b, 0x5cb0679e, 0x4fa33742, 0xd3822740, 0x99bc9bbe, 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b, 0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4, 0x5748ab2f, 0xbc946e79, 0xc6a376d2, 0x6549c2c8, 0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6, 0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304, 0xa1fad5f0, 0x6a2d519a, 0x63ef8ce2, 0x9a86ee22, 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4, 0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6, 0x2826a2f9, 0xa73a3ae1, 0x4ba99586, 0xef5562e9, 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59, 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593, 0xe990fd5a, 0x9e34d797, 0x2cf0b7d9, 0x022b8b51, 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28, 0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c, 0xe029ac71, 0xe019a5e6, 0x47b0acfd, 0xed93fa9b, 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28, 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c, 0x15056dd4, 0x88f46dba, 0x03a16125, 0x0564f0bd, 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a, 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319, 0x7533d928, 0xb155fdf5, 0x03563482, 0x8aba3cbb, 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f, 0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991, 0xea7a90c2, 0xfb3e7bce, 0x5121ce64, 0x774fbe32, 0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680, 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166, 0xb39a460a, 0x6445c0dd, 0x586cdecf, 0x1c20c8ae, 0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb, 0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5, 0x72eacea8, 0xfa6484bb, 0x8d6612ae, 0xbf3c6f47, 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370, 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d, 0x4040cb08, 0x4eb4e2cc, 0x34d2466a, 0x0115af84, 0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048, 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8, 0x611560b1, 0xe7933fdc, 0xbb3a792b, 0x344525bd, 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9, 0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7, 0x1a908749, 0xd44fbd9a, 0xd0dadecb, 0xd50ada38, 0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f, 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c, 0xbf97222c, 0x15e6fc2a, 0x0f91fc71, 0x9b941525, 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1, 0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442, 0xe0ec6e0e, 0x1698db3b, 0x4c98a0be, 0x3278e964, 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e, 0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8, 0xdf359f8d, 0x9b992f2e, 0xe60b6f47, 0x0fe3f11d, 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f, 0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299, 0xf523f357, 0xa6327623, 0x93a83531, 0x56cccd02, 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc, 0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614, 0xe6c6c7bd, 0x327a140a, 0x45e1d006, 0xc3f27b9a, 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6, 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b, 0x53113ec0, 0x1640e3d3, 0x38abbd60, 0x2547adf0, 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060, 0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e, 0x1948c25c, 0x02fb8a8c, 0x01c36ae4, 0xd6ebe1f9, 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f, 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6 } }; private static readonly uint[] P0 = new uint[] { 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, 0xa4093822, 0x299f31d0, 0x082efa98, 0xec4e6c89, 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c, 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917, 0x9216d5d9, 0x8979fb1b }; public static string BCryptMagic { get { return "OrpheanBeholderScryDoubt"; } } } }
// 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.Threading.Tasks; using Xunit; namespace System.IO.Compression.Tests { public class zip_ManualAndCompatabilityTests : ZipFileTestBase { public static bool IsUsingNewPathNormalization => !PathFeatures.IsUsingLegacyPathNormalization(); [Theory] [InlineData("7zip.zip", "normal", true, true)] [InlineData("windows.zip", "normalWithoutEmptyDir", false, true)] [InlineData("dotnetzipstreaming.zip", "normal", false, false)] [InlineData("sharpziplib.zip", "normalWithoutEmptyDir", false, false)] [InlineData("xceedstreaming.zip", "normal", false, false)] public static async Task CompatibilityTests(string zipFile, string zipFolder, bool requireExplicit, bool checkTimes) { IsZipSameAsDir(await StreamHelpers.CreateTempCopyStream(compat(zipFile)), zfolder(zipFolder), ZipArchiveMode.Update, requireExplicit, checkTimes); } [Fact] public static async Task Deflate64Zip() { IsZipSameAsDir(await StreamHelpers.CreateTempCopyStream(compat("deflate64.zip")), zfolder("normal"), ZipArchiveMode.Update, requireExplicit: true, checkTimes: true); } [Theory] [InlineData("excel.xlsx", "excel", false, false)] [InlineData("powerpoint.pptx", "powerpoint", false, false)] [InlineData("word.docx", "word", false, false)] [InlineData("silverlight.xap", "silverlight", false, false)] [InlineData("packaging.package", "packaging", false, false)] public static async Task CompatibilityTestsMsFiles(string withTrailing, string withoutTrailing, bool requireExplicit, bool checkTimes) { IsZipSameAsDir(await StreamHelpers.CreateTempCopyStream(compat(withTrailing)), compat(withoutTrailing), ZipArchiveMode.Update, requireExplicit, checkTimes); } /// <summary> /// This test ensures that a zipfile created on one platform with a file containing potentially invalid characters elsewhere /// will be interpreted based on the source OS path name validation rules. /// /// For example, the file "aa\bb\cc\dd" in a zip created on Unix should be one file "aa\bb\cc\dd" whereas the same file /// in a zip created on Windows should be interpreted as the file "dd" underneath three subdirectories. /// </summary> [ConditionalTheory(nameof(IsUsingNewPathNormalization))] [InlineData("backslashes_FromUnix.zip", "aa\\bb\\cc\\dd")] [InlineData("backslashes_FromWindows.zip", "dd")] [InlineData("WindowsInvalid_FromUnix.zip", "aa<b>d")] [InlineData("WindowsInvalid_FromWindows.zip", "aa<b>d")] [InlineData("NullCharFileName_FromWindows.zip", "a\06b6d")] [InlineData("NullCharFileName_FromUnix.zip", "a\06b6d")] public static async Task ZipWithInvalidFileNames_ParsedBasedOnSourceOS(string zipName, string fileName) { using (Stream stream = await StreamHelpers.CreateTempCopyStream(compat(zipName))) using (ZipArchive archive = new ZipArchive(stream)) { Assert.Equal(1, archive.Entries.Count); ZipArchiveEntry entry = archive.Entries[0]; Assert.Equal(fileName, entry.Name); } } /// <summary> /// This test compares binary content of a zip produced by the current version with a zip produced by /// other frameworks. It does this by searching the two zips for the header signature and then /// it compares the subsequent header values for equality. /// /// This test looks for the local file headers that each entry within a zip possesses and compares these /// values: /// local file header signature 4 bytes (0x04034b50) /// version needed to extract 2 bytes /// general purpose bit flag 2 bytes /// compression method 2 bytes /// last mod file time 2 bytes /// last mod file date 2 bytes /// /// it does not compare these values: /// /// crc-32 4 bytes /// compressed size 4 bytes /// uncompressed size 4 bytes /// file name length 2 bytes /// extra field length 2 bytes /// file name(variable size) /// extra field(variable size) /// </summary> [Theory] [InlineData("net45_unicode.zip", "unicode")] [InlineData("net46_unicode.zip", "unicode")] [InlineData("net45_normal.zip", "normal")] [InlineData("net46_normal.zip", "normal")] public static async Task ZipBinaryCompat_LocalFileHeaders(string zipFile, string zipFolder) { using (MemoryStream actualArchiveStream = new MemoryStream()) using (MemoryStream expectedArchiveStream = await StreamHelpers.CreateTempCopyStream(compat(zipFile))) { byte[] localFileHeaderSignature = new byte[] { 0x50, 0x4b, 0x03, 0x04 }; // Produce a ZipFile await CreateFromDir(zfolder(zipFolder), actualArchiveStream, ZipArchiveMode.Create); // Read the streams to byte arrays byte[] actualBytes = actualArchiveStream.ToArray(); byte[] expectedBytes = expectedArchiveStream.ToArray(); // Search for the file headers int actualIndex = 0, expectedIndex = 0; while ((expectedIndex = FindIndexOfSequence(expectedBytes, expectedIndex, localFileHeaderSignature)) != -1) { actualIndex = FindIndexOfSequence(actualBytes, actualIndex, localFileHeaderSignature); Assert.NotEqual(-1, actualIndex); for (int i = 0; i < 14; i++) { Assert.Equal(expectedBytes[expectedIndex], actualBytes[actualIndex]); } expectedIndex += 14; actualIndex += 14; } } } /// <summary> /// This test compares binary content of a zip produced by the current version with a zip produced by /// other frameworks. It does this by searching the two zips for the header signature and then /// it compares the subsequent header values for equality. /// /// This test looks for the central directory headers that each entry within a zip possesses and compares these /// values: /// central file header signature 4 bytes (0x02014b50) /// version made by 2 bytes /// version needed to extract 2 bytes /// general purpose bit flag 2 bytes /// compression method 2 bytes /// last mod file time 2 bytes /// last mod file date 2 bytes /// uncompressed size 4 bytes /// file name length 2 bytes /// extra field length 2 bytes /// file comment length 2 bytes /// disk number start 2 bytes /// internal file attributes 2 bytes /// external file attributes 4 bytes /// /// it does not compare these values: /// crc-32 4 bytes /// compressed size 4 bytes /// relative offset of local header 4 bytes /// file name (variable size) /// extra field (variable size) /// file comment (variable size) /// </summary> [Theory] [InlineData("net45_unicode.zip", "unicode")] [InlineData("net46_unicode.zip", "unicode")] [InlineData("net45_normal.zip", "normal")] [InlineData("net46_normal.zip", "normal")] public static async Task ZipBinaryCompat_CentralDirectoryHeaders(string zipFile, string zipFolder) { using (MemoryStream actualArchiveStream = new MemoryStream()) using (MemoryStream expectedArchiveStream = await StreamHelpers.CreateTempCopyStream(compat(zipFile))) { byte[] signature = new byte[] { 0x50, 0x4b, 0x03, 0x04 }; // Produce a ZipFile await CreateFromDir(zfolder(zipFolder), actualArchiveStream, ZipArchiveMode.Create); // Read the streams to byte arrays byte[] actualBytes = actualArchiveStream.ToArray(); byte[] expectedBytes = expectedArchiveStream.ToArray(); // Search for the file headers int actualIndex = 0, expectedIndex = 0; while ((expectedIndex = FindIndexOfSequence(expectedBytes, expectedIndex, signature)) != -1) { actualIndex = FindIndexOfSequence(actualBytes, actualIndex, signature); Assert.NotEqual(-1, actualIndex); for (int i = 0; i < 16; i++) { Assert.Equal(expectedBytes[expectedIndex], actualBytes[actualIndex]); } for (int i = 24; i < 42; i++) { Assert.Equal(expectedBytes[expectedIndex], actualBytes[actualIndex]); } expectedIndex += 38; actualIndex += 38; } } } /// <summary> /// Simple helper method to search <paramref name="bytesToSearch"/> for the exact byte sequence specified by /// <paramref name="sequenceToFind"/>, starting at <paramref name="startIndex"/>. /// </summary> /// <returns>The first index of the first element in the matching sequence</returns> public static int FindIndexOfSequence(byte[] bytesToSearch, int startIndex, byte[] sequenceToFind) { for (int index = startIndex; index < bytesToSearch.Length - sequenceToFind.Length; index++) { bool equal = true; for (int i = 0; i < sequenceToFind.Length; i++) { if (bytesToSearch[index + i] != sequenceToFind[i]) { equal = false; break; } } if (equal) return index; } return -1; } } }
#region License /* The MIT License * * Copyright (c) 2011 Red Badger Consulting * * 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 //------------------------------------------------------------------------------------------------- // <auto-generated> // Marked as auto-generated so StyleCop will ignore BDD style tests // </auto-generated> //------------------------------------------------------------------------------------------------- #pragma warning disable 169 // ReSharper disable InconsistentNaming // ReSharper disable UnusedMember.Global // ReSharper disable UnusedMember.Local namespace RedBadger.Xpf.Specs.Controls.ScrollViewerSpecs { using System.Collections.Generic; using System.Reactive.Subjects; using Machine.Specifications; using Moq; using RedBadger.Xpf.Adapters.Xna.Graphics; using RedBadger.Xpf.Controls; using RedBadger.Xpf.Graphics; using RedBadger.Xpf.Input; using RedBadger.Xpf.Specs.Extensions; using It = Machine.Specifications.It; public abstract class a_ScrollViewer { protected static Subject<Gesture> Gestures; protected static Mock<IInputManager> InputManager; protected static Mock<Renderer> Renderer; protected static Mock<RootElement> RootElement; protected static ScrollViewer ScrollViewer; protected static Rect ViewPort = new Rect(0, 0, 100, 100); private Establish context = () => { Renderer = new Mock<Renderer>(new Mock<ISpriteBatch>().Object, new Mock<IPrimitivesService>().Object) { CallBase = true }; Gestures = new Subject<Gesture>(); InputManager = new Mock<IInputManager>(); InputManager.SetupGet(inputManager => inputManager.Gestures).Returns(Gestures); RootElement = new Mock<RootElement>(ViewPort, Renderer.Object, InputManager.Object) { CallBase = true }; ScrollViewer = new ScrollViewer(); RootElement.Object.Content = ScrollViewer; }; } [Subject(typeof(ScrollViewer), "Content")] public class when_content_is_set_to_a_control_that_doesnt_implement_IScrollInfo : a_ScrollViewer { private static Mock<IElement> content; private Establish context = () => content = new Mock<IElement>(); private Because of = () => ScrollViewer.Content = content.Object; private It should_set_the_content_of_the_ScrollContentPresenter_to_the_control = () => ((ScrollContentPresenter)ScrollViewer.Content).Content.ShouldBeTheSameAs(content.Object); private It should_use_a_ScrollContentPresenter = () => ScrollViewer.Content.ShouldBeOfType<ScrollContentPresenter>(); } [Subject(typeof(ScrollViewer), "Mouse Capture")] public class when_a_left_mouse_button_down_gesture_is_received : a_ScrollViewer { private Establish context = () => RootElement.Object.Update(); private Because of = () => Gestures.OnNext(new Gesture(GestureType.LeftButtonDown, new Point(), new Vector())); private It should_capture_the_mouse = () => ScrollViewer.IsMouseCaptured.ShouldBeTrue(); } [Subject(typeof(ScrollViewer), "Mouse Capture")] public class when_a_mouse_button_gesture_is_received_the_mouse_is_captured : a_ScrollViewer { private Establish context = () => { ScrollViewer.CaptureMouse(); RootElement.Object.Update(); }; private Because of = () => Gestures.OnNext(new Gesture(GestureType.LeftButtonUp, new Point(), new Vector())); private It should_release_mouse_capture = () => ScrollViewer.IsMouseCaptured.ShouldBeFalse(); } [Subject(typeof(ScrollViewer), "Scrolling")] public class when_horizontal_and_vertical_scrolling_is_enabled : a_ScrollViewer { private static Mock<UIElement> content; private Establish context = () => { content = new Mock<UIElement> { CallBase = true }; content.Object.Width = 200; content.Object.Height = 200; ScrollViewer.Content = content.Object; }; private Because of = () => RootElement.Object.Update(); private It should_allow_the_contents_height_to_exceed_the_height_of_the_viewport = () => ScrollViewer.Extent.Height.ShouldBeGreaterThan(ScrollViewer.Viewport.Height); private It should_allow_the_contents_width_to_exceed_the_width_of_the_viewport = () => ScrollViewer.Extent.Width.ShouldBeGreaterThan(ScrollViewer.Viewport.Width); } [Subject(typeof(ScrollViewer), "Scrolling")] public class when_horizontal_and_vertical_scrolling_is_disabled : a_ScrollViewer { private static Mock<UIElement> content; private Establish context = () => { content = new Mock<UIElement> { CallBase = true }; content.Object.Width = 200; content.Object.Height = 200; ScrollViewer.Content = content.Object; }; private Because of = () => { ScrollViewer.CanHorizontallyScroll = false; ScrollViewer.CanVerticallyScroll = false; RootElement.Object.Update(); }; private It should_constrain_the_contents_height_to_be_less_than_or_equal_to_the_height_of_the_viewport = () => ScrollViewer.Extent.Height.ShouldBeLessThanOrEqualTo(ScrollViewer.Viewport.Height); private It should_constrain_the_contents_width_to_be_less_than_or_equal_to_the_width_of_the_viewport = () => ScrollViewer.Extent.Width.ShouldBeLessThanOrEqualTo(ScrollViewer.Viewport.Width); } [Subject(typeof(ScrollViewer), "Scrolling")] public class when_free_drag_gestures_are_received : a_ScrollViewer { private static readonly Size extent = new Size(200, 200); private static readonly Size viewport = new Size(100, 100); private static Mock<ScrollContentPresenter> scrollInfo; private Establish context = () => { scrollInfo = new Mock<ScrollContentPresenter> { CallBase = true }; ScrollViewer.Content = scrollInfo.Object; RootElement.Object.Update(); }; private Because of = () => { ScrollViewer.CaptureMouse(); Gestures.OnNext(new Gesture(GestureType.FreeDrag, new Point(), new Vector(-20, -30))); Gestures.OnNext(new Gesture(GestureType.FreeDrag, new Point(), new Vector(-5, 3))); }; private It should_the_scroll_content_horizontally = () => scrollInfo.Object.Offset.X.ShouldEqual(25); private It should_the_scroll_content_vertically = () => scrollInfo.Object.Offset.Y.ShouldEqual(27); } }
// 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.14.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.Azure.AcceptanceTestsSubscriptionIdApiVersion { 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> /// GroupOperations operations. /// </summary> internal partial class GroupOperations : IServiceOperations<MicrosoftAzureTestUrl>, IGroupOperations { /// <summary> /// Initializes a new instance of the GroupOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal GroupOperations(MicrosoftAzureTestUrl client) { if (client == null) { throw new ArgumentNullException("client"); } this.Client = client; } /// <summary> /// Gets a reference to the MicrosoftAzureTestUrl /// </summary> public MicrosoftAzureTestUrl Client { get; private set; } /// <summary> /// Provides a resouce group with name 'testgroup101' and location 'West US'. /// </summary> /// <param name='resourceGroupName'> /// Resource Group name 'testgroup101'. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse<SampleResourceGroup>> GetSampleResourceGroupWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (this.Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (this.Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // 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("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetSampleResourceGroup", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}").ToString(); _url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId)); _url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName)); 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(); _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers _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); } } // 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(); HttpResponseMessage _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { string _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = _httpRequest; ex.Response = _httpResponse; if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } throw ex; } // Create Result var _result = new AzureOperationResponse<SampleResourceGroup>(); _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) { try { string _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); _result.Body = SafeJsonConvert.DeserializeObject<SampleResourceGroup>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { throw new RestException("Unable to deserialize the response.", ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
//----------------------------------------------------------------------- // <copyright company="nBuildKit"> // Copyright (c) nBuildKit. All rights reserved. // Licensed under the Apache License, Version 2.0 license. See LICENCE.md file in the project root for full license information. // </copyright> //----------------------------------------------------------------------- using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Text; using Microsoft.Build.Framework; using Microsoft.Build.Utilities; using NBuildKit.MsBuild.Tasks.Core; namespace NBuildKit.MsBuild.Tasks.Script { /// <summary> /// Defines a <see cref="ITask"/> that executes steps for nBuildKit. /// </summary> public sealed class InvokeSteps : BaseTask { private const string ErrorIdInvalidConfiguration = "NBuildKit.Steps.InvalidConfiguration"; private const string ErrorIdInvalidDependencies = "NBuildKit.Steps.InvalidDependencies"; private const string ErrorIdPostStepFailure = "NBuildKit.Steps.PostStep"; private const string ErrorIdPreStepFailure = "NBuildKit.Steps.PreStep"; private const string ErrorIdStepFailure = "NBuildKit.Steps.Failure"; private const string StepMetadataDescription = "StepDescription"; private const string StepMetadataId = "StepId"; private const string StepMetadataName = "StepName"; private const string StepMetadataPath = "StepPath"; private static Hashtable GetStepMetadata(string stepPath, ITaskItem[] metadata, bool isFirst, bool isLast) { const string MetadataTagDescription = "Description"; const string MetadataTagId = "Id"; const string MetadataTagName = "Name"; var stepFileName = Path.GetFileName(stepPath); var stepMetadata = metadata.FirstOrDefault(t => string.Equals(stepFileName, t.ItemSpec, StringComparison.OrdinalIgnoreCase)); var result = new Hashtable(StringComparer.OrdinalIgnoreCase); var description = stepMetadata != null ? stepMetadata.GetMetadata(MetadataTagDescription) : string.Empty; result.Add(StepMetadataDescription, description); var id = (stepMetadata != null) && !string.IsNullOrEmpty(stepMetadata.GetMetadata(MetadataTagId)) ? stepMetadata.GetMetadata(MetadataTagId) : stepFileName; result.Add(StepMetadataId, id); var name = (stepMetadata != null) && !string.IsNullOrEmpty(stepMetadata.GetMetadata(MetadataTagName)) ? stepMetadata.GetMetadata(MetadataTagName) : stepFileName; result.Add(StepMetadataName, name); result.Add(StepMetadataPath, stepPath); result.Add("IsFirstStep", isFirst.ToString().ToLower(CultureInfo.InvariantCulture)); result.Add("IsLastStep", isLast.ToString().ToLower(CultureInfo.InvariantCulture)); return result; } private static StepId[] ExecuteAfter(ITaskItem step) { const string MetadataTag = "ExecuteAfter"; var idsText = (step != null) && !string.IsNullOrEmpty(step.GetMetadata(MetadataTag)) ? step.GetMetadata(MetadataTag) : string.Empty; var ids = idsText.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries); return ids.Select(id => new StepId(id)).ToArray(); } private static StepId[] ExecuteBefore(ITaskItem step) { const string MetadataTag = "ExecuteBefore"; var idsText = (step != null) && !string.IsNullOrEmpty(step.GetMetadata(MetadataTag)) ? step.GetMetadata(MetadataTag) : string.Empty; var ids = idsText.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries); return ids.Select(id => new StepId(id)).ToArray(); } private static ITaskItem[] LocalPreSteps(ITaskItem step) { const string MetadataTag = "PreSteps"; var steps = step.GetMetadata(MetadataTag); return steps.Split(';').Select(s => new TaskItem(s)).ToArray(); } private static ITaskItem[] LocalPostSteps(ITaskItem step) { const string MetadataTag = "PostSteps"; var steps = step.GetMetadata(MetadataTag); return steps.Split(';').Select(s => new TaskItem(s)).ToArray(); } private static IEnumerable<string> StepGroups(ITaskItem step) { const string MetadataTag = "Groups"; var groups = step.GetMetadata(MetadataTag); return groups.ToLower(CultureInfo.InvariantCulture).Split(';'); } private static StepId StepId(ITaskItem step) { const string MetadataTagId = "Id"; var id = (step != null) && !string.IsNullOrEmpty(step.GetMetadata(MetadataTagId)) ? step.GetMetadata(MetadataTagId) : step.ItemSpec; return new StepId(id); } private void AddStepMetadata(ITaskItem subStep, string stepPath, ITaskItem[] metadata, bool isFirst, bool isLast) { const string MetadataTag = "Properties"; var stepMetadata = GetStepMetadata(stepPath, metadata, isFirst, isLast); var stepProperties = subStep.GetMetadata(MetadataTag); if (!string.IsNullOrEmpty(stepProperties)) { Hashtable additionalProjectPropertiesTable = null; if (!PropertyParser.GetTableWithEscaping(Log, "AdditionalProperties", "AdditionalProperties", stepProperties.Split(';'), out additionalProjectPropertiesTable)) { // Ignore it ... } foreach (DictionaryEntry entry in additionalProjectPropertiesTable) { if (!stepMetadata.ContainsKey(entry.Key)) { stepMetadata.Add(entry.Key, entry.Value); } } } // Turn the hashtable into a properties string again. var builder = new StringBuilder(); foreach (DictionaryEntry entry in stepMetadata) { builder.Append( string.Format( CultureInfo.InvariantCulture, "{0}={1};", entry.Key, EscapingUtilities.UnescapeAll(entry.Value as string))); } subStep.SetMetadata(MetadataTag, builder.ToString()); } /// <inheritdoc/> [SuppressMessage( "Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Catching, logging and letting MsBuild deal with the fall out")] public override bool Execute() { if ((Projects == null) || (Projects.Length == 0)) { return true; } // Get groups and determine which steps should be executed var hasFailed = false; var groups = Groups().Select(s => s.ToLower(CultureInfo.InvariantCulture).Trim()); var stepsToExecute = new List<ITaskItem>(); foreach (var step in Projects) { var stepGroups = StepGroups(step); if (!ShouldExecuteStep(groups, stepGroups)) { Log.LogMessage( MessageImportance.Low, "Step {0} has tags {1} none of which are included in execution list of {2}.", step.ItemSpec, string.Join(", ", stepGroups), string.Join(", ", groups)); continue; } stepsToExecute.Add(step); } var orderedStepsToExecute = OrderSteps(stepsToExecute); if (orderedStepsToExecute == null) { return false; } Log.LogMessage( MessageImportance.Normal, "Executing steps in the following order: "); for (int i = 0; i < orderedStepsToExecute.Count; i++) { var step = orderedStepsToExecute[i]; var metadata = GetStepMetadata(step.ItemSpec, StepMetadata, false, false); Log.LogMessage( MessageImportance.Normal, "{0} - {1}: {2}", i, metadata.ContainsKey(StepMetadataName) ? ((string)metadata[StepMetadataName]).Trim() : step.ItemSpec, metadata.ContainsKey(StepMetadataDescription) ? ((string)metadata[StepMetadataDescription]).Trim() : string.Empty); } for (int i = 0; i < orderedStepsToExecute.Count; i++) { var step = orderedStepsToExecute[i]; try { if (!ExecuteStep(step, i == 0, i == orderedStepsToExecute.Count - 1)) { hasFailed = true; if (StopOnFirstFailure) { break; } } } catch (Exception e) { hasFailed = true; Log.LogError( string.Empty, ErrorCodeById(ErrorIdStepFailure), ErrorIdStepFailure, string.Empty, 0, 0, 0, 0, "Execution of steps failed with exception. Exception was: {0}", e); } } if (Log.HasLoggedErrors || hasFailed) { if (FailureSteps != null) { var failureStepsToExecute = new List<ITaskItem>(); foreach (var step in FailureSteps) { if (!string.IsNullOrEmpty(step.ItemSpec)) { var stepGroups = StepGroups(step); if (!ShouldExecuteStep(groups, stepGroups)) { Log.LogMessage( MessageImportance.Low, "Step {0} has tags {1} none of which are included in execution list of {2}.", step.ItemSpec, string.Join(", ", stepGroups), string.Join(", ", groups)); continue; } failureStepsToExecute.Add(step); } } for (int i = 0; i < failureStepsToExecute.Count; i++) { var step = failureStepsToExecute[i]; if (!ExecuteFailureStep(step)) { if (StopOnFirstFailure) { break; } } } } } return !Log.HasLoggedErrors && !hasFailed; } private bool ExecuteFailureStep(ITaskItem step) { var result = InvokeBuildEngine(step); if (!result && StopOnFirstFailure) { return false; } return true; } private bool ExecuteStep(ITaskItem step, bool isFirst, bool isLast) { var stepResult = true; var stepPath = GetAbsolutePath(step.ItemSpec); if (PreSteps != null) { foreach (var globalPreStep in PreSteps) { if (!string.IsNullOrEmpty(globalPreStep.ItemSpec)) { AddStepMetadata(globalPreStep, stepPath, StepMetadata, isFirst, isLast); var result = InvokeBuildEngine(globalPreStep); if (!result) { if (FailOnPreStepFailure) { stepResult = false; Log.LogError( string.Empty, ErrorCodeById(ErrorIdPreStepFailure), ErrorIdPreStepFailure, string.Empty, 0, 0, 0, 0, "Failed while executing global pre-step action from '{0}'", globalPreStep.ItemSpec); } else { Log.LogWarning( "Failed while executing global pre-step action from '{0}'", globalPreStep.ItemSpec); } if (StopOnPreStepFailure) { return false; } } } } } var localPreSteps = LocalPreSteps(step); if (localPreSteps != null) { foreach (var localPreStep in localPreSteps) { if (!string.IsNullOrEmpty(localPreStep.ItemSpec)) { AddStepMetadata(localPreStep, stepPath, StepMetadata, isFirst, isLast); var result = InvokeBuildEngine(localPreStep); if (!result) { if (FailOnPreStepFailure) { stepResult = false; Log.LogError( string.Empty, ErrorCodeById(ErrorIdPreStepFailure), ErrorIdPreStepFailure, string.Empty, 0, 0, 0, 0, "Failed while executing step specific pre-step action from '{0}'", localPreStep.ItemSpec); } else { Log.LogWarning( "Failed while executing step specific pre-step action from '{0}'", localPreStep.ItemSpec); } if (StopOnPreStepFailure) { return false; } } } } } // Get the result but always try to excecute the post-step actions var localStepResult = InvokeBuildEngine(step); stepResult = stepResult && localStepResult; var localPostSteps = LocalPostSteps(step); if (localPostSteps != null) { foreach (var localPostStep in localPostSteps) { if (!string.IsNullOrEmpty(localPostStep.ItemSpec)) { AddStepMetadata(localPostStep, stepPath, StepMetadata, isFirst, isLast || !stepResult); var result = InvokeBuildEngine(localPostStep); if (!result) { if (FailOnPostStepFailure) { stepResult = false; Log.LogError( string.Empty, ErrorCodeById(ErrorIdPostStepFailure), ErrorIdPostStepFailure, string.Empty, 0, 0, 0, 0, "Failed while executing step specific post-step action from '{0}'", localPostStep.ItemSpec); } else { Log.LogWarning( "Failed while executing step specific post-step action from '{0}'", localPostStep.ItemSpec); } if (StopOnPostStepFailure) { return false; } } } } } if (PostSteps != null) { foreach (var globalPostStep in PostSteps) { if (!string.IsNullOrEmpty(globalPostStep.ItemSpec)) { AddStepMetadata(globalPostStep, stepPath, StepMetadata, isFirst, isLast || !stepResult); var result = InvokeBuildEngine(globalPostStep); if (!result && StopOnFirstFailure) { if (FailOnPostStepFailure) { stepResult = false; Log.LogError( string.Empty, ErrorCodeById(ErrorIdPostStepFailure), ErrorIdPostStepFailure, string.Empty, 0, 0, 0, 0, "Failed while executing global post-step action from '{0}'", globalPostStep.ItemSpec); } else { Log.LogWarning( "Failed while executing global post-step action from '{0}'", globalPostStep.ItemSpec); } if (StopOnPostStepFailure) { stepResult = false; } } } } } return stepResult; } /// <summary> /// Gets or sets a value indicating whether the process should fail if a post-step fails. /// </summary> public bool FailOnPostStepFailure { get; set; } /// <summary> /// Gets or sets a value indicating whether the process should fail if a pre-step fails. /// </summary> public bool FailOnPreStepFailure { get; set; } /// <summary> /// Gets or sets the steps that should be taken if a step fails. /// </summary> public ITaskItem[] FailureSteps { get; set; } private IEnumerable<string> Groups() { return GroupsToExecute.Select(t => t.ItemSpec).ToList(); } /// <summary> /// Gets or sets the collection of tags that mark which steps should be executed. If no groups are specified /// it is assumed that all valid steps should be executed. /// </summary> public ITaskItem[] GroupsToExecute { get; set; } private bool InvokeBuildEngine(ITaskItem project) { Hashtable propertiesTable; if (!PropertyParser.GetTableWithEscaping(Log, "GlobalProperties", "Properties", Properties.Select(t => t.ItemSpec).ToArray(), out propertiesTable)) { return false; } string projectPath = GetAbsolutePath(project.ItemSpec); if (File.Exists(projectPath)) { var toolsVersion = ToolsVersion; if (project != null) { // If the user specified additional properties then add those var projectProperties = project.GetMetadata("Properties"); if (!string.IsNullOrEmpty(projectProperties)) { Hashtable additionalProjectPropertiesTable; if (!PropertyParser.GetTableWithEscaping(Log, "AdditionalProperties", "AdditionalProperties", projectProperties.Split(';'), out additionalProjectPropertiesTable)) { return false; } var combinedTable = new Hashtable(StringComparer.OrdinalIgnoreCase); // First copy in the properties from the global table that not in the additional properties table if (propertiesTable != null) { foreach (DictionaryEntry entry in propertiesTable) { if (!additionalProjectPropertiesTable.Contains(entry.Key)) { combinedTable.Add(entry.Key, entry.Value); } } } // Add all the additional properties foreach (DictionaryEntry entry in additionalProjectPropertiesTable) { combinedTable.Add(entry.Key, entry.Value); } propertiesTable = combinedTable; } } // Send the project off to the build engine. By passing in null to the // first param, we are indicating that the project to build is the same // as the *calling* project file. BuildEngineResult result = BuildEngine3.BuildProjectFilesInParallel( new[] { projectPath }, null, new IDictionary[] { propertiesTable }, new IList<string>[] { new List<string>() }, new[] { toolsVersion }, false); return result.Result; } else { Log.LogError( string.Empty, ErrorCodeById(Core.ErrorInformation.ErrorIdFileNotFound), Core.ErrorInformation.ErrorIdFileNotFound, string.Empty, 0, 0, 0, 0, "MsBuild script file expected to be at '{0}' but could not be found", projectPath); return false; } } private List<ITaskItem> OrderSteps(IEnumerable<ITaskItem> steps) { var sortedItems = new List<Tuple<StepId, ITaskItem>>(); int IndexOf(StepId id) { return sortedItems.FindIndex(t => t.Item1.Equals(id)); } var unsortedItems = new List<Tuple<StepId, StepId[], StepId[], ITaskItem>>(); foreach (var item in steps) { var id = StepId(item); var executeAfter = ExecuteAfter(item); var executeBefore = ExecuteBefore(item); if ((executeBefore.Length > 0) || (executeAfter.Length > 0)) { unsortedItems.Add(Tuple.Create(id, executeBefore, executeAfter, item)); } else { sortedItems.Add(Tuple.Create(id, item)); } } var lastCount = steps.Count(); while ((unsortedItems.Count > 0) && (lastCount > unsortedItems.Count)) { lastCount = unsortedItems.Count; var toDelete = new List<Tuple<StepId, StepId[], StepId[], ITaskItem>>(); foreach (var unsortedItem in unsortedItems) { var insertBefore = -1; var executeBefore = unsortedItem.Item2; if (executeBefore.Length > 0) { var indices = executeBefore.Select(id => IndexOf(id)).Where(i => i > -1); if (indices.Count() != executeBefore.Length) { continue; } insertBefore = indices.Min(); } var insertAfter = sortedItems.Count; var executeAfter = unsortedItem.Item3; if (executeAfter.Length > 0) { var indices = executeAfter.Select(id => IndexOf(id)).Where(i => i > -1); if (indices.Count() != executeAfter.Length) { continue; } insertAfter = indices.Max(); } if ((executeBefore.Length > 0) && (executeAfter.Length > 0) && (insertBefore < insertAfter)) { Log.LogError( string.Empty, ErrorCodeById(ErrorIdInvalidDependencies), ErrorIdInvalidDependencies, string.Empty, 0, 0, 0, 0, "At least one dependency needs to be inserted both before an earlier item and after a later item. No suitable place for the insertion could be found."); return null; } if (executeBefore.Length > 0) { sortedItems.Insert(insertBefore, Tuple.Create(unsortedItem.Item1, unsortedItem.Item4)); toDelete.Add(unsortedItem); } else { sortedItems.Insert(insertAfter + 1, Tuple.Create(unsortedItem.Item1, unsortedItem.Item4)); toDelete.Add(unsortedItem); } } foreach (var item in toDelete) { unsortedItems.Remove(item); } } if (unsortedItems.Count > 0) { Log.LogMessage( MessageImportance.Normal, "Failed to sort all the steps. The sorted steps were: "); for (int i = 0; i < sortedItems.Count; i++) { var tuple = sortedItems[i]; Log.LogMessage( MessageImportance.Normal, "{0} - {1}", i, tuple.Item1); } Log.LogMessage( MessageImportance.Normal, "The unsorted steps were: "); for (int i = 0; i < unsortedItems.Count; i++) { var tuple = unsortedItems[i]; Log.LogMessage( MessageImportance.Normal, "{0} - {1}", i, tuple.Item1); } Log.LogError( string.Empty, ErrorCodeById(ErrorIdInvalidDependencies), ErrorIdInvalidDependencies, string.Empty, 0, 0, 0, 0, "Was not able to order all the steps."); return null; } return sortedItems.Select(t => t.Item2).ToList(); } /// <summary> /// Gets or sets the steps that should be executed after each step. /// </summary> public ITaskItem[] PostSteps { get; set; } /// <summary> /// Gets or sets the steps that should be executed prior to each step. /// </summary> public ITaskItem[] PreSteps { get; set; } /// <summary> /// Gets or sets the steps that should be taken for the current process. /// </summary> [Required] public ITaskItem[] Projects { get; set; } /// <summary> /// Gets or sets the properties for the steps. /// </summary> public ITaskItem[] Properties { get; set; } [SuppressMessage( "Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Catching, logging and letting MsBuild deal with the fall out")] private bool ShouldExecuteStep(IEnumerable<string> groupsToExecute, IEnumerable<string> stepGroups) { const string AlwaysExecuteGroup = "all"; try { return !groupsToExecute.Any() || groupsToExecute.Contains(AlwaysExecuteGroup) || (groupsToExecute.Any() && groupsToExecute.Intersect(stepGroups).Any()); } catch (Exception e) { Log.LogError( string.Empty, ErrorCodeById(ErrorIdInvalidConfiguration), ErrorIdInvalidConfiguration, string.Empty, 0, 0, 0, 0, "Failed to determine if the collection contains any of the items. Error was: {0}", e); return false; } } /// <summary> /// Gets or sets the collection containing the metadata describing the different steps. /// </summary> [Required] public ITaskItem[] StepMetadata { get; set; } /// <summary> /// Gets or sets a value indicating whether or not the process should stop on the first error or continue. /// Default is false. /// </summary> public bool StopOnFirstFailure { get; set; } /// <summary> /// Gets or sets a value indicating whether the process should stop if a pre-step fails. /// </summary> public bool StopOnPreStepFailure { get; set; } /// <summary> /// Gets or sets a value indicating whether the process should stop if a post-step fails. /// </summary> public bool StopOnPostStepFailure { get; set; } /// <summary> /// Gets or sets the version of MsBuild and the build tools that should be used. /// </summary> public string ToolsVersion { get; set; } } }
#region Copyright notice and license // Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // http://github.com/jskeet/dotnet-protobufs/ // Original C++/Java/Python code: // http://code.google.com/p/protobuf/ // // 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 Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endregion using System; using System.Collections; using System.Collections.Generic; using System.IO; using Google.ProtocolBuffers.Descriptors; namespace Google.ProtocolBuffers.ProtoMunge { /// <summary> /// Utility console application which takes a message descriptor and a corresponding message, /// and produces a new message with similar but random data. The data is the same length /// as the original, but with random values within appropriate bands. (For instance, a compressed /// integer in the range 0-127 will end up as another integer in the same range, to keep the length /// the same.) /// TODO(jonskeet): Potentially refactor to use an instance instead, making it simpler to /// be thread-safe for external use. /// </summary> public sealed class Program { private static readonly Random rng = new Random(); private static int Main(string[] args) { if (args.Length != 3) { Console.Error.WriteLine("Usage: ProtoMunge <descriptor type name> <input data> <output file>"); Console.Error.WriteLine( "The descriptor type name is the fully-qualified message name, including assembly."); Console.Error.WriteLine( "(At a future date it may be possible to do this without building the .NET assembly at all.)"); return 1; } IMessage defaultMessage; try { defaultMessage = MessageUtil.GetDefaultMessage(args[0]); } catch (ArgumentException e) { Console.Error.WriteLine(e.Message); return 1; } try { IBuilder builder = defaultMessage.WeakCreateBuilderForType(); byte[] inputData = File.ReadAllBytes(args[1]); builder.WeakMergeFrom(ByteString.CopyFrom(inputData)); IMessage original = builder.WeakBuild(); IMessage munged = Munge(original); if (original.SerializedSize != munged.SerializedSize) { throw new Exception("Serialized sizes don't match"); } File.WriteAllBytes(args[2], munged.ToByteArray()); return 0; } catch (Exception e) { Console.Error.WriteLine("Error: {0}", e.Message); Console.Error.WriteLine(); Console.Error.WriteLine("Detailed exception information: {0}", e); return 1; } } /// <summary> /// Munges a message recursively. /// </summary> /// <returns>A new message of the same type as the original message, /// but munged so that all the data is desensitised.</returns> private static IMessage Munge(IMessage message) { IBuilder builder = message.WeakCreateBuilderForType(); foreach (var pair in message.AllFields) { if (pair.Key.IsRepeated) { foreach (object singleValue in (IEnumerable) pair.Value) { builder.WeakAddRepeatedField(pair.Key, CheckedMungeValue(pair.Key, singleValue)); } } else { builder[pair.Key] = CheckedMungeValue(pair.Key, pair.Value); } } IMessage munged = builder.WeakBuild(); if (message.SerializedSize != munged.SerializedSize) { Console.WriteLine("Sub message sizes: {0}/{1}", message.SerializedSize, munged.SerializedSize); } return munged; } /// <summary> /// Munges a single value and checks that the length ends up the same as it was before. /// </summary> private static object CheckedMungeValue(FieldDescriptor fieldDescriptor, object value) { int currentSize = CodedOutputStream.ComputeFieldSize(fieldDescriptor.FieldType, fieldDescriptor.FieldNumber, value); object mungedValue = MungeValue(fieldDescriptor, value); int mungedSize = CodedOutputStream.ComputeFieldSize(fieldDescriptor.FieldType, fieldDescriptor.FieldNumber, mungedValue); // Exceptions log more easily than assertions if (currentSize != mungedSize) { throw new Exception("Munged value had wrong size. Field type: " + fieldDescriptor.FieldType + "; old value: " + value + "; new value: " + mungedValue); } return mungedValue; } /// <summary> /// Munges a single value of the specified field descriptor. (i.e. if the field is /// actually a repeated int, this method receives a single int value to munge, and /// is called multiple times). /// </summary> private static object MungeValue(FieldDescriptor fieldDescriptor, object value) { switch (fieldDescriptor.FieldType) { case FieldType.SInt64: case FieldType.Int64: return (long) MungeVarint64((ulong) (long) value); case FieldType.UInt64: return MungeVarint64((ulong) value); case FieldType.SInt32: return (int) MungeVarint32((uint) (int) value); case FieldType.Int32: return MungeInt32((int) value); case FieldType.UInt32: return MungeVarint32((uint) value); case FieldType.Double: return rng.NextDouble(); case FieldType.Float: return (float) rng.NextDouble(); case FieldType.Fixed64: { byte[] data = new byte[8]; rng.NextBytes(data); return BitConverter.ToUInt64(data, 0); } case FieldType.Fixed32: { byte[] data = new byte[4]; rng.NextBytes(data); return BitConverter.ToUInt32(data, 0); } case FieldType.Bool: return rng.Next(2) == 1; case FieldType.String: return MungeString((string) value); case FieldType.Group: case FieldType.Message: return Munge((IMessage) value); case FieldType.Bytes: return MungeByteString((ByteString) value); case FieldType.SFixed64: { byte[] data = new byte[8]; rng.NextBytes(data); return BitConverter.ToInt64(data, 0); } case FieldType.SFixed32: { byte[] data = new byte[4]; rng.NextBytes(data); return BitConverter.ToInt32(data, 0); } case FieldType.Enum: return MungeEnum(fieldDescriptor, (EnumValueDescriptor) value); default: // TODO(jonskeet): Different exception? throw new ArgumentException("Invalid field descriptor"); } } private static object MungeString(string original) { foreach (char c in original) { if (c > 127) { throw new ArgumentException("Can't handle non-ascii yet"); } } char[] chars = new char[original.Length]; // Convert to pure ASCII - no control characters. for (int i = 0; i < chars.Length; i++) { chars[i] = (char) rng.Next(32, 127); } return new string(chars); } /// <summary> /// Int32 fields are slightly strange - we need to keep the sign the same way it is: /// negative numbers can munge to any other negative number (it'll always take /// 10 bytes) but positive numbers have to stay positive, so we can't use the /// full range of 32 bits. /// </summary> private static int MungeInt32(int value) { if (value < 0) { return rng.Next(int.MinValue, 0); } int length = CodedOutputStream.ComputeRawVarint32Size((uint) value); uint min = length == 1 ? 0 : 1U << ((length - 1)*7); uint max = length == 5 ? int.MaxValue : (1U << (length*7)) - 1; return (int) NextRandomUInt64(min, max); } private static uint MungeVarint32(uint original) { int length = CodedOutputStream.ComputeRawVarint32Size(original); uint min = length == 1 ? 0 : 1U << ((length - 1)*7); uint max = length == 5 ? uint.MaxValue : (1U << (length*7)) - 1; return (uint) NextRandomUInt64(min, max); } private static ulong MungeVarint64(ulong original) { int length = CodedOutputStream.ComputeRawVarint64Size(original); ulong min = length == 1 ? 0 : 1UL << ((length - 1)*7); ulong max = length == 10 ? ulong.MaxValue : (1UL << (length*7)) - 1; return NextRandomUInt64(min, max); } /// <summary> /// Returns a random number in the range [min, max] (both inclusive). /// </summary> private static ulong NextRandomUInt64(ulong min, ulong max) { if (min > max) { throw new ArgumentException("min must be <= max; min=" + min + "; max = " + max); } ulong range = max - min; // This isn't actually terribly good at very large ranges - but it doesn't really matter for the sake // of this program. return min + (ulong) (range*rng.NextDouble()); } private static object MungeEnum(FieldDescriptor fieldDescriptor, EnumValueDescriptor original) { // Find all the values which get encoded to the same size as the current value, and pick one at random int originalSize = CodedOutputStream.ComputeRawVarint32Size((uint) original.Number); List<EnumValueDescriptor> sameSizeValues = new List<EnumValueDescriptor>(); foreach (EnumValueDescriptor candidate in fieldDescriptor.EnumType.Values) { if (CodedOutputStream.ComputeRawVarint32Size((uint) candidate.Number) == originalSize) { sameSizeValues.Add(candidate); } } return sameSizeValues[rng.Next(sameSizeValues.Count)]; } private static object MungeByteString(ByteString byteString) { byte[] data = new byte[byteString.Length]; rng.NextBytes(data); return ByteString.CopyFrom(data); } } }
using System; using System.Diagnostics; using System.Text; using Bitmask = System.UInt64; using u8 = System.Byte; using u16 = System.UInt16; using u32 = System.UInt32; namespace System.Data.SQLite { using sqlite3_int64 = System.Int64; using MemJournal = Sqlite3.sqlite3_file; public partial class Sqlite3 { /* ** 2007 August 22 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** ** This file contains code use to implement an in-memory rollback journal. ** The in-memory rollback journal is used to journal transactions for ** ":memory:" databases and when the journal_mode=MEMORY pragma is used. ************************************************************************* ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart ** C#-SQLite is an independent reimplementation of the SQLite software library ** ** SQLITE_SOURCE_ID: 2010-12-07 20:14:09 a586a4deeb25330037a49df295b36aaf624d0f45 ** ************************************************************************* */ //#include "sqliteInt.h" /* Forward references to internal structures */ //typedef struct MemJournal MemJournal; //typedef struct FilePoint FilePoint; //typedef struct FileChunk FileChunk; /* Space to hold the rollback journal is allocated in increments of ** this many bytes. ** ** The size chosen is a little less than a power of two. That way, ** the FileChunk object will have a size that almost exactly fills ** a power-of-two allocation. This mimimizes wasted space in power-of-two ** memory allocators. */ //#define JOURNAL_CHUNKSIZE ((int)(1024-sizeof(FileChunk*))) const int JOURNAL_CHUNKSIZE = 4096; /* Macro to find the minimum of two numeric values. */ //#if !MIN //# define MIN(x,y) ((x)<(y)?(x):(y)) //#endif static int MIN(int x, int y) { return (x < y) ? x : y; } static int MIN(int x, u32 y) { return (x < y) ? x : (int)y; } /* ** The rollback journal is composed of a linked list of these structures. */ public class FileChunk { public FileChunk pNext; /* Next chunk in the journal */ public byte[] zChunk = new byte[JOURNAL_CHUNKSIZE]; /* Content of this chunk */ }; /* ** An instance of this object serves as a cursor into the rollback journal. ** The cursor can be either for reading or writing. */ public class FilePoint { public long iOffset; /* Offset from the beginning of the file */ public FileChunk pChunk; /* Specific chunk into which cursor points */ }; /* ** This subclass is a subclass of sqlite3_file. Each open memory-journal ** is an instance of this class. */ public partial class sqlite3_file { //public sqlite3_io_methods pMethods; /* Parent class. MUST BE FIRST */ public FileChunk pFirst; /* Head of in-memory chunk-list */ public FilePoint endpoint; /* Pointer to the end of the file */ public FilePoint readpoint; /* Pointer to the end of the last xRead() */ }; /* ** Read data from the in-memory journal file. This is the implementation ** of the sqlite3_vfs.xRead method. */ static int memjrnlRead( sqlite3_file pJfd, /* The journal file from which to read */ byte[] zBuf, /* Put the results here */ int iAmt, /* Number of bytes to read */ sqlite3_int64 iOfst /* Begin reading at this offset */ ) { MemJournal p = (MemJournal)pJfd; byte[] zOut = zBuf; int nRead = iAmt; int iChunkOffset; FileChunk pChunk; /* SQLite never tries to read past the end of a rollback journal file */ Debug.Assert(iOfst + iAmt <= p.endpoint.iOffset); if (p.readpoint.iOffset != iOfst || iOfst == 0) { int iOff = 0; for (pChunk = p.pFirst; ALWAYS(pChunk != null) && (iOff + JOURNAL_CHUNKSIZE) <= iOfst; pChunk = pChunk.pNext ) { iOff += JOURNAL_CHUNKSIZE; } } else { pChunk = p.readpoint.pChunk; } iChunkOffset = (int)(iOfst % JOURNAL_CHUNKSIZE); int izOut = 0; do { int iSpace = JOURNAL_CHUNKSIZE - iChunkOffset; int nCopy = MIN(nRead, (JOURNAL_CHUNKSIZE - iChunkOffset)); Buffer.BlockCopy(pChunk.zChunk, iChunkOffset, zOut, izOut, nCopy); //memcpy( zOut, pChunk.zChunk[iChunkOffset], nCopy ); izOut += nCopy;// zOut += nCopy; nRead -= iSpace; iChunkOffset = 0; } while (nRead >= 0 && (pChunk = pChunk.pNext) != null && nRead > 0); p.readpoint.iOffset = (int)(iOfst + iAmt); p.readpoint.pChunk = pChunk; return SQLITE_OK; } /* ** Write data to the file. */ static int memjrnlWrite( sqlite3_file pJfd, /* The journal file into which to write */ byte[] zBuf, /* Take data to be written from here */ int iAmt, /* Number of bytes to write */ sqlite3_int64 iOfst /* Begin writing at this offset into the file */ ) { MemJournal p = (MemJournal)pJfd; int nWrite = iAmt; byte[] zWrite = zBuf; int izWrite = 0; /* An in-memory journal file should only ever be appended to. Random ** access writes are not required by sqlite. */ Debug.Assert(iOfst == p.endpoint.iOffset); UNUSED_PARAMETER(iOfst); while (nWrite > 0) { FileChunk pChunk = p.endpoint.pChunk; int iChunkOffset = (int)(p.endpoint.iOffset % JOURNAL_CHUNKSIZE); int iSpace = MIN(nWrite, JOURNAL_CHUNKSIZE - iChunkOffset); if (iChunkOffset == 0) { /* New chunk is required to extend the file. */ FileChunk pNew = new FileChunk();// sqlite3_malloc( sizeof( FileChunk ) ); if (null == pNew) { return SQLITE_IOERR_NOMEM; } pNew.pNext = null; if (pChunk != null) { Debug.Assert(p.pFirst != null); pChunk.pNext = pNew; } else { Debug.Assert(null == p.pFirst); p.pFirst = pNew; } p.endpoint.pChunk = pNew; } Buffer.BlockCopy(zWrite, izWrite, p.endpoint.pChunk.zChunk, iChunkOffset, iSpace); //memcpy( &p.endpoint.pChunk.zChunk[iChunkOffset], zWrite, iSpace ); izWrite += iSpace;//zWrite += iSpace; nWrite -= iSpace; p.endpoint.iOffset += iSpace; } return SQLITE_OK; } /* ** Truncate the file. */ static int memjrnlTruncate(sqlite3_file pJfd, sqlite3_int64 size) { MemJournal p = (MemJournal)pJfd; FileChunk pChunk; Debug.Assert(size == 0); UNUSED_PARAMETER(size); pChunk = p.pFirst; while (pChunk != null) { FileChunk pTmp = pChunk; pChunk = pChunk.pNext; //sqlite3_free( ref pTmp ); } sqlite3MemJournalOpen(pJfd); return SQLITE_OK; } /* ** Close the file. */ static int memjrnlClose(MemJournal pJfd) { memjrnlTruncate(pJfd, 0); return SQLITE_OK; } /* ** Sync the file. ** ** Syncing an in-memory journal is a no-op. And, in fact, this routine ** is never called in a working implementation. This implementation ** exists purely as a contingency, in case some malfunction in some other ** part of SQLite causes Sync to be called by mistake. */ static int memjrnlSync(sqlite3_file NotUsed, int NotUsed2) { UNUSED_PARAMETER2(NotUsed, NotUsed2); return SQLITE_OK; } /* ** Query the size of the file in bytes. */ static int memjrnlFileSize(sqlite3_file pJfd, ref long pSize) { MemJournal p = (MemJournal)pJfd; pSize = p.endpoint.iOffset; return SQLITE_OK; } /* ** Table of methods for MemJournal sqlite3_file object. */ static sqlite3_io_methods MemJournalMethods = new sqlite3_io_methods( 1, /* iVersion */ (dxClose)memjrnlClose, /* xClose */ (dxRead)memjrnlRead, /* xRead */ (dxWrite)memjrnlWrite, /* xWrite */ (dxTruncate)memjrnlTruncate, /* xTruncate */ (dxSync)memjrnlSync, /* xSync */ (dxFileSize)memjrnlFileSize, /* xFileSize */ null, /* xLock */ null, /* xUnlock */ null, /* xCheckReservedLock */ null, /* xFileControl */ null, /* xSectorSize */ null, /* xDeviceCharacteristics */ null, /* xShmMap */ null, /* xShmLock */ null, /* xShmBarrier */ null /* xShmUnlock */ ); /* ** Open a journal file. */ static void sqlite3MemJournalOpen(sqlite3_file pJfd) { MemJournal p = (MemJournal)pJfd; //memset( p, 0, sqlite3MemJournalSize() ); p.pFirst = null; p.endpoint = new FilePoint(); p.readpoint = new FilePoint(); p.pMethods = MemJournalMethods;//(sqlite3_io_methods*)&MemJournalMethods; } /* ** Return true if the file-handle passed as an argument is ** an in-memory journal */ static bool sqlite3IsMemJournal(sqlite3_file pJfd) { return pJfd.pMethods == MemJournalMethods; } /* ** Return the number of bytes required to store a MemJournal file descriptor. */ static int sqlite3MemJournalSize() { return 3096; // sizeof( MemJournal ); } } }
using System; using System.Xml; using System.Diagnostics; using System.Drawing; using System.Drawing.Drawing2D; using SharpVectors.Dom.Events; namespace SharpVectors.Dom.Svg { /// <summary> /// The SVGRectElement interface corresponds to the 'rect' element. /// </summary> /// <developer>[email protected]</developer> /// <completed>100</completed> public class SvgRectElement : SvgTransformableElement , ISharpGDIPath , ISvgRectElement , IGraphicsElement { #region Constructors internal SvgRectElement(string prefix, string localname, string ns, SvgDocument doc) : base(prefix, localname, ns, doc) { svgExternalResourcesRequired = new SvgExternalResourcesRequired(this); svgTests = new SvgTests(this); } #endregion #region Implementation of ISvgExternalResourcesRequired private SvgExternalResourcesRequired svgExternalResourcesRequired; public ISvgAnimatedBoolean ExternalResourcesRequired { get { return svgExternalResourcesRequired.ExternalResourcesRequired; } } #endregion #region Implementation of ISvgRectElement private ISvgAnimatedLength width; public ISvgAnimatedLength Width { get { if(width == null) { width = new SvgAnimatedLength(this, "width", SvgLengthDirection.Horizontal, "100"); } return width; } } private ISvgAnimatedLength height; public ISvgAnimatedLength Height { get { if(height == null) { height = new SvgAnimatedLength(this, "height", SvgLengthDirection.Vertical, "100"); } return height; } } private ISvgAnimatedLength x; public ISvgAnimatedLength X { get { if(x == null) { x = new SvgAnimatedLength(this, "x", SvgLengthDirection.Horizontal, "0"); } return x; } } private ISvgAnimatedLength y; public ISvgAnimatedLength Y { get { if(y == null) { y = new SvgAnimatedLength(this, "y", SvgLengthDirection.Vertical, "0"); } return y; } } private ISvgAnimatedLength rx; public ISvgAnimatedLength Rx { get { if(rx == null) { rx = new SvgAnimatedLength(this, "rx", SvgLengthDirection.Horizontal, "0"); } return rx; } } private ISvgAnimatedLength ry; public ISvgAnimatedLength Ry { get { if(ry == null) { ry = new SvgAnimatedLength(this, "ry", SvgLengthDirection.Vertical, "0"); } return ry; } } #endregion #region Implementation of ISharpGDIPath public void Invalidate() { gp = null; renderingNode = null; } private void addRoundedRect(GraphicsPath graphicsPath, RectangleF rect, float rx, float ry) { if(rx == 0F) rx = ry; else if(ry == 0F) ry = rx; rx = Math.Min(rect.Width/2, rx); ry = Math.Min(rect.Height/2, ry); float a = rect.X + rect.Width - rx; graphicsPath.AddLine(rect.X + rx, rect.Y, a, rect.Y); graphicsPath.AddArc(a-rx, rect.Y, rx*2, ry*2, 270, 90); float right = rect.X + rect.Width; // rightmost X float b = rect.Y + rect.Height - ry; graphicsPath.AddLine(right, rect.Y + ry, right, b); graphicsPath.AddArc(right - rx*2, b-ry, rx*2, ry*2, 0, 90); graphicsPath.AddLine(right - rx, rect.Y + rect.Height, rect.X + rx, rect.Y + rect.Height); graphicsPath.AddArc(rect.X, b-ry, rx*2, ry*2, 90, 90); graphicsPath.AddLine(rect.X, b, rect.X, rect.Y + ry); graphicsPath.AddArc(rect.X, rect.Y, rx*2, ry*2, 180, 90); } private GraphicsPath gp = null; public GraphicsPath GetGraphicsPath() { if(gp == null) { gp = new GraphicsPath(); RectangleF rect = new RectangleF((float)X.AnimVal.Value, (float)Y.AnimVal.Value, (float)Width.AnimVal.Value, (float)Height.AnimVal.Value); float rx = (float)Rx.AnimVal.Value; float ry = (float)Ry.AnimVal.Value; if(rx == 0F && ry == 0F) { gp.AddRectangle(rect); } else { addRoundedRect(gp, rect, rx, ry); } } return gp; } #endregion #region Implementation of ISvgTests private SvgTests svgTests; public ISvgStringList RequiredFeatures { get { return svgTests.RequiredFeatures; } } public ISvgStringList RequiredExtensions { get { return svgTests.RequiredExtensions; } } public ISvgStringList SystemLanguage { get { return svgTests.SystemLanguage; } } public bool HasExtension(string extension) { return svgTests.HasExtension(extension); } #endregion #region Update handling public override void HandleAttributeChange(XmlAttribute attribute) { if(attribute.NamespaceURI.Length == 0) { switch(attribute.LocalName) { case "x": x = null; Invalidate(); return; case "y": y = null; Invalidate(); return; case "width": width = null; Invalidate(); return; case "height": height = null; Invalidate(); return; case "rx": rx = null; Invalidate(); return; case "ry": ry = null; Invalidate(); return; // Color.attrib, Paint.attrib case "color": case "fill": case "fill-rule": case "stroke": case "stroke-dasharray": case "stroke-dashoffset": case "stroke-linecap": case "stroke-linejoin": case "stroke-miterlimit": case "stroke-width": // Opacity.attrib case "opacity": case "stroke-opacity": case "fill-opacity": // Graphics.attrib case "display": case "image-rendering": case "shape-rendering": case "text-rendering": case "visibility": Invalidate(); break; case "transform": Invalidate(); break; case "onclick": break; } base.HandleAttributeChange(attribute); } } #endregion } }