context
stringlengths
2.52k
185k
gt
stringclasses
1 value
using JabbR.Commands; using JabbR.ContentProviders.Core; using JabbR.Infrastructure; using JabbR.Models; using JabbR.Services; using JabbR.ViewModels; using Microsoft.AspNet.SignalR; using Microsoft.AspNet.SignalR.Messaging; using Microsoft.Data.Edm.Validation; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace JabbR { [AuthorizeClaim(JabbRClaimTypes.Identifier)] public class Chat : Hub, INotificationService { private static readonly TimeSpan _disconnectThreshold = TimeSpan.FromSeconds(10); private readonly IJabbrRepository _repository; private readonly IChatService _service; private readonly IRecentMessageCache _recentMessageCache; private readonly ICache _cache; private readonly ContentProviderProcessor _resourceProcessor; private readonly PushNotificationService _pushNotification; private readonly ILogger _logger; private readonly ApplicationSettings _settings; public Chat(ContentProviderProcessor resourceProcessor, PushNotificationService pushNotification, IChatService service, IRecentMessageCache recentMessageCache, IJabbrRepository repository, ICache cache, ILogger logger, ApplicationSettings settings) { _resourceProcessor = resourceProcessor; _pushNotification = pushNotification; _service = service; _recentMessageCache = recentMessageCache; _repository = repository; _cache = cache; _logger = logger; _settings = settings; } private string UserAgent { get { if (Context.Headers != null) { return Context.Headers["User-Agent"]; } return null; } } private bool OutOfSync { get { string version = Context.QueryString["version"]; if (String.IsNullOrEmpty(version)) { return true; } return new Version(version) != Constants.JabbRVersion; } } public override Task OnConnected() { _logger.Log("OnConnected({0})", Context.ConnectionId); CheckStatus(); return base.OnConnected(); } public void Join() { Join(reconnecting: false); } public void Join(bool reconnecting) { // Get the client state var userId = Context.User.GetUserId(); // Try to get the user from the client state ChatUser user = _repository.GetUserById(userId); if (reconnecting) { _logger.Log("{0}:{1} connected after dropping connection.", user.Name, Context.ConnectionId); // If the user was marked as offline then mark them inactive if (user.Status == (int)UserStatus.Offline) { user.Status = (int)UserStatus.Inactive; _repository.CommitChanges(); } // Ensure the client is re-added _service.AddClient(user, Context.ConnectionId, UserAgent); } else { _logger.Log("{0}:{1} connected.", user.Name, Context.ConnectionId); // Update some user values _service.UpdateActivity(user, Context.ConnectionId, UserAgent); _repository.CommitChanges(); } ClientState clientState = GetClientState(); OnUserInitialize(clientState, user, reconnecting); } private void CheckStatus() { if (OutOfSync) { Clients.Caller.outOfSync(); } } private void OnUserInitialize(ClientState clientState, ChatUser user, bool reconnecting) { // Update the active room on the client (only if it's still a valid room) if (user.Rooms.Any(room => room.Name.Equals(clientState.ActiveRoom, StringComparison.OrdinalIgnoreCase))) { // Update the active room on the client (only if it's still a valid room) Clients.Caller.activeRoom = clientState.ActiveRoom; } LogOn(user, Context.ConnectionId, reconnecting); } public bool Send(string content, string roomName) { var message = new ClientMessage { Content = content, Room = roomName }; return Send(message); } public bool Send(ClientMessage clientMessage) { CheckStatus(); // reject it if it's too long if (_settings.MaxMessageLength > 0 && clientMessage.Content.Length > _settings.MaxMessageLength) { throw new HubException(String.Format(LanguageResources.SendMessageTooLong, _settings.MaxMessageLength)); } // See if this is a valid command (starts with /) if (TryHandleCommand(clientMessage.Content, clientMessage.Room)) { return true; } var userId = Context.User.GetUserId(); var user = _repository.VerifyUserId(userId); var room = _repository.VerifyUserRoom(_cache, user, clientMessage.Room); var roomUserData = _repository.GetRoomUserData(user, room); if (room == null || (room.Private && !user.AllowedRooms.Contains(room))) { return false; } // REVIEW: Is it better to use the extension method room.EnsureOpen here? if (room.Closed) { throw new HubException(String.Format(LanguageResources.SendMessageRoomClosed, clientMessage.Room)); } if (roomUserData.IsMuted) { throw new InvalidOperationException(String.Format("You cannot post messages to '{0}'. You have been muted.", clientMessage.Room)); } // Update activity *after* ensuring the user, this forces them to be active UpdateActivity(user, room); string id = clientMessage.Id; ChatMessage chatMessage = _repository.GetMessageById(id); if (chatMessage == null) { // Create a true unique id and save the message to the db id = Guid.NewGuid().ToString("d"); chatMessage = _service.AddMessage(user, room, id, clientMessage.Content); _repository.CommitChanges(); } else if (chatMessage.User == user) { chatMessage.Content = clientMessage.Content; chatMessage.HtmlContent = null; chatMessage.Edited = DateTimeOffset.UtcNow; _repository.Update(chatMessage); _repository.CommitChanges(); } else { throw new InvalidOperationException(String.Format("You cannot edit a message you do not own.")); } var messageViewModel = new MessageViewModel(chatMessage); if (clientMessage.Id == null) { // If the client didn't generate an id for the message then just // send it to everyone. The assumption is that the client has some ui // that it wanted to update immediately showing the message and // then when the actual message is roundtripped it would "solidify it". Clients.Group(room.Name).addMessage(messageViewModel, room.Name); } else { // If the client did set an id then we need to give everyone the real id first Clients.OthersInGroup(room.Name).addMessage(messageViewModel, room.Name); // Now tell the caller to replace the message Clients.Caller.replaceMessage(clientMessage.Id, messageViewModel, room.Name); } // Add mentions AddMentions(chatMessage); var urls = UrlExtractor.ExtractUrls(chatMessage.Content); if (urls.Count > 0) { _resourceProcessor.ProcessUrls(urls, Clients, room.Name, chatMessage.Id); } return true; } private void AddMentions(ChatMessage message) { var mentionedUsers = new List<ChatUser>(); foreach (var userName in MentionExtractor.ExtractMentions(message.Content, _repository.GetMentions())) { ChatUser mentionedUser = _repository.GetUserByName(userName); // Don't create a mention if // 1. If the mentioned user doesn't exist. // 2. If you mention yourself // 3. If you're mentioned in a private room that you don't have access to // 4. You've already been mentioned in this message if (mentionedUser == null || mentionedUser == message.User || (message.Room.Private && !mentionedUser.AllowedRooms.Contains(message.Room)) || mentionedUsers.Contains(mentionedUser)) { continue; } // mark as read if ALL of the following // 1. user is not offline // 2. user is not AFK // 3. user has been active within the last 10 minutes // 4. user is currently in the room bool markAsRead = mentionedUser.Status != (int)UserStatus.Offline && !mentionedUser.IsAfk && (DateTimeOffset.UtcNow - mentionedUser.LastActivity) < TimeSpan.FromMinutes(10) && _repository.IsUserInRoom(_cache, mentionedUser, message.Room); var notification = _service.AddNotification(mentionedUser, message, message.Room, markAsRead); if (!markAsRead) { MessageReadStateChanged(mentionedUser, message, notification); _pushNotification.SendAsync(notification); } mentionedUsers.Add(mentionedUser); } if (mentionedUsers.Count > 0) { _repository.CommitChanges(); } foreach (var user in mentionedUsers) { UpdateUnreadMentions(user); } } public void SetMessageReadState(string id, bool read) { var userId = Context.User.GetUserId(); var user = _repository.VerifyUserId(userId); var message = _repository.GetMessageById(id); if (message == null) return; var notification = _repository.GetNotificationByMessage(message, user); if (notification == null) return; notification.Read = read; _repository.CommitChanges(); MessageReadStateChanged(user, message, notification); UpdateUnreadMentions(user); } private void MessageReadStateChanged(ChatUser mentionedUser, ChatMessage message, Notification notification) { foreach (var client in mentionedUser.ConnectedClients) { Clients.Client(client.Id).messageReadStateChanged(message.Id, notification.Read); } } private void UpdateUnreadMentions(ChatUser mentionedUser) { var unread = _repository.GetUnreadNotificationsCount(mentionedUser); Clients.User(mentionedUser.Id) .updateUnreadNotifications(unread); } public UserViewModel GetUserInfo() { var userId = Context.User.GetUserId(); ChatUser user = _repository.VerifyUserId(userId); return new UserViewModel(user); } public override Task OnReconnected() { _logger.Log("OnReconnected({0})", Context.ConnectionId); var userId = Context.User.GetUserId(); ChatUser user = _repository.VerifyUserId(userId); if (user == null) { _logger.Log("Reconnect failed user {0}:{1} doesn't exist.", userId, Context.ConnectionId); return TaskAsyncHelper.Empty; } // Make sure this client is being tracked _service.AddClient(user, Context.ConnectionId, UserAgent); var currentStatus = (UserStatus)user.Status; if (currentStatus == UserStatus.Offline) { _logger.Log("{0}:{1} reconnected after temporary network problem and marked offline.", user.Name, Context.ConnectionId); // Mark the user as inactive user.Status = (int)UserStatus.Inactive; _repository.CommitChanges(); // If the user was offline that means they are not in the user list so we need to tell // everyone the user is really in the room var userViewModel = new UserViewModel(user); foreach (var room in user.Rooms) { var isOwner = user.OwnedRooms.Contains(room); // Tell the people in this room that you've joined Clients.Group(room.Name).addUser(userViewModel, room.Name, isOwner); } } else { _logger.Log("{0}:{1} reconnected after temporary network problem.", user.Name, Context.ConnectionId); } CheckStatus(); return base.OnReconnected(); } public override Task OnDisconnected() { _logger.Log("OnDisconnected({0})", Context.ConnectionId); DisconnectClient(Context.ConnectionId, useThreshold: true); return base.OnDisconnected(); } public object GetCommands() { return CommandManager.GetCommandsMetaData(); } public object GetShortcuts() { return new[] { new { Name = "Tab or Shift + Tab", Group = "shortcut", IsKeyCombination = true, Description = LanguageResources.Client_ShortcutTabs }, new { Name = "Alt + L", Group = "shortcut", IsKeyCombination = true, Description = LanguageResources.Client_ShortcutLobby }, new { Name = "Alt + Number", Group = "shortcut", IsKeyCombination = true, Description = LanguageResources.Client_ShortcutSpecificTab } }; } public Task<List<LobbyRoomViewModel>> GetRooms() { string userId = Context.User.GetUserId(); ChatUser user = _repository.VerifyUserId(userId); return _repository.GetAllowedRooms(user).Select(r => new LobbyRoomViewModel { Name = r.Name, Count = r.Users.Count(u => u.Status != (int)UserStatus.Offline), Private = r.Private, Closed = r.Closed, Topic = r.Topic }).ToListAsync(); } public async Task<IEnumerable<MessageViewModel>> GetPreviousMessages(string messageId) { var previousMessages = await (from m in _repository.GetPreviousMessages(messageId) orderby m.When descending select m).Take(100).ToListAsync(); return previousMessages.AsEnumerable() .Reverse() .Select(m => new MessageViewModel(m)); } public async Task LoadRooms(string[] roomNames) { string userId = Context.User.GetUserId(); ChatUser user = _repository.VerifyUserId(userId); var rooms = await _repository.Rooms.Where(r => roomNames.Contains(r.Name)) .ToListAsync(); // Can't async whenall because we'd be hitting a single // EF context with multiple concurrent queries. foreach (var room in rooms) { if (room == null || (room.Private && !user.AllowedRooms.Contains(room))) { continue; } RoomViewModel roomInfo = null; while (true) { try { // If invoking roomLoaded fails don't get the roomInfo again roomInfo = roomInfo ?? await GetRoomInfoCore(room); Clients.Caller.roomLoaded(roomInfo); break; } catch (Exception ex) { _logger.Log(ex); } } } } public Task<RoomViewModel> GetRoomInfo(string roomName) { if (String.IsNullOrEmpty(roomName)) { return null; } string userId = Context.User.GetUserId(); ChatUser user = _repository.VerifyUserId(userId); ChatRoom room = _repository.GetRoomByName(roomName); if (room == null || (room.Private && !user.AllowedRooms.Contains(room))) { return null; } return GetRoomInfoCore(room); } private async Task<RoomViewModel> GetRoomInfoCore(ChatRoom room) { var recentMessages = _recentMessageCache.GetRecentMessages(room.Name); // If we haven't cached enough messages just populate it now if (recentMessages.Count == 0) { var messages = await (from m in _repository.GetMessagesByRoom(room) orderby m.When descending select m).Take(50).ToListAsync(); // Reverse them since we want to get them in chronological order messages.Reverse(); recentMessages = messages.Select(m => new MessageViewModel(m)).ToList(); _recentMessageCache.Add(room.Name, recentMessages); } // Get online users through the repository List<ChatUser> onlineUsers = await _repository.GetOnlineUsers(room).ToListAsync(); return new RoomViewModel { Name = room.Name, Users = from u in onlineUsers select new UserViewModel(u), Owners = from u in room.Owners.Online() select u.Name, RecentMessages = recentMessages, Topic = room.Topic ?? String.Empty, Welcome = room.Welcome ?? String.Empty, Closed = room.Closed }; } public int GetMessageCount() { _repository.VerifyUserId(Context.User.GetUserId()); return _repository.GetMessageCount(); } public void PostNotification(ClientNotification notification) { PostNotification(notification, executeContentProviders: true); } public void PostNotification(ClientNotification notification, bool executeContentProviders) { string userId = Context.User.GetUserId(); ChatUser user = _repository.GetUserById(userId); ChatRoom room = _repository.VerifyUserRoom(_cache, user, notification.Room); // User must be an owner if (room == null || !room.Owners.Contains(user) || (room.Private && !user.AllowedRooms.Contains(room))) { throw new HubException(LanguageResources.PostNotification_NotAllowed); } var chatMessage = new ChatMessage { Id = Guid.NewGuid().ToString("d"), Content = notification.Content, User = user, Room = room, HtmlEncoded = false, ImageUrl = notification.ImageUrl, Source = notification.Source, When = DateTimeOffset.UtcNow, MessageType = (int)MessageType.Notification }; _repository.Add(chatMessage); _repository.CommitChanges(); Clients.Group(room.Name).addMessage(new MessageViewModel(chatMessage), room.Name); if (executeContentProviders) { var urls = UrlExtractor.ExtractUrls(chatMessage.Content); if (urls.Count > 0) { _resourceProcessor.ProcessUrls(urls, Clients, room.Name, chatMessage.Id); } } } public void Typing(string roomName) { string userId = Context.User.GetUserId(); ChatUser user = _repository.GetUserById(userId); ChatRoom room = _repository.VerifyUserRoom(_cache, user, roomName); if (room == null || (room.Private && !user.AllowedRooms.Contains(room))) { return; } UpdateActivity(user, room); var userViewModel = new UserViewModel(user); Clients.Group(room.Name).setTyping(userViewModel, room.Name); } public void UpdateActivity() { string userId = Context.User.GetUserId(); ChatUser user = _repository.GetUserById(userId); foreach (var room in user.Rooms) { UpdateActivity(user, room); } CheckStatus(); } public void ClaimPublisher() { var userId = Context.User.GetUserId(); var user = _repository.GetUserById(userId); foreach (var client in user.ConnectedClients) { Clients.Client(client.Id).publisherChanged(Context.ConnectionId); } } public void PublishExternalStatus(string source, string type, Dictionary<string, object> result, long timestamp, int interval) { var userId = Context.User.GetUserId(); var user = _repository.GetUserById(userId); // TODO Stop message duplication here foreach (var room in user.Rooms) { Clients.Group(room.Name).changeExternalStatus(user.Name, source, type, result, timestamp, interval); } } public void UpdatePreferences(JObject newPreferences) { var userId = Context.User.GetUserId(); var user = _repository.GetUserById(userId); user.Preferences = newPreferences.ToObject<ChatUserPreferences>(); _repository.CommitChanges(); Clients.User(user.Id).preferencesChanged(user.Preferences); } public void TabOrderChanged(string[] tabOrdering) { string userId = Context.User.GetUserId(); ChatUser user = _repository.GetUserById(userId); ChatUserPreferences userPreferences = user.Preferences; userPreferences.TabOrder = tabOrdering.ToList(); user.Preferences = userPreferences; _repository.CommitChanges(); Clients.Clients(user.GetConnections()).updateTabOrder(tabOrdering); } private void LogOn(ChatUser user, string clientId, bool reconnecting) { if (!reconnecting) { // Update the client state Clients.Caller.id = user.Id; Clients.Caller.name = user.Name; Clients.Caller.hash = user.Hash; Clients.Caller.unreadNotifications = user.Notifications.Count(n => !n.Read); } var ownedRooms = user.OwnedRooms.Select(r => r.Key); var userViewModel = new UserViewModel(user); var rooms = new List<RoomViewModel>(); foreach (var room in user.Rooms) { var isOwner = ownedRooms.Contains(room.Key); // Tell the people in this room that you've joined Clients.Group(room.Name).addUser(userViewModel, room.Name, isOwner); // Add the caller to the group so they receive messages Groups.Add(clientId, room.Name); if (!reconnecting) { // Add to the list of room names rooms.Add(new RoomViewModel { Name = room.Name, Private = room.Private, Closed = room.Closed }); } } if (!reconnecting) { var privateRooms = user.AllowedRooms.Select(r => new LobbyRoomViewModel { Name = r.Name, Count = _repository.GetOnlineUsers(r).Count(), Private = r.Private, Closed = r.Closed, Topic = r.Topic }); var unreadNotifications = user.Notifications .Where(n => !n.Read) .Select(n => new { n.Key, MessageId = n.Message.Id }); // Initialize the chat with the rooms the user is in Clients.Caller.logOn( rooms, privateRooms, user.Preferences, user.Mentions.Select(m => m.String), unreadNotifications ); } // Send preferences to client Clients.Caller.preferencesChanged(user.Preferences); } private void UpdateActivity(ChatUser user, ChatRoom room) { UpdateActivity(user); OnUpdateActivity(user, room); } private void UpdateActivity(ChatUser user) { _service.UpdateActivity(user, Context.ConnectionId, UserAgent); _repository.CommitChanges(); } private bool TryHandleCommand(string command, string room) { string clientId = Context.ConnectionId; string userId = Context.User.GetUserId(); var commandManager = new CommandManager(clientId, UserAgent, userId, room, _service, _repository, _cache, this); return commandManager.TryHandleCommand(command); } private void DisconnectClient(string clientId, bool useThreshold = false) { string userId = _service.DisconnectClient(clientId); if (String.IsNullOrEmpty(userId)) { _logger.Log("Failed to disconnect {0}. No user found", clientId); return; } if (useThreshold) { Thread.Sleep(_disconnectThreshold); } // Query for the user to get the updated status ChatUser user = _repository.GetUserById(userId); // There's no associated user for this client id if (user == null) { _logger.Log("Failed to disconnect {0}:{1}. No user found", userId, clientId); return; } _repository.Reload(user); _logger.Log("{0}:{1} disconnected", user.Name, Context.ConnectionId); // The user will be marked as offline if all clients leave if (user.Status == (int)UserStatus.Offline) { _logger.Log("Marking {0} offline", user.Name); foreach (var room in user.Rooms) { var userViewModel = new UserViewModel(user); Clients.OthersInGroup(room.Name).leave(userViewModel, room.Name); } } } private void OnUpdateActivity(ChatUser user, ChatRoom room) { var userViewModel = new UserViewModel(user); Clients.Group(room.Name).updateActivity(userViewModel, room.Name); } private void LeaveRoom(ChatUser user, ChatRoom room) { var userViewModel = new UserViewModel(user); Clients.Group(room.Name).leave(userViewModel, room.Name); foreach (var client in user.ConnectedClients) { Groups.Remove(client.Id, room.Name); } OnRoomChanged(room); } void INotificationService.LogOn(ChatUser user, string clientId) { LogOn(user, clientId, reconnecting: true); } void INotificationService.KickUser(ChatUser targetUser, ChatRoom room, string message, Uri imageUrl) { var userViewModel = new UserViewModel(targetUser); // Send user kicked message to everyone Clients.Group(room.Name).kick(userViewModel, room.Name, message, imageUrl); // Remove targetUser clients foreach (var client in targetUser.ConnectedClients) { Groups.Remove(client.Id, room.Name); } OnRoomChanged(room); } void INotificationService.OnUserCreated(ChatUser user) { // Set some client state Clients.Caller.name = user.Name; Clients.Caller.id = user.Id; Clients.Caller.hash = user.Hash; // Tell the client a user was created Clients.Caller.userCreated(); } void INotificationService.JoinRoom(ChatUser user, ChatRoom room) { var userViewModel = new UserViewModel(user); var roomViewModel = new RoomViewModel { Name = room.Name, Private = room.Private, Welcome = room.Welcome ?? String.Empty, Closed = room.Closed }; var isOwner = user.OwnedRooms.Contains(room); // Tell all clients to join this room Clients.User(user.Id).joinRoom(roomViewModel); // Tell the people in this room that you've joined Clients.Group(room.Name).addUser(userViewModel, room.Name, isOwner); // Notify users of the room count change OnRoomChanged(room); foreach (var client in user.ConnectedClients) { Groups.Add(client.Id, room.Name); } } void INotificationService.AllowUser(ChatUser targetUser, ChatRoom targetRoom) { // Build a viewmodel for the room var roomViewModel = new RoomViewModel { Name = targetRoom.Name, Private = targetRoom.Private, Closed = targetRoom.Closed, Topic = targetRoom.Topic ?? String.Empty, Count = _repository.GetOnlineUsers(targetRoom).Count() }; // Tell this client it's allowed. Pass down a viewmodel so that we can add the room to the lobby. Clients.User(targetUser.Id).allowUser(targetRoom.Name, roomViewModel); // Tell the calling client the granting permission into the room was successful Clients.Caller.userAllowed(targetUser.Name, targetRoom.Name); } void INotificationService.UnallowUser(ChatUser targetUser, ChatRoom targetRoom) { // Kick the user from the room when they are unallowed ((INotificationService)this).KickUser(targetUser, targetRoom); // Tell this client it's no longer allowed Clients.User(targetUser.Id).unallowUser(targetRoom.Name); // Tell the calling client the granting permission into the room was successful Clients.Caller.userUnallowed(targetUser.Name, targetRoom.Name); } void INotificationService.MuteUser(ChatUser targetUser, ChatRoom targetRoom) { // Tell the room that the user has been muted Clients.Group(targetRoom.Name).userMuted(targetUser.Name, targetRoom.Name); } void INotificationService.UnMuteUser(ChatUser targetUser, ChatRoom targetRoom) { // Tell the room that the user has been un-muted Clients.Group(targetRoom.Name).userUnMuted(targetUser.Name, targetRoom.Name); } void INotificationService.AddOwner(ChatUser targetUser, ChatRoom targetRoom) { // Tell this client it's an owner Clients.User(targetUser.Id).makeOwner(targetRoom.Name); var userViewModel = new UserViewModel(targetUser); // If the target user is in the target room. // Tell everyone in the target room that a new owner was added if (_repository.IsUserInRoom(_cache, targetUser, targetRoom)) { Clients.Group(targetRoom.Name).addOwner(userViewModel, targetRoom.Name); } // Tell the calling client the granting of ownership was successful Clients.Caller.ownerMade(targetUser.Name, targetRoom.Name); } void INotificationService.RemoveOwner(ChatUser targetUser, ChatRoom targetRoom) { // Tell this client it's no longer an owner Clients.User(targetUser.Id).demoteOwner(targetRoom.Name); var userViewModel = new UserViewModel(targetUser); // If the target user is in the target room. // Tell everyone in the target room that the owner was removed if (_repository.IsUserInRoom(_cache, targetUser, targetRoom)) { Clients.Group(targetRoom.Name).removeOwner(userViewModel, targetRoom.Name); } // Tell the calling client the removal of ownership was successful Clients.Caller.ownerRemoved(targetUser.Name, targetRoom.Name); } void INotificationService.ChangeGravatar(ChatUser user) { Clients.Caller.hash = user.Hash; // Update the calling client Clients.User(user.Id).gravatarChanged(); // Create the view model var userViewModel = new UserViewModel(user); // Tell all users in rooms to change the gravatar foreach (var room in user.Rooms) { Clients.Group(room.Name).changeGravatar(userViewModel, room.Name); } } void INotificationService.ChangeMentions(ChatUser user, string[] mentions, bool update) { Clients.Caller.hash = user.Hash; // Update the calling client foreach (var client in user.ConnectedClients) { Clients.Client(client.Id).mentionsChanged(mentions, update); } // Create the view model var userViewModel = new UserViewModel(user); // Tell all users in rooms to change the gravatar foreach (var room in user.Rooms) { Clients.Group(room.Name).changeMentions(userViewModel, room.Name); } } void INotificationService.OnSelfMessage(ChatRoom room, ChatUser user, string content) { Clients.Group(room.Name).sendMeMessage(user.Name, content, room.Name); } void INotificationService.SendPrivateMessage(ChatUser fromUser, ChatUser toUser, string messageText) { // Send a message to the sender and the sendee Clients.User(fromUser.Id).sendPrivateMessage(fromUser.Name, toUser.Name, messageText); Clients.User(toUser.Id).sendPrivateMessage(fromUser.Name, toUser.Name, messageText); } void INotificationService.PostNotification(ChatRoom room, ChatUser user, string message) { Clients.User(user.Id).postNotification(message, room.Name); } void INotificationService.ListRooms(ChatUser user) { string userId = Context.User.GetUserId(); var userModel = new UserViewModel(user); Clients.Caller.showUsersRoomList(userModel, user.Rooms.Allowed(userId).Select(r => r.Name)); } void INotificationService.ListUsers() { var users = _repository.Users.Online().Select(s => s.Name).OrderBy(s => s); Clients.Caller.listUsers(users); } void INotificationService.ListUsers(IEnumerable<ChatUser> users) { Clients.Caller.listUsers(users.Select(s => s.Name)); } void INotificationService.ListUsers(ChatRoom room, IEnumerable<string> names) { Clients.Caller.showUsersInRoom(room.Name, names); } void INotificationService.ListAllowedUsers(ChatRoom room) { Clients.Caller.listAllowedUsers(room.Name, room.Private, room.AllowedUsers.Select(s => s.Name)); } void INotificationService.LockRoom(ChatUser targetUser, ChatRoom room) { var userViewModel = new UserViewModel(targetUser); // Tell everyone that the room's locked Clients.Clients(_repository.GetAllowedClientIds(room)).lockRoom(userViewModel, room.Name, true); Clients.AllExcept(_repository.GetAllowedClientIds(room).ToArray()).lockRoom(userViewModel, room.Name, false); // Tell the caller the room was successfully locked Clients.Caller.roomLocked(room.Name); // Notify people of the change OnRoomChanged(room); } void INotificationService.CloseRoom(IEnumerable<ChatUser> users, ChatRoom room) { // notify all members of room that it is now closed foreach (var user in users) { Clients.User(user.Id).roomClosed(room.Name); } // notify everyone to update their lobby OnRoomChanged(room); } void INotificationService.UnCloseRoom(IEnumerable<ChatUser> users, ChatRoom room) { // notify all members of room that it is now re-opened foreach (var user in users) { Clients.User(user.Id).roomUnClosed(room.Name); } // notify everyone to update their lobby OnRoomChanged(room); } void INotificationService.LogOut(ChatUser user, string clientId) { foreach (var client in user.ConnectedClients) { DisconnectClient(client.Id); Clients.Client(client.Id).logOut(); } } void INotificationService.ShowUserInfo(ChatUser user) { string userId = Context.User.GetUserId(); Clients.Caller.showUserInfo(new { Name = user.Name, OwnedRooms = user.OwnedRooms .Allowed(userId) .Where(r => !r.Closed) .Select(r => r.Name), Status = ((UserStatus)user.Status).ToString(), LastActivity = user.LastActivity, IsAfk = user.IsAfk, AfkNote = user.AfkNote, Note = user.Note, Hash = user.Hash, Rooms = user.Rooms.Allowed(userId).Select(r => r.Name) }); } void INotificationService.ShowHelp() { Clients.Caller.showCommands(); } void INotificationService.Invite(ChatUser user, ChatUser targetUser, ChatRoom targetRoom) { // Send the invite message to the sendee Clients.User(targetUser.Id).sendInvite(user.Name, targetUser.Name, targetRoom.Name); // Send the invite notification to the sender Clients.User(user.Id).sendInvite(user.Name, targetUser.Name, targetRoom.Name); } void INotificationService.NudgeUser(ChatUser user, ChatUser targetUser) { // Send a nudge message to the sender and the sendee Clients.User(targetUser.Id).nudge(user.Name, targetUser.Name, null); Clients.User(user.Id).nudge(user.Name, targetUser.Name, null); } void INotificationService.NudgeRoom(ChatRoom room, ChatUser user) { Clients.Group(room.Name).nudge(user.Name, null, room.Name); } void INotificationService.LeaveRoom(ChatUser user, ChatRoom room) { LeaveRoom(user, room); } void INotificationService.OnUserNameChanged(ChatUser user, string oldUserName, string newUserName) { // Create the view model var userViewModel = new UserViewModel(user); // Tell the user's connected clients that the name changed Clients.User(user.Id).userNameChanged(userViewModel); // Notify all users in the rooms foreach (var room in user.Rooms) { Clients.Group(room.Name).changeUserName(oldUserName, userViewModel, room.Name); } } void INotificationService.ChangeAfk(ChatUser user) { // Create the view model var userViewModel = new UserViewModel(user); // Tell all users in rooms to change the note foreach (var room in user.Rooms) { Clients.Group(room.Name).changeAfk(userViewModel, room.Name); } } void INotificationService.ChangeNote(ChatUser user) { // Create the view model var userViewModel = new UserViewModel(user); // Tell all users in rooms to change the note foreach (var room in user.Rooms) { Clients.Group(room.Name).changeNote(userViewModel, room.Name); } } void INotificationService.ChangeFlag(ChatUser user) { bool isFlagCleared = String.IsNullOrWhiteSpace(user.Flag); // Create the view model var userViewModel = new UserViewModel(user); // Update the calling client Clients.User(user.Id).flagChanged(isFlagCleared, userViewModel.Country); // Tell all users in rooms to change the flag foreach (var room in user.Rooms) { Clients.Group(room.Name).changeFlag(userViewModel, room.Name); } } void INotificationService.ChangeTopic(ChatUser user, ChatRoom room) { Clients.Group(room.Name).topicChanged(room.Name, room.Topic ?? String.Empty, user.Name); // trigger a lobby update OnRoomChanged(room); } void INotificationService.ChangeWelcome(ChatUser user, ChatRoom room) { bool isWelcomeCleared = String.IsNullOrWhiteSpace(room.Welcome); var parsedWelcome = room.Welcome ?? String.Empty; Clients.User(user.Id).welcomeChanged(isWelcomeCleared, parsedWelcome); } void INotificationService.GenerateMeme(ChatUser user, ChatRoom room, string message) { Send(message, room.Name); } void INotificationService.AddAdmin(ChatUser targetUser) { // Tell this client it's an owner Clients.User(targetUser.Id).makeAdmin(); var userViewModel = new UserViewModel(targetUser); // Tell all users in rooms to change the admin status foreach (var room in targetUser.Rooms) { Clients.Group(room.Name).addAdmin(userViewModel, room.Name); } // Tell the calling client the granting of admin status was successful Clients.Caller.adminMade(targetUser.Name); } void INotificationService.RemoveAdmin(ChatUser targetUser) { // Tell this client it's no longer an owner Clients.User(targetUser.Id).demoteAdmin(); var userViewModel = new UserViewModel(targetUser); // Tell all users in rooms to change the admin status foreach (var room in targetUser.Rooms) { Clients.Group(room.Name).removeAdmin(userViewModel, room.Name); } // Tell the calling client the removal of admin status was successful Clients.Caller.adminRemoved(targetUser.Name); } void INotificationService.BroadcastMessage(ChatUser user, string messageText) { // Tell all users in all rooms about this message foreach (var room in _repository.Rooms) { Clients.Group(room.Name).broadcastMessage(messageText, room.Name); } } void INotificationService.ForceUpdate() { Clients.All.forceUpdate(); } private void OnRoomChanged(ChatRoom room) { var roomViewModel = new RoomViewModel { Name = room.Name, Private = room.Private, Closed = room.Closed, Topic = room.Topic ?? String.Empty, Count = _repository.GetOnlineUsers(room).Count() }; // notify all clients who can see the room if (!room.Private) { Clients.All.updateRoom(roomViewModel); } else { Clients.Clients(_repository.GetAllowedClientIds(room)).updateRoom(roomViewModel); } } private ClientState GetClientState() { // New client state var jabbrState = GetCookieValue("jabbr.state"); ClientState clientState = null; if (String.IsNullOrEmpty(jabbrState)) { clientState = new ClientState(); } else { clientState = JsonConvert.DeserializeObject<ClientState>(jabbrState); } return clientState; } private string GetCookieValue(string key) { Cookie cookie; Context.RequestCookies.TryGetValue(key, out cookie); string value = cookie != null ? cookie.Value : null; return value != null ? Uri.UnescapeDataString(value) : null; } void INotificationService.BanUser(ChatUser targetUser) { var rooms = targetUser.Rooms.Select(x => x.Name); foreach (var room in rooms) { foreach (var client in targetUser.ConnectedClients) { // Kick the user from this room Clients.Client(client.Id).kick(room); // Remove the user from this the room group so he doesn't get the leave message Groups.Remove(client.Id, room); } } Clients.User(targetUser.Id).logOut(rooms); } protected override void Dispose(bool disposing) { if (disposing) { _repository.Dispose(); } base.Dispose(disposing); } } }
using System; using NUnit.Framework; using Org.BouncyCastle.Crypto; using Org.BouncyCastle.Crypto.Parameters; using Org.BouncyCastle.Security; using Org.BouncyCastle.Utilities.Encoders; using Org.BouncyCastle.Utilities.Test; namespace Org.BouncyCastle.Tests { /** * CMAC tester - <a href="http://www.nuee.nagoya-u.ac.jp/labs/tiwata/omac/tv/omac1-tv.txt">AES Official Test Vectors</a>. */ [TestFixture] public class CMacTest : SimpleTest { private static readonly byte[] keyBytes128 = Hex.Decode("2b7e151628aed2a6abf7158809cf4f3c"); private static readonly byte[] keyBytes192 = Hex.Decode( "8e73b0f7da0e6452c810f32b809079e5" + "62f8ead2522c6b7b"); private static readonly byte[] keyBytes256 = Hex.Decode( "603deb1015ca71be2b73aef0857d7781" + "1f352c073b6108d72d9810a30914dff4"); private static readonly byte[] input0 = Hex.Decode(""); private static readonly byte[] input16 = Hex.Decode("6bc1bee22e409f96e93d7e117393172a"); private static readonly byte[] input40 = Hex.Decode( "6bc1bee22e409f96e93d7e117393172a" + "ae2d8a571e03ac9c9eb76fac45af8e5130c81c46a35ce411"); private static readonly byte[] input64 = Hex.Decode( "6bc1bee22e409f96e93d7e117393172a" + "ae2d8a571e03ac9c9eb76fac45af8e51" + "30c81c46a35ce411e5fbc1191a0a52ef" + "f69f2445df4f9b17ad2b417be66c3710"); private static readonly byte[] output_k128_m0 = Hex.Decode("bb1d6929e95937287fa37d129b756746"); private static readonly byte[] output_k128_m16 = Hex.Decode("070a16b46b4d4144f79bdd9dd04a287c"); private static readonly byte[] output_k128_m40 = Hex.Decode("dfa66747de9ae63030ca32611497c827"); private static readonly byte[] output_k128_m64 = Hex.Decode("51f0bebf7e3b9d92fc49741779363cfe"); private static readonly byte[] output_k192_m0 = Hex.Decode("d17ddf46adaacde531cac483de7a9367"); private static readonly byte[] output_k192_m16 = Hex.Decode("9e99a7bf31e710900662f65e617c5184"); private static readonly byte[] output_k192_m40 = Hex.Decode("8a1de5be2eb31aad089a82e6ee908b0e"); private static readonly byte[] output_k192_m64 = Hex.Decode("a1d5df0eed790f794d77589659f39a11"); private static readonly byte[] output_k256_m0 = Hex.Decode("028962f61b7bf89efc6b551f4667d983"); private static readonly byte[] output_k256_m16 = Hex.Decode("28a7023f452e8f82bd4bf28d8c37c35c"); private static readonly byte[] output_k256_m40 = Hex.Decode("aaf3d8f1de5640c232f5b169b9c911e6"); private static readonly byte[] output_k256_m64 = Hex.Decode("e1992190549f6ed5696a2c056c315410"); private static readonly byte[] output_des_ede = Hex.Decode("1ca670dea381d37c"); public CMacTest() { } public override void PerformTest() { // Mac mac = Mac.getInstance("AESCMAC", "BC"); IMac mac = MacUtilities.GetMac("AESCMAC"); //128 bytes key // SecretKeySpec key = new SecretKeySpec(keyBytes128, "AES"); KeyParameter key = new KeyParameter(keyBytes128); // 0 bytes message - 128 bytes key mac.Init(key); mac.BlockUpdate(input0, 0, input0.Length); byte[] output = MacUtilities.DoFinal(mac); if (!AreEqual(output, output_k128_m0)) { Fail("Failed - expected " + Hex.ToHexString(output_k128_m0) + " got " + Hex.ToHexString(output)); } // 16 bytes message - 128 bytes key mac.Init(key); mac.BlockUpdate(input16, 0, input16.Length); output = MacUtilities.DoFinal(mac); if (!AreEqual(output, output_k128_m16)) { Fail("Failed - expected " + Hex.ToHexString(output_k128_m16) + " got " + Hex.ToHexString(output)); } // 40 bytes message - 128 bytes key mac.Init(key); mac.BlockUpdate(input40, 0, input40.Length); output = MacUtilities.DoFinal(mac); if (!AreEqual(output, output_k128_m40)) { Fail("Failed - expected " + Hex.ToHexString(output_k128_m40) + " got " + Hex.ToHexString(output)); } // 64 bytes message - 128 bytes key mac.Init(key); mac.BlockUpdate(input64, 0, input64.Length); output = MacUtilities.DoFinal(mac); if (!AreEqual(output, output_k128_m64)) { Fail("Failed - expected " + Hex.ToHexString(output_k128_m64) + " got " + Hex.ToHexString(output)); } //192 bytes key // key = new SecretKeySpec(keyBytes192, "AES"); key = new KeyParameter(keyBytes192); // 0 bytes message - 192 bytes key mac.Init(key); mac.BlockUpdate(input0, 0, input0.Length); output = MacUtilities.DoFinal(mac); if (!AreEqual(output, output_k192_m0)) { Fail("Failed - expected " + Hex.ToHexString(output_k192_m0) + " got " + Hex.ToHexString(output)); } // 16 bytes message - 192 bytes key mac.Init(key); mac.BlockUpdate(input16, 0, input16.Length); output = MacUtilities.DoFinal(mac); if (!AreEqual(output, output_k192_m16)) { Fail("Failed - expected " + Hex.ToHexString(output_k192_m16) + " got " + Hex.ToHexString(output)); } // 40 bytes message - 192 bytes key mac.Init(key); mac.BlockUpdate(input40, 0, input40.Length); output = MacUtilities.DoFinal(mac); if (!AreEqual(output, output_k192_m40)) { Fail("Failed - expected " + Hex.ToHexString(output_k192_m40) + " got " + Hex.ToHexString(output)); } // 64 bytes message - 192 bytes key mac.Init(key); mac.BlockUpdate(input64, 0, input64.Length); output = MacUtilities.DoFinal(mac); if (!AreEqual(output, output_k192_m64)) { Fail("Failed - expected " + Hex.ToHexString(output_k192_m64) + " got " + Hex.ToHexString(output)); } //256 bytes key // key = new SecretKeySpec(keyBytes256, "AES"); key = new KeyParameter(keyBytes256); // 0 bytes message - 256 bytes key mac.Init(key); mac.BlockUpdate(input0, 0, input0.Length); output = MacUtilities.DoFinal(mac); if (!AreEqual(output, output_k256_m0)) { Fail("Failed - expected " + Hex.ToHexString(output_k256_m0) + " got " + Hex.ToHexString(output)); } // 16 bytes message - 256 bytes key mac.Init(key); mac.BlockUpdate(input16, 0, input16.Length); output = MacUtilities.DoFinal(mac); if (!AreEqual(output, output_k256_m16)) { Fail("Failed - expected " + Hex.ToHexString(output_k256_m16) + " got " + Hex.ToHexString(output)); } // 40 bytes message - 256 bytes key mac.Init(key); mac.BlockUpdate(input40, 0, input40.Length); output = MacUtilities.DoFinal(mac); if (!AreEqual(output, output_k256_m40)) { Fail("Failed - expected " + Hex.ToHexString(output_k256_m40) + " got " + Hex.ToHexString(output)); } // 64 bytes message - 256 bytes key mac.Init(key); mac.BlockUpdate(input64, 0, input64.Length); output = MacUtilities.DoFinal(mac); if (!AreEqual(output, output_k256_m64)) { Fail("Failed - expected " + Hex.ToHexString(output_k256_m64) + " got " + Hex.ToHexString(output)); } // mac = Mac.getInstance("DESedeCMAC", "BC"); mac = MacUtilities.GetMac("DESedeCMAC"); //DESede // key = new SecretKeySpec(keyBytes128, "DESede"); key = new KeyParameter(keyBytes128); // 0 bytes message - 128 bytes key mac.Init(key); mac.BlockUpdate(input0, 0, input0.Length); output = MacUtilities.DoFinal(mac); if (!AreEqual(output, output_des_ede)) { Fail("Failed - expected " + Hex.ToHexString(output_des_ede) + " got " + Hex.ToHexString(output)); } } public override string Name { get { return "CMac"; } } public static void Main(string[] args) { RunTest(new CMacTest()); } [Test] public void TestFunction() { string resultText = Perform().ToString(); Assert.AreEqual(Name + ": Okay", resultText); } } }
using UnityEngine; using UnityEditor; [CustomEditor(typeof(MegaHose))] public class MegaHoseEditor : Editor { [MenuItem("GameObject/Create Other/MegaShape/Hose")] static void CreatePageMesh() { Vector3 pos = Vector3.zero; if ( UnityEditor.SceneView.lastActiveSceneView ) pos = UnityEditor.SceneView.lastActiveSceneView.pivot; GameObject go = new GameObject("Hose"); MeshFilter mf = go.AddComponent<MeshFilter>(); mf.sharedMesh = new Mesh(); MeshRenderer mr = go.AddComponent<MeshRenderer>(); Material[] mats = new Material[3]; mr.sharedMaterials = mats; MegaHose pm = go.AddComponent<MegaHose>(); go.transform.position = pos; Selection.activeObject = go; pm.rebuildcross = true; pm.updatemesh = true; //pm.Rebuild(); } public override void OnInspectorGUI() { MegaHose mod = (MegaHose)target; EditorGUIUtility.LookLikeControls(); mod.dolateupdate = EditorGUILayout.Toggle("Do Late Update", mod.dolateupdate); mod.InvisibleUpdate = EditorGUILayout.Toggle("Invisible Update", mod.InvisibleUpdate); mod.wiretype = (MegaHoseType)EditorGUILayout.EnumPopup("Wire Type", mod.wiretype); mod.segments = EditorGUILayout.IntField("Segments", mod.segments); mod.capends = EditorGUILayout.Toggle("Cap Ends", mod.capends); mod.calcnormals = EditorGUILayout.Toggle("Calc Normals", mod.calcnormals); mod.calctangents = EditorGUILayout.Toggle("Calc Tangents", mod.calctangents); mod.optimize = EditorGUILayout.Toggle("Optimize", mod.optimize); mod.recalcCollider = EditorGUILayout.Toggle("Calc Collider", mod.recalcCollider); switch ( mod.wiretype ) { case MegaHoseType.Round: mod.rnddia = EditorGUILayout.FloatField("Diameter", mod.rnddia); mod.rndsides = EditorGUILayout.IntField("Sides", mod.rndsides); mod.rndrot = EditorGUILayout.FloatField("Rotate", mod.rndrot); break; case MegaHoseType.Rectangle: mod.rectwidth = EditorGUILayout.FloatField("Width", mod.rectwidth); mod.rectdepth = EditorGUILayout.FloatField("Depth", mod.rectdepth); mod.rectfillet = EditorGUILayout.FloatField("Fillet", mod.rectfillet); mod.rectfilletsides = EditorGUILayout.IntField("Fillet Sides", mod.rectfilletsides); mod.rectrotangle = EditorGUILayout.FloatField("Rotate", mod.rectrotangle); break; case MegaHoseType.DSection: mod.dsecwidth = EditorGUILayout.FloatField("Width", mod.dsecwidth); mod.dsecdepth = EditorGUILayout.FloatField("Depth", mod.dsecdepth); mod.dsecrndsides = EditorGUILayout.IntField("Rnd Sides", mod.dsecrndsides); mod.dsecfillet = EditorGUILayout.FloatField("Fillet", mod.dsecfillet); mod.dsecfilletsides = EditorGUILayout.IntField("Fillet Sides", mod.dsecfilletsides); mod.dsecrotangle = EditorGUILayout.FloatField("Rotate", mod.dsecrotangle); break; } mod.uvscale = EditorGUILayout.Vector2Field("UV Scale", mod.uvscale); if ( GUI.changed ) { mod.updatemesh = true; mod.rebuildcross = true; } mod.custnode = (GameObject)EditorGUILayout.ObjectField("Start Object", mod.custnode, typeof(GameObject), true); mod.offset = EditorGUILayout.Vector3Field("Offset", mod.offset); mod.rotate = EditorGUILayout.Vector3Field("Rotate", mod.rotate); mod.scale = EditorGUILayout.Vector3Field("Scale", mod.scale); mod.custnode2 = (GameObject)EditorGUILayout.ObjectField("End Object", mod.custnode2, typeof(GameObject), true); mod.offset1 = EditorGUILayout.Vector3Field("Offset", mod.offset1); mod.rotate1 = EditorGUILayout.Vector3Field("Rotate", mod.rotate1); mod.scale1 = EditorGUILayout.Vector3Field("Scale", mod.scale1); mod.flexon = EditorGUILayout.BeginToggleGroup("Flex On", mod.flexon); mod.flexstart = EditorGUILayout.Slider("Start", mod.flexstart, 0.0f, 1.0f); mod.flexstop = EditorGUILayout.Slider("Stop", mod.flexstop, 0.0f, 1.0f); if ( mod.flexstart > mod.flexstop ) mod.flexstart = mod.flexstop; if ( mod.flexstop < mod.flexstart ) mod.flexstop = mod.flexstart; mod.flexcycles = EditorGUILayout.IntField("Cycles", mod.flexcycles); mod.flexdiameter = EditorGUILayout.FloatField("Diameter", mod.flexdiameter); EditorGUILayout.EndToggleGroup(); mod.usebulgecurve = EditorGUILayout.BeginToggleGroup("Use Bulge Curve", mod.usebulgecurve); mod.bulge = EditorGUILayout.CurveField("Bulge", mod.bulge); mod.bulgeamount = EditorGUILayout.FloatField("Bulge Amount", mod.bulgeamount); mod.bulgeoffset = EditorGUILayout.FloatField("Bulge Offset", mod.bulgeoffset); mod.animatebulge = EditorGUILayout.BeginToggleGroup("Animate", mod.animatebulge); mod.bulgespeed = EditorGUILayout.FloatField("Speed", mod.bulgespeed); mod.minbulge = EditorGUILayout.FloatField("Min", mod.minbulge); mod.maxbulge = EditorGUILayout.FloatField("Max", mod.maxbulge); EditorGUILayout.EndToggleGroup(); EditorGUILayout.EndToggleGroup(); mod.tension1 = EditorGUILayout.FloatField("Tension Start", mod.tension1); mod.tension2 = EditorGUILayout.FloatField("Tension End", mod.tension2); mod.freecreate = EditorGUILayout.BeginToggleGroup("Free Create", mod.freecreate); mod.noreflength = EditorGUILayout.FloatField("Free Length", mod.noreflength); EditorGUILayout.EndToggleGroup(); mod.up = EditorGUILayout.Vector3Field("Up", mod.up); mod.displayspline = EditorGUILayout.Toggle("Display Spline", mod.displayspline); if ( GUI.changed ) //rebuild ) { mod.updatemesh = true; mod.Rebuild(); } } #if false public void OnSceneGUI() { MegaHose hose = (MegaHose)target; if ( hose.calcnormals ) { Handles.matrix = hose.transform.localToWorldMatrix; Handles.color = Color.red; for ( int i = 0; i < hose.verts.Length; i++ ) { //Gizmos.DrawRay(hose.verts[i], hose.normals[i] * 2.0f); Handles.DrawLine(hose.verts[i], hose.verts[i] + (hose.normals[i] * 0.5f)); } } } #endif #if UNITY_5_1 || UNITY_5_2 [DrawGizmo(GizmoType.NotInSelectionHierarchy | GizmoType.Pickable | GizmoType.InSelectionHierarchy)] #else [DrawGizmo(GizmoType.NotSelected | GizmoType.Pickable | GizmoType.SelectedOrChild)] #endif static void RenderGizmo(MegaHose hose, GizmoType gizmoType) { if ( (gizmoType & GizmoType.Active) != 0 && Selection.activeObject == hose.gameObject ) { if ( !hose.displayspline ) return; if ( hose.custnode == null || hose.custnode2 == null ) return; DrawGizmos(hose, new Color(1.0f, 1.0f, 1.0f, 1.0f)); Color col = Color.yellow; col.a = 0.5f; //0.75f; Gizmos.color = col; //Color.yellow; Matrix4x4 RingTM = Matrix4x4.identity; hose.CalcMatrix(ref RingTM, 0.0f); RingTM = hose.transform.localToWorldMatrix * RingTM; float gsize = 0.0f; switch ( hose.wiretype ) { case MegaHoseType.Round: gsize = hose.rnddia; break; case MegaHoseType.Rectangle: gsize = (hose.rectdepth + hose.rectwidth) * 0.5f; break; case MegaHoseType.DSection: gsize = (hose.dsecdepth + hose.dsecwidth) * 0.5f; break; } gsize *= 0.1f; for ( int p = 0; p < hose.hosespline.knots.Count; p++ ) { Vector3 p1 = RingTM.MultiplyPoint(hose.hosespline.knots[p].p); Vector3 p2 = RingTM.MultiplyPoint(hose.hosespline.knots[p].invec); Vector3 p3 = RingTM.MultiplyPoint(hose.hosespline.knots[p].outvec); Gizmos.color = Color.black; Gizmos.DrawLine(p2, p1); Gizmos.DrawLine(p3, p1); Gizmos.color = Color.green; Gizmos.DrawSphere(p1, gsize); Gizmos.color = Color.red; Gizmos.DrawSphere(p2, gsize); Gizmos.DrawSphere(p3, gsize); } } } static void DrawGizmos(MegaHose hose, Color modcol1) { Matrix4x4 RingTM = Matrix4x4.identity; Matrix4x4 tm = hose.transform.localToWorldMatrix; float ldist = 1.0f * 0.1f; if ( ldist < 0.01f ) ldist = 0.01f; Color modcol = modcol1; if ( hose.hosespline.length / ldist > 500.0f ) ldist = hose.hosespline.length / 500.0f; float ds = hose.hosespline.length / (hose.hosespline.length / ldist); if ( ds > hose.hosespline.length ) ds = hose.hosespline.length; int c = 0; int k = -1; int lk = -1; Vector3 first = hose.hosespline.Interpolate(0.0f, true, ref lk); hose.CalcMatrix(ref RingTM, 0.0f); RingTM = tm * RingTM; for ( float dist = ds; dist < hose.hosespline.length; dist += ds ) { float alpha = dist / hose.hosespline.length; Vector3 pos = hose.hosespline.Interpolate(alpha, true, ref k); if ( (c & 1) == 1 ) Gizmos.color = Color.black * modcol; else Gizmos.color = Color.yellow * modcol; if ( k != lk ) { for ( lk = lk + 1; lk <= k; lk++ ) { Gizmos.DrawLine(RingTM.MultiplyPoint(first), RingTM.MultiplyPoint(hose.hosespline.knots[lk].p)); first = hose.hosespline.knots[lk].p; } } lk = k; Gizmos.DrawLine(RingTM.MultiplyPoint(first), RingTM.MultiplyPoint(pos)); c++; first = pos; } if ( (c & 1) == 1 ) Gizmos.color = Color.blue * modcol; else Gizmos.color = Color.yellow * modcol; Vector3 lastpos; if ( hose.hosespline.closed ) lastpos = hose.hosespline.Interpolate(0.0f, true, ref k); else lastpos = hose.hosespline.Interpolate(1.0f, true, ref k); Gizmos.DrawLine(RingTM.MultiplyPoint(first), RingTM.MultiplyPoint(lastpos)); } }
/* * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.RDS.Model { /// <summary> /// Container for the parameters to the DescribeReservedDBInstances operation. /// <para> Returns information about reserved DB Instances for this account, or about a specified reserved DB Instance. </para> /// </summary> /// <seealso cref="Amazon.RDS.AmazonRDS.DescribeReservedDBInstances"/> public class DescribeReservedDBInstancesRequest : AmazonWebServiceRequest { private string reservedDBInstanceId; private string reservedDBInstancesOfferingId; private string dBInstanceClass; private string duration; private string productDescription; private string offeringType; private bool? multiAZ; private int? maxRecords; private string marker; /// <summary> /// The reserved DB Instance identifier filter value. Specify this parameter to show only the reservation that matches the specified reservation /// ID. /// /// </summary> public string ReservedDBInstanceId { get { return this.reservedDBInstanceId; } set { this.reservedDBInstanceId = value; } } /// <summary> /// Sets the ReservedDBInstanceId property /// </summary> /// <param name="reservedDBInstanceId">The value to set for the ReservedDBInstanceId property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public DescribeReservedDBInstancesRequest WithReservedDBInstanceId(string reservedDBInstanceId) { this.reservedDBInstanceId = reservedDBInstanceId; return this; } // Check to see if ReservedDBInstanceId property is set internal bool IsSetReservedDBInstanceId() { return this.reservedDBInstanceId != null; } /// <summary> /// The offering identifier filter value. Specify this parameter to show only purchased reservations matching the specified offering identifier. /// /// </summary> public string ReservedDBInstancesOfferingId { get { return this.reservedDBInstancesOfferingId; } set { this.reservedDBInstancesOfferingId = value; } } /// <summary> /// Sets the ReservedDBInstancesOfferingId property /// </summary> /// <param name="reservedDBInstancesOfferingId">The value to set for the ReservedDBInstancesOfferingId property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public DescribeReservedDBInstancesRequest WithReservedDBInstancesOfferingId(string reservedDBInstancesOfferingId) { this.reservedDBInstancesOfferingId = reservedDBInstancesOfferingId; return this; } // Check to see if ReservedDBInstancesOfferingId property is set internal bool IsSetReservedDBInstancesOfferingId() { return this.reservedDBInstancesOfferingId != null; } /// <summary> /// The DB Instance class filter value. Specify this parameter to show only those reservations matching the specified DB Instances class. /// /// </summary> public string DBInstanceClass { get { return this.dBInstanceClass; } set { this.dBInstanceClass = value; } } /// <summary> /// Sets the DBInstanceClass property /// </summary> /// <param name="dBInstanceClass">The value to set for the DBInstanceClass property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public DescribeReservedDBInstancesRequest WithDBInstanceClass(string dBInstanceClass) { this.dBInstanceClass = dBInstanceClass; return this; } // Check to see if DBInstanceClass property is set internal bool IsSetDBInstanceClass() { return this.dBInstanceClass != null; } /// <summary> /// The duration filter value, specified in years or seconds. Specify this parameter to show only reservations for this duration. Valid Values: /// <c>1 | 3 | 31536000 | 94608000</c> /// /// </summary> public string Duration { get { return this.duration; } set { this.duration = value; } } /// <summary> /// Sets the Duration property /// </summary> /// <param name="duration">The value to set for the Duration property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public DescribeReservedDBInstancesRequest WithDuration(string duration) { this.duration = duration; return this; } // Check to see if Duration property is set internal bool IsSetDuration() { return this.duration != null; } /// <summary> /// The product description filter value. Specify this parameter to show only those reservations matching the specified product description. /// /// </summary> public string ProductDescription { get { return this.productDescription; } set { this.productDescription = value; } } /// <summary> /// Sets the ProductDescription property /// </summary> /// <param name="productDescription">The value to set for the ProductDescription property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public DescribeReservedDBInstancesRequest WithProductDescription(string productDescription) { this.productDescription = productDescription; return this; } // Check to see if ProductDescription property is set internal bool IsSetProductDescription() { return this.productDescription != null; } /// <summary> /// The offering type filter value. Specify this parameter to show only the available offerings matching the specified offering type. Valid /// Values: <c>"Light Utilization" | "Medium Utilization" | "Heavy Utilization" </c> /// /// </summary> public string OfferingType { get { return this.offeringType; } set { this.offeringType = value; } } /// <summary> /// Sets the OfferingType property /// </summary> /// <param name="offeringType">The value to set for the OfferingType property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public DescribeReservedDBInstancesRequest WithOfferingType(string offeringType) { this.offeringType = offeringType; return this; } // Check to see if OfferingType property is set internal bool IsSetOfferingType() { return this.offeringType != null; } /// <summary> /// The Multi-AZ filter value. Specify this parameter to show only those reservations matching the specified Multi-AZ parameter. /// /// </summary> public bool MultiAZ { get { return this.multiAZ ?? default(bool); } set { this.multiAZ = value; } } /// <summary> /// Sets the MultiAZ property /// </summary> /// <param name="multiAZ">The value to set for the MultiAZ property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public DescribeReservedDBInstancesRequest WithMultiAZ(bool multiAZ) { this.multiAZ = multiAZ; return this; } // Check to see if MultiAZ property is set internal bool IsSetMultiAZ() { return this.multiAZ.HasValue; } /// <summary> /// The maximum number of records to include in the response. If more than the <c>MaxRecords</c> value is available, a pagination token called a /// marker is included in the response so that the following results can be retrieved. Default: 100 Constraints: minimum 20, maximum 100 /// /// </summary> public int MaxRecords { get { return this.maxRecords ?? default(int); } set { this.maxRecords = value; } } /// <summary> /// Sets the MaxRecords property /// </summary> /// <param name="maxRecords">The value to set for the MaxRecords property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public DescribeReservedDBInstancesRequest WithMaxRecords(int maxRecords) { this.maxRecords = maxRecords; return this; } // Check to see if MaxRecords property is set internal bool IsSetMaxRecords() { return this.maxRecords.HasValue; } /// <summary> /// An optional pagination token provided by a previous request. If this parameter is specified, the response includes only records beyond the /// marker, up to the value specified by <c>MaxRecords</c>. /// /// </summary> public string Marker { get { return this.marker; } set { this.marker = value; } } /// <summary> /// Sets the Marker property /// </summary> /// <param name="marker">The value to set for the Marker property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public DescribeReservedDBInstancesRequest WithMarker(string marker) { this.marker = marker; return this; } // Check to see if Marker property is set internal bool IsSetMarker() { return this.marker != null; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics.Contracts; using System.Security; namespace System.Text { // Shared implementations for commonly overriden Encoding methods internal static class EncodingForwarder { // We normally have to duplicate a lot of code between UTF8Encoding, // UTF7Encoding, EncodingNLS, etc. because we want to override many // of the methods in all of those classes to just forward to the unsafe // version. (e.g. GetBytes(char[])) // Ideally, everything would just derive from EncodingNLS, but that's // not exposed in the public API, and C# prohibits a public class from // inheriting from an internal one. So, we have to override each of the // methods in question and repeat the argument validation/logic. // These set of methods exist so instead of duplicating code, we can // simply have those overriden methods call here to do the actual work. // NOTE: This class should ONLY be called from Encodings that override // the internal methods which accept an Encoder/DecoderNLS. The reason // for this is that by default, those methods just call the same overload // except without the encoder/decoder parameter. If an overriden method // without that parameter calls this class, which calls the overload with // the parameter, it will call the same method again, which will eventually // lead to a StackOverflowException. [SecuritySafeCritical] public unsafe static int GetByteCount(Encoding encoding, char[] chars, int index, int count) { // Validate parameters Contract.Assert(encoding != null); // this parameter should only be affected internally, so just do a debug check here if (chars == null) { throw new ArgumentNullException("chars", Environment.GetResourceString("ArgumentNull_Array")); } if (index < 0 || count < 0) { throw new ArgumentOutOfRangeException(index < 0 ? "index" : "count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); } if (chars.Length - index < count) { throw new ArgumentOutOfRangeException("chars", Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer")); } Contract.EndContractBlock(); // If no input, return 0, avoid fixed empty array problem if (count == 0) return 0; // Just call the (internal) pointer version fixed (char* pChars = chars) return encoding.GetByteCount(pChars + index, count, encoder: null); } [SecuritySafeCritical] public unsafe static int GetByteCount(Encoding encoding, string s) { Contract.Assert(encoding != null); if (s == null) { string paramName = encoding is ASCIIEncoding ? "chars" : "s"; // ASCIIEncoding calls the string chars // UTF8Encoding does this as well, but it originally threw an ArgumentNull for "s" so don't check for that throw new ArgumentNullException(paramName); } Contract.EndContractBlock(); // NOTE: The behavior of fixed *is* defined by // the spec for empty strings, although not for // null strings/empty char arrays. See // http://stackoverflow.com/q/37757751/4077294 // Regardless, we may still want to check // for if (s.Length == 0) in the future // and short-circuit as an optimization (TODO). fixed (char* pChars = s) return encoding.GetByteCount(pChars, s.Length, encoder: null); } [SecurityCritical] public unsafe static int GetByteCount(Encoding encoding, char* chars, int count) { Contract.Assert(encoding != null); if (chars == null) { throw new ArgumentNullException("chars", Environment.GetResourceString("ArgumentNull_Array")); } if (count < 0) { throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); } Contract.EndContractBlock(); // Call the internal version, with an empty encoder return encoding.GetByteCount(chars, count, encoder: null); } [SecuritySafeCritical] public unsafe static int GetBytes(Encoding encoding, string s, int charIndex, int charCount, byte[] bytes, int byteIndex) { Contract.Assert(encoding != null); if (s == null || bytes == null) { string stringName = encoding is ASCIIEncoding ? "chars" : "s"; // ASCIIEncoding calls the first parameter chars throw new ArgumentNullException(s == null ? stringName : "bytes", Environment.GetResourceString("ArgumentNull_Array")); } if (charIndex < 0 || charCount < 0) { throw new ArgumentOutOfRangeException(charIndex < 0 ? "charIndex" : "charCount", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); } if (s.Length - charIndex < charCount) { string stringName = encoding is ASCIIEncoding ? "chars" : "s"; // ASCIIEncoding calls the first parameter chars // Duplicate the above check since we don't want the overhead of a type check on the general path throw new ArgumentOutOfRangeException(stringName, Environment.GetResourceString("ArgumentOutOfRange_IndexCount")); } if (byteIndex < 0 || byteIndex > bytes.Length) { throw new ArgumentOutOfRangeException("byteIndex", Environment.GetResourceString("ArgumentOutOfRange_Index")); } Contract.EndContractBlock(); int byteCount = bytes.Length - byteIndex; // Fixed doesn't like empty arrays if (bytes.Length == 0) bytes = new byte[1]; fixed (char* pChars = s) fixed (byte* pBytes = bytes) { return encoding.GetBytes(pChars + charIndex, charCount, pBytes + byteIndex, byteCount, encoder: null); } } [SecuritySafeCritical] public unsafe static int GetBytes(Encoding encoding, char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex) { Contract.Assert(encoding != null); if (chars == null || bytes == null) { throw new ArgumentNullException(chars == null ? "chars" : "bytes", Environment.GetResourceString("ArgumentNull_Array")); } if (charIndex < 0 || charCount < 0) { throw new ArgumentOutOfRangeException(charIndex < 0 ? "charIndex" : "charCount", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); } if (chars.Length - charIndex < charCount) { throw new ArgumentOutOfRangeException("chars", Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer")); } if (byteIndex < 0 || byteIndex > bytes.Length) { throw new ArgumentOutOfRangeException("byteIndex", Environment.GetResourceString("ArgumentOutOfRange_Index")); } Contract.EndContractBlock(); // If nothing to encode return 0, avoid fixed problem if (charCount == 0) return 0; // Note that this is the # of bytes to decode, // not the size of the array int byteCount = bytes.Length - byteIndex; // Fixed doesn't like 0 length arrays. if (bytes.Length == 0) bytes = new byte[1]; // Just call the (internal) pointer version fixed (char* pChars = chars) fixed (byte* pBytes = bytes) { return encoding.GetBytes(pChars + charIndex, charCount, pBytes + byteIndex, byteCount, encoder: null); } } [SecurityCritical] public unsafe static int GetBytes(Encoding encoding, char* chars, int charCount, byte* bytes, int byteCount) { Contract.Assert(encoding != null); if (bytes == null || chars == null) { throw new ArgumentNullException(bytes == null ? "bytes" : "chars", Environment.GetResourceString("ArgumentNull_Array")); } if (charCount < 0 || byteCount < 0) { throw new ArgumentOutOfRangeException(charCount < 0 ? "charCount" : "byteCount", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); } Contract.EndContractBlock(); return encoding.GetBytes(chars, charCount, bytes, byteCount, encoder: null); } [SecuritySafeCritical] public unsafe static int GetCharCount(Encoding encoding, byte[] bytes, int index, int count) { Contract.Assert(encoding != null); if (bytes == null) { throw new ArgumentNullException("bytes", Environment.GetResourceString("ArgumentNull_Array")); } if (index < 0 || count < 0) { throw new ArgumentOutOfRangeException(index < 0 ? "index" : "count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); } if (bytes.Length - index < count) { throw new ArgumentOutOfRangeException("bytes", Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer")); } Contract.EndContractBlock(); // If no input just return 0, fixed doesn't like 0 length arrays. if (count == 0) return 0; // Just call pointer version fixed (byte* pBytes = bytes) return encoding.GetCharCount(pBytes + index, count, decoder: null); } [SecurityCritical] public unsafe static int GetCharCount(Encoding encoding, byte* bytes, int count) { Contract.Assert(encoding != null); if (bytes == null) { throw new ArgumentNullException("bytes", Environment.GetResourceString("ArgumentNull_Array")); } if (count < 0) { throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); } Contract.EndContractBlock(); return encoding.GetCharCount(bytes, count, decoder: null); } [SecuritySafeCritical] public unsafe static int GetChars(Encoding encoding, byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) { Contract.Assert(encoding != null); if (bytes == null || chars == null) { throw new ArgumentNullException(bytes == null ? "bytes" : "chars", Environment.GetResourceString("ArgumentNull_Array")); } if (byteIndex < 0 || byteCount < 0) { throw new ArgumentOutOfRangeException(byteIndex < 0 ? "byteIndex" : "byteCount", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); } if (bytes.Length - byteIndex < byteCount) { throw new ArgumentOutOfRangeException("bytes", Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer")); } if (charIndex < 0 || charIndex > chars.Length) { throw new ArgumentOutOfRangeException("charIndex", Environment.GetResourceString("ArgumentOutOfRange_Index")); } Contract.EndContractBlock(); if (byteCount == 0) return 0; // NOTE: This is the # of chars we can decode, // not the size of the array int charCount = chars.Length - charIndex; // Fixed doesn't like 0 length arrays. if (chars.Length == 0) chars = new char[1]; fixed (byte* pBytes = bytes) fixed (char* pChars = chars) { return encoding.GetChars(pBytes + byteIndex, byteCount, pChars + charIndex, charCount, decoder: null); } } [SecurityCritical] public unsafe static int GetChars(Encoding encoding, byte* bytes, int byteCount, char* chars, int charCount) { Contract.Assert(encoding != null); if (bytes == null || chars == null) { throw new ArgumentNullException(bytes == null ? "bytes" : "chars", Environment.GetResourceString("ArgumentNull_Array")); } if (charCount < 0 || byteCount < 0) { throw new ArgumentOutOfRangeException(charCount < 0 ? "charCount" : "byteCount", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); } Contract.EndContractBlock(); return encoding.GetChars(bytes, byteCount, chars, charCount, decoder: null); } [SecuritySafeCritical] public unsafe static string GetString(Encoding encoding, byte[] bytes, int index, int count) { Contract.Assert(encoding != null); if (bytes == null) { throw new ArgumentNullException("bytes", Environment.GetResourceString("ArgumentNull_Array")); } if (index < 0 || count < 0) { // ASCIIEncoding has different names for its parameters here (byteIndex, byteCount) bool ascii = encoding is ASCIIEncoding; string indexName = ascii ? "byteIndex" : "index"; string countName = ascii ? "byteCount" : "count"; throw new ArgumentOutOfRangeException(index < 0 ? indexName : countName, Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); } if (bytes.Length - index < count) { throw new ArgumentOutOfRangeException("bytes", Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer")); } Contract.EndContractBlock(); // Avoid problems with empty input buffer if (count == 0) return string.Empty; // Call string.CreateStringFromEncoding here, which // allocates a string and lets the Encoding modify // it in place. This way, we don't have to allocate // an intermediary char[] to decode into and then // call the string constructor; instead we decode // directly into the string. fixed (byte* pBytes = bytes) { return string.CreateStringFromEncoding(pBytes + index, count, encoding); } } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace GotLcg.Web.Api.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
// This file was created automatically, do not modify the contents of this file. // ReSharper disable InvalidXmlDocComment // ReSharper disable InconsistentNaming // ReSharper disable CheckNamespace // ReSharper disable MemberCanBePrivate.Global using System; using System.Runtime.InteropServices; // Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Core\Public\Math\CurveEdInterface.h:10 namespace UnrealEngine { public partial class FCurveEdInterface : NativeStructWrapper { public FCurveEdInterface(IntPtr NativePointer, bool IsRef = false) : base(NativePointer, IsRef) { } public FCurveEdInterface() : base(E_CreateStruct_FCurveEdInterface(), false) { } #region DLLInmport [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr E_CreateStruct_FCurveEdInterface(); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern int E_FCurveEdInterface_CreateNewKey(IntPtr self, float keyIn); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_FCurveEdInterface_DeleteKey(IntPtr self, int keyIndex); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern float E_FCurveEdInterface_EvalSub(IntPtr self, int subIndex, float inVal); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_FCurveEdInterface_GetInRange(IntPtr self, float minIn, float maxIn); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern float E_FCurveEdInterface_GetKeyIn(IntPtr self, int keyIndex); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern byte E_FCurveEdInterface_GetKeyInterpMode(IntPtr self, int keyIndex); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern float E_FCurveEdInterface_GetKeyOut(IntPtr self, int subIndex, int keyIndex); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern int E_FCurveEdInterface_GetNumKeys(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern int E_FCurveEdInterface_GetNumSubCurves(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_FCurveEdInterface_GetOutRange(IntPtr self, float minOut, float maxOut); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_FCurveEdInterface_GetTangents(IntPtr self, int subIndex, int keyIndex, float arriveTangent, float leaveTangent); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern int E_FCurveEdInterface_SetKeyIn(IntPtr self, int keyIndex, float newInVal); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_FCurveEdInterface_SetKeyInterpMode(IntPtr self, int keyIndex, byte newMode); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_FCurveEdInterface_SetKeyOut(IntPtr self, int subIndex, int keyIndex, float newOutVal); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_FCurveEdInterface_SetTangents(IntPtr self, int subIndex, int keyIndex, float arriveTangent, float leaveTangent); #endregion #region ExternMethods /// <summary> /// Add a new key to the curve with the specified input. Its initial value is set using EvalSub at that location. /// <para>Returns the index of the new key. </para> /// </summary> public virtual int CreateNewKey(float keyIn) => E_FCurveEdInterface_CreateNewKey(this, keyIn); /// <summary> /// Remove the specified key from the curve. /// <para>KeyIndex must be within range ie >=0 and < NumKeys. </para> /// </summary> public virtual void DeleteKey(int keyIndex) => E_FCurveEdInterface_DeleteKey(this, keyIndex); /// <summary> /// Evaluate a subcurve at an arbitary point. Outside the keyframe range, curves are assumed to continue their end values. /// </summary> public virtual float EvalSub(int subIndex, float inVal) => E_FCurveEdInterface_EvalSub(this, subIndex, inVal); /// <summary> /// Get input range of keys. Outside this region curve continues constantly the start/end values. /// </summary> public virtual void GetInRange(float minIn, float maxIn) => E_FCurveEdInterface_GetInRange(this, minIn, maxIn); /// <summary> /// Get the input value for the Key with the specified index. KeyIndex must be within range ie >=0 and < NumKeys. /// </summary> public virtual float GetKeyIn(int keyIndex) => E_FCurveEdInterface_GetKeyIn(this, keyIndex); /// <summary> /// Get the interpolation mode of the specified keyframe. This can be CIM_Constant, CIM_Linear or CIM_Curve. /// <para>KeyIndex must be within range ie >=0 and < NumKeys. </para> /// </summary> public virtual EInterpCurveMode GetKeyInterpMode(int keyIndex) => (EInterpCurveMode)E_FCurveEdInterface_GetKeyInterpMode(this, keyIndex); /// <summary> /// Get the output value for the key with the specified index on the specified sub-curve. /// <para>SubIndex must be within range ie >=0 and < NumSubCurves. </para> /// KeyIndex must be within range ie >=0 and < NumKeys. /// </summary> public virtual float GetKeyOut(int subIndex, int keyIndex) => E_FCurveEdInterface_GetKeyOut(this, subIndex, keyIndex); /// <summary> /// Get number of keyframes in curve. /// </summary> public virtual int GetNumKeys() => E_FCurveEdInterface_GetNumKeys(this); /// <summary> /// Get number of 'sub curves' in this Curve. For example, a vector curve will have 3 sub-curves, for X, Y and Z. /// </summary> public virtual int GetNumSubCurves() => E_FCurveEdInterface_GetNumSubCurves(this); /// <summary> /// Get overall range of output values. /// </summary> public virtual void GetOutRange(float minOut, float maxOut) => E_FCurveEdInterface_GetOutRange(this, minOut, maxOut); /// <summary> /// Get the incoming and outgoing tangent for the given subcurve and key. /// <para>SubIndex must be within range ie >=0 and < NumSubCurves. </para> /// KeyIndex must be within range ie >=0 and < NumKeys. /// </summary> public virtual void GetTangents(int subIndex, int keyIndex, float arriveTangent, float leaveTangent) => E_FCurveEdInterface_GetTangents(this, subIndex, keyIndex, arriveTangent, leaveTangent); /// <summary> /// Set the input value of the specified Key. This may change the index of the key, so the new index of the key is retured. /// <para>KeyIndex must be within range ie >=0 and < NumKeys. </para> /// </summary> public virtual int SetKeyIn(int keyIndex, float newInVal) => E_FCurveEdInterface_SetKeyIn(this, keyIndex, newInVal); /// <summary> /// Set the method to use for interpolating between the give keyframe and the next one. /// <para>KeyIndex must be within range ie >=0 and < NumKeys. </para> /// </summary> public virtual void SetKeyInterpMode(int keyIndex, EInterpCurveMode newMode) => E_FCurveEdInterface_SetKeyInterpMode(this, keyIndex, (byte)newMode); /// <summary> /// Set the output values of the specified key. /// <para>SubIndex must be within range ie >=0 and < NumSubCurves. </para> /// KeyIndex must be within range ie >=0 and < NumKeys. /// </summary> public virtual void SetKeyOut(int subIndex, int keyIndex, float newOutVal) => E_FCurveEdInterface_SetKeyOut(this, subIndex, keyIndex, newOutVal); /// <summary> /// Set the incoming and outgoing tangent for the given subcurve and key. /// <para>SubIndex must be within range ie >=0 and < NumSubCurves. </para> /// KeyIndex must be within range ie >=0 and < NumKeys. /// </summary> public virtual void SetTangents(int subIndex, int keyIndex, float arriveTangent, float leaveTangent) => E_FCurveEdInterface_SetTangents(this, subIndex, keyIndex, arriveTangent, leaveTangent); #endregion public static implicit operator IntPtr(FCurveEdInterface self) { return self?.NativePointer ?? IntPtr.Zero; } public static implicit operator FCurveEdInterface(IntPtr adress) { return adress == IntPtr.Zero ? null : new FCurveEdInterface(adress, false); } } }
/* * 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 NUnit.Framework; using org.apache.juddi.v3.client.util; using org.uddi.apiv3; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace juddi_client.net.test.org.apache.juddi.client.test { [TestFixture] public class TModelInstanceDetailsComparatorTest { /** * Test of compare method, of class TModelInstanceDetailsComparator. */ [Test] [ExpectedException(typeof(ArgumentNullException))] public void testCompareToNulls() { System.Console.Out.WriteLine("TModelInstanceDetailsComparator.compare nulls"); tModelInstanceInfo[] lhs = null; tModelInstanceInfo[] rhs = null; TModelInstanceDetailsComparator instance = new TModelInstanceDetailsComparator(null, true, false, false); int expResult = 0; int result = instance.compare(lhs, rhs); } [Test] [ExpectedException(typeof(ArgumentOutOfRangeException))] public void testCompareToNulls2() { System.Console.Out.WriteLine("TModelInstanceDetailsComparator.compare nulls2"); tModelInstanceInfo[] lhs = null; tModelInstanceInfo[] rhs = null; TModelInstanceDetailsComparator instance = new TModelInstanceDetailsComparator("hi", true, true, false); int expResult = 0; int result = instance.compare(lhs, rhs); } [Test] [ExpectedException(typeof(ArgumentOutOfRangeException))] public void testCompareToNulls3() { System.Console.Out.WriteLine("TModelInstanceDetailsComparator.compare nulls3"); tModelInstanceInfo[] lhs = null; tModelInstanceInfo[] rhs = null; TModelInstanceDetailsComparator instance = new TModelInstanceDetailsComparator("hi", true, false, true); int expResult = 0; int result = instance.compare(lhs, rhs); } [Test] [ExpectedException(typeof(ArgumentOutOfRangeException))] public void testCompareToNulls4() { System.Console.Out.WriteLine("TModelInstanceDetailsComparator.compare nulls4"); tModelInstanceInfo[] lhs = null; tModelInstanceInfo[] rhs = null; TModelInstanceDetailsComparator instance = new TModelInstanceDetailsComparator("hi", false, true, true); int expResult = 0; int result = instance.compare(lhs, rhs); } [Test] [ExpectedException(typeof(ArgumentOutOfRangeException))] public void testCompareToNulls5() { System.Console.Out.WriteLine("TModelInstanceDetailsComparator.compare nulls5"); tModelInstanceInfo[] lhs = new tModelInstanceInfo[1] { new tModelInstanceInfo() }; tModelInstanceInfo[] rhs = new tModelInstanceInfo[1] { new tModelInstanceInfo() }; TModelInstanceDetailsComparator instance = new TModelInstanceDetailsComparator("hi", true, false, false); int expResult = 0; int result = instance.compare(lhs, rhs); } [Test] [ExpectedException(typeof(ArgumentOutOfRangeException))] public void testCompareToNulls6() { System.Console.Out.WriteLine("TModelInstanceDetailsComparator.compare nulls6"); tModelInstanceInfo[] lhs = new tModelInstanceInfo[1] { new tModelInstanceInfo() }; tModelInstanceInfo[] rhs = new tModelInstanceInfo[1] { new tModelInstanceInfo() }; TModelInstanceDetailsComparator instance = new TModelInstanceDetailsComparator("hi", true, false, false); int expResult = 0; int result = instance.compare(lhs, rhs); } [Test] [ExpectedException(typeof(ArgumentOutOfRangeException))] public void testCompareToNulls7() { System.Console.Out.WriteLine("TModelInstanceDetailsComparator.compare nulls7"); tModelInstanceInfo[] lhs = new tModelInstanceInfo[1] { new tModelInstanceInfo() }; tModelInstanceInfo[] rhs = new tModelInstanceInfo[1] { new tModelInstanceInfo() }; TModelInstanceDetailsComparator instance = new TModelInstanceDetailsComparator("hi", true, false, false); int expResult = 0; int result = instance.compare(lhs, rhs); } [Test] [ExpectedException(typeof(ArgumentNullException))] public void testCompareToNulls8() { System.Console.Out.WriteLine("TModelInstanceDetailsComparator.compare nulls8"); tModelInstanceInfo[] lhs = null; tModelInstanceInfo[] rhs = null; TModelInstanceDetailsComparator instance = new TModelInstanceDetailsComparator("hi", true, false, false); int expResult = 0; int result = instance.compare(lhs, rhs); } [Test] [ExpectedException(typeof(ArgumentOutOfRangeException))] public void testCompareToNotFound() { System.Console.Out.WriteLine("TModelInstanceDetailsComparator.compare notfound"); tModelInstanceInfo[] lhs = new tModelInstanceInfo[1] { new tModelInstanceInfo() }; lhs[0].tModelKey = ("asd"); tModelInstanceInfo[] rhs = new tModelInstanceInfo[1] { new tModelInstanceInfo() }; rhs[0].tModelKey = ("asd"); rhs[0].instanceDetails = new instanceDetails(); TModelInstanceDetailsComparator instance = new TModelInstanceDetailsComparator("hi", true, false, false); int expResult = 0; int result = instance.compare(lhs, rhs); } [Test] [ExpectedException(typeof(ArgumentOutOfRangeException))] public void testCompareToNoData() { System.Console.Out.WriteLine("TModelInstanceDetailsComparator.compare testCompareToNoData"); tModelInstanceInfo[] lhs = new tModelInstanceInfo[1] { new tModelInstanceInfo() }; lhs[0].tModelKey = ("hi"); lhs[0].instanceDetails = new instanceDetails(); tModelInstanceInfo[] rhs = new tModelInstanceInfo[1] { new tModelInstanceInfo() }; rhs[0].tModelKey = ("hi"); rhs[0].instanceDetails = new instanceDetails(); TModelInstanceDetailsComparator instance = new TModelInstanceDetailsComparator("hi", true, false, false); int expResult = 0; int result = instance.compare(lhs, rhs); } [Test] [ExpectedException(typeof(ArgumentOutOfRangeException))] public void testCompareToLHSNull() { System.Console.Out.WriteLine("TModelInstanceDetailsComparator.compare testCompareToLHSNull"); tModelInstanceInfo[] lhs = new tModelInstanceInfo[1] { new tModelInstanceInfo() }; lhs[0].tModelKey = ("hi"); lhs[0].instanceDetails = new instanceDetails(); tModelInstanceInfo[] rhs = new tModelInstanceInfo[1] { new tModelInstanceInfo() }; rhs[0].tModelKey = ("hi"); rhs[0].instanceDetails = new instanceDetails(); rhs[0].instanceDetails.instanceParms = ("xyz"); TModelInstanceDetailsComparator instance = new TModelInstanceDetailsComparator("hi", true, false, false); int expResult = 0; int result = instance.compare(lhs, rhs); } [Test] [ExpectedException(typeof(System.ArgumentOutOfRangeException))] public void testCompareToRHSNull() { System.Console.Out.WriteLine("TModelInstanceDetailsComparator.compare testCompareToRHSNull"); tModelInstanceInfo[] lhs = new tModelInstanceInfo[1] { new tModelInstanceInfo() }; lhs[0].tModelKey = ("hi"); lhs[0].instanceDetails = new instanceDetails(); lhs[0].instanceDetails.instanceParms = ("xyz"); tModelInstanceInfo[] rhs = new tModelInstanceInfo[1] { new tModelInstanceInfo() }; rhs[0].tModelKey = ("hi"); rhs[0].instanceDetails = new instanceDetails(); //rhs[0].instanceDetails.instanceParms=("xyz"); TModelInstanceDetailsComparator instance = new TModelInstanceDetailsComparator("hi", true, false, false); int expResult = 0; int result = instance.compare(lhs, rhs); } [Test] [ExpectedException(typeof(FormatException))] public void testCompareToNotNumberData() { System.Console.Out.WriteLine("TModelInstanceDetailsComparator.compare testCompareToNotNumberData"); tModelInstanceInfo[] lhs = new tModelInstanceInfo[1] { new tModelInstanceInfo() }; lhs[0].tModelKey = ("hi"); lhs[0].instanceDetails = new instanceDetails(); lhs[0].instanceDetails.instanceParms = ("xyz"); tModelInstanceInfo[] rhs = new tModelInstanceInfo[1] { new tModelInstanceInfo() }; rhs[0].tModelKey = ("hi"); rhs[0].instanceDetails = new instanceDetails(); rhs[0].instanceDetails.instanceParms = ("xyz"); TModelInstanceDetailsComparator instance = new TModelInstanceDetailsComparator("hi", true, false, false); int expResult = 0; int result = instance.compare(lhs, rhs); } [Test] public void testCompareToNumberDataEquals() { System.Console.Out.WriteLine("TModelInstanceDetailsComparator.compare testCompareToNumberDataEquals"); tModelInstanceInfo[] lhs = new tModelInstanceInfo[1] { new tModelInstanceInfo() }; lhs[0].tModelKey = ("hi"); lhs[0].instanceDetails = new instanceDetails(); lhs[0].instanceDetails.instanceParms = ("3.14"); tModelInstanceInfo[] rhs = new tModelInstanceInfo[1] { new tModelInstanceInfo() }; rhs[0].tModelKey = ("hi"); rhs[0].instanceDetails = new instanceDetails(); rhs[0].instanceDetails.instanceParms = ("3.14"); TModelInstanceDetailsComparator instance = new TModelInstanceDetailsComparator("hi", true, false, false); int expResult = 0; int result = instance.compare(lhs, rhs); Assert.AreEqual(expResult, result, "result " + result); } [Test] public void testCompareToNumberDataGT() { System.Console.Out.WriteLine("TModelInstanceDetailsComparator.compare testCompareToNumberDataGT"); tModelInstanceInfo[] lhs = new tModelInstanceInfo[1] { new tModelInstanceInfo() }; lhs[0].tModelKey = ("hi"); lhs[0].instanceDetails = new instanceDetails(); lhs[0].instanceDetails.instanceParms = ("3.15"); tModelInstanceInfo[] rhs = new tModelInstanceInfo[1] { new tModelInstanceInfo() }; rhs[0].tModelKey = ("hi"); rhs[0].instanceDetails = new instanceDetails(); rhs[0].instanceDetails.instanceParms = ("3.14"); TModelInstanceDetailsComparator instance = new TModelInstanceDetailsComparator("hi", true, false, false); int result = instance.compare(lhs, rhs); Assert.True(result > 0, "result " + result); } [Test] public void testCompareToNumberDataLT() { System.Console.Out.WriteLine("TModelInstanceDetailsComparator.compare testCompareToNumberDataLT"); tModelInstanceInfo[] lhs = new tModelInstanceInfo[1] { new tModelInstanceInfo() }; lhs[0].tModelKey = ("hi"); lhs[0].instanceDetails = new instanceDetails(); lhs[0].instanceDetails.instanceParms = ("3.10"); tModelInstanceInfo[] rhs = new tModelInstanceInfo[1] { new tModelInstanceInfo() }; rhs[0].tModelKey = ("hi"); rhs[0].instanceDetails = new instanceDetails(); rhs[0].instanceDetails.instanceParms = ("3.14"); TModelInstanceDetailsComparator instance = new TModelInstanceDetailsComparator("hi", true, false, false); int result = instance.compare(lhs, rhs); Assert.True(result < 0, "result " + result); } [Test] [ExpectedException(typeof(System.FormatException))] public void testCompareToDate() { System.Console.Out.WriteLine("TModelInstanceDetailsComparator.compare testCompareToDate"); tModelInstanceInfo[] lhs = new tModelInstanceInfo[1] { new tModelInstanceInfo() }; lhs[0].tModelKey = ("hi"); lhs[0].instanceDetails = new instanceDetails(); lhs[0].instanceDetails.instanceParms = ("asdasd"); tModelInstanceInfo[] rhs = new tModelInstanceInfo[1] { new tModelInstanceInfo() }; rhs[0].tModelKey = ("hi"); rhs[0].instanceDetails = new instanceDetails(); rhs[0].instanceDetails.instanceParms = ("asdasdasd"); TModelInstanceDetailsComparator instance = new TModelInstanceDetailsComparator("hi", false, true, false); int result = instance.compare(lhs, rhs); //Assert.assertTrue("result " + result,result < 0); } [Test] public void testCompareToDateGT() { System.Console.Out.WriteLine("TModelInstanceDetailsComparator.compare testCompareToDateGT"); tModelInstanceInfo[] lhs = new tModelInstanceInfo[1] { new tModelInstanceInfo() }; lhs[0].tModelKey = ("hi"); lhs[0].instanceDetails = new instanceDetails(); lhs[0].instanceDetails.instanceParms = ("2006-05-30T09:30:10-06:00"); tModelInstanceInfo[] rhs = new tModelInstanceInfo[1] { new tModelInstanceInfo() }; rhs[0].tModelKey = ("hi"); rhs[0].instanceDetails = new instanceDetails(); rhs[0].instanceDetails.instanceParms = ("2004-05-30T09:30:10-06:00"); TModelInstanceDetailsComparator instance = new TModelInstanceDetailsComparator("hi", false, true, false); int result = instance.compare(lhs, rhs); Assert.True(result > 0, "result " + lhs[0].instanceDetails.instanceParms + " compare to " + rhs[0].instanceDetails.instanceParms + " " + result); } [Test] public void testCompareToDateLT() { System.Console.Out.WriteLine("TModelInstanceDetailsComparator.compare testCompareToDateLT"); tModelInstanceInfo[] lhs = new tModelInstanceInfo[1] { new tModelInstanceInfo() }; lhs[0].tModelKey = ("hi"); lhs[0].instanceDetails = new instanceDetails(); lhs[0].instanceDetails.instanceParms = ("2002-05-30T09:30:10-06:00"); tModelInstanceInfo[] rhs = new tModelInstanceInfo[1] { new tModelInstanceInfo() }; rhs[0].tModelKey = ("hi"); rhs[0].instanceDetails = new instanceDetails(); rhs[0].instanceDetails.instanceParms = ("2005-05-30T09:30:10-06:00"); TModelInstanceDetailsComparator instance = new TModelInstanceDetailsComparator("hi", false, true, false); int result = instance.compare(lhs, rhs); Assert.True(result < 0, "result " + lhs[0].instanceDetails.instanceParms + " compare to " + rhs[0].instanceDetails.instanceParms + " " + result); } [Test] public void testCompareToDateEQ() { System.Console.Out.WriteLine("TModelInstanceDetailsComparator.compare testCompareToDateEQ"); tModelInstanceInfo[] lhs = new tModelInstanceInfo[1] { new tModelInstanceInfo() }; lhs[0].tModelKey = ("hi"); lhs[0].instanceDetails = new instanceDetails(); lhs[0].instanceDetails.instanceParms = ("2002-05-30T09:30:10-06:00"); tModelInstanceInfo[] rhs = new tModelInstanceInfo[1] { new tModelInstanceInfo() }; rhs[0].tModelKey = ("hi"); rhs[0].instanceDetails = new instanceDetails(); rhs[0].instanceDetails.instanceParms = ("2002-05-30T09:30:10-06:00"); TModelInstanceDetailsComparator instance = new TModelInstanceDetailsComparator("hi", false, true, false); int result = instance.compare(lhs, rhs); Assert.True(result == 0, "result " + lhs[0].instanceDetails.instanceParms + " compare to " + rhs[0].instanceDetails.instanceParms + " " + result); } [Test] [ExpectedException(typeof(System.FormatException))] public void testCompareToDurationInvalid() { System.Console.Out.WriteLine("TModelInstanceDetailsComparator.compare testCompareToDurationInvalid"); tModelInstanceInfo[] lhs = new tModelInstanceInfo[1] { new tModelInstanceInfo() }; lhs[0].tModelKey = ("hi"); lhs[0].instanceDetails = new instanceDetails(); lhs[0].instanceDetails.instanceParms = ("asdasd"); tModelInstanceInfo[] rhs = new tModelInstanceInfo[1] { new tModelInstanceInfo() }; rhs[0].tModelKey = ("hi"); rhs[0].instanceDetails = new instanceDetails(); rhs[0].instanceDetails.instanceParms = ("asdasd"); TModelInstanceDetailsComparator instance = new TModelInstanceDetailsComparator("hi", false, false, true); int result = instance.compare(lhs, rhs); Assert.True(result == 0, "result " + result); } [Test] public void testCompareToDurationLT() { System.Console.Out.WriteLine("TModelInstanceDetailsComparator.compare testCompareToDurationLT"); tModelInstanceInfo[] lhs = new tModelInstanceInfo[1] { new tModelInstanceInfo() }; lhs[0].tModelKey = ("hi"); lhs[0].instanceDetails = new instanceDetails(); lhs[0].instanceDetails.instanceParms = ("P1Y"); tModelInstanceInfo[] rhs = new tModelInstanceInfo[1] { new tModelInstanceInfo() }; rhs[0].tModelKey = ("hi"); rhs[0].instanceDetails = new instanceDetails(); rhs[0].instanceDetails.instanceParms = ("P3Y"); TModelInstanceDetailsComparator instance = new TModelInstanceDetailsComparator("hi", false, false, true); int result = instance.compare(lhs, rhs); Assert.True(result < 0, "result " + lhs[0].instanceDetails.instanceParms + " compare to " + rhs[0].instanceDetails.instanceParms + " " + result); } [Test] public void testCompareToDurationGT() { System.Console.Out.WriteLine("TModelInstanceDetailsComparator.compare testCompareToDurationGT"); tModelInstanceInfo[] lhs = new tModelInstanceInfo[1] { new tModelInstanceInfo() }; lhs[0].tModelKey = ("hi"); lhs[0].instanceDetails = new instanceDetails(); lhs[0].instanceDetails.instanceParms = ("P5Y"); tModelInstanceInfo[] rhs = new tModelInstanceInfo[1] { new tModelInstanceInfo() }; rhs[0].tModelKey = ("hi"); rhs[0].instanceDetails = new instanceDetails(); rhs[0].instanceDetails.instanceParms = ("P2Y"); TModelInstanceDetailsComparator instance = new TModelInstanceDetailsComparator("hi", false, false, true); int result = instance.compare(lhs, rhs); Assert.True(result > 0, "result " + lhs[0].instanceDetails.instanceParms + " compare to " + rhs[0].instanceDetails.instanceParms + " " + result); } [Test] public void testCompareToDurationEQ() { System.Console.Out.WriteLine("TModelInstanceDetailsComparator.compare testCompareToDurationEQ"); tModelInstanceInfo[] lhs = new tModelInstanceInfo[1] { new tModelInstanceInfo() }; lhs[0].tModelKey = ("hi"); lhs[0].instanceDetails = new instanceDetails(); lhs[0].instanceDetails.instanceParms = ("P5Y"); tModelInstanceInfo[] rhs = new tModelInstanceInfo[1] { new tModelInstanceInfo() }; rhs[0].tModelKey = ("hi"); rhs[0].instanceDetails = new instanceDetails(); rhs[0].instanceDetails.instanceParms = ("P5Y"); TModelInstanceDetailsComparator instance = new TModelInstanceDetailsComparator("hi", false, false, true); int result = instance.compare(lhs, rhs); Assert.True(result == 0, "result " + lhs[0].instanceDetails.instanceParms + " compare to " + lhs[0].instanceDetails.instanceParms + " " + result); } } }
// <copyright file=OrphanFinder company=Hydra> // Copyright (c) 2015 All Rights Reserved // </copyright> // <author>Christopher Cameron</author> using System; using System.Collections.Generic; using System.IO; using Hydra.HydraCommon.Editor.Utils; using Hydra.HydraCommon.Utils; using UnityEditor; using UnityEngine; using Object = UnityEngine.Object; namespace Hydra.HydraCommon.Editor.Windows { /// <summary> /// OrphanFinder is a utility for finding orphaned assets. /// </summary> public class OrphanFinder : HydraEditorWindow { public const string TITLE = "Orphan Finder"; public const string GUID_PREFIX = "guid:"; private static GUIContent s_SearchLabel = new GUIContent("Search"); // Ignored directories private static string[] s_DirIgnore = {"ProjectSettings", "Resources", "ShaderForge"}; private static string[] s_ExtIgnore = {".js", ".cs", ".unity", ".txt", ".md", ".dll"}; private static Vector2 s_ScrollPosition; private static Dictionary<string, List<string>> s_CachedGuidDependencies; private static Dictionary<string, List<string>> s_CachedGuidParents; private static List<string> s_GuidOrphans; /// <summary> /// Initializes the class. /// </summary> static OrphanFinder() { s_CachedGuidDependencies = new Dictionary<string, List<string>>(); s_CachedGuidParents = new Dictionary<string, List<string>>(); s_GuidOrphans = new List<string>(); } /// <summary> /// Shows the window. /// </summary> [MenuItem(MENU + TITLE)] public static void Init() { GetWindow<OrphanFinder>(false, TITLE, true); } #region Messages /// <summary> /// Called to draw the window contents. /// </summary> protected override void OnGUI() { base.OnGUI(); EditorGUILayout.LabelField(string.Format("{0} orphaned assets", s_GuidOrphans.Count)); HydraEditorLayoutUtils.BeginBox(false); { s_ScrollPosition = EditorGUILayout.BeginScrollView(s_ScrollPosition, false, true); { for (int index = 0; index < s_GuidOrphans.Count; index++) DrawGuidRow(s_GuidOrphans[index], index); } EditorGUILayout.EndScrollView(); } HydraEditorLayoutUtils.EndBox(false); if (GUILayout.Button(s_SearchLabel)) Search(); } #endregion /// <summary> /// Draws the GUID row. /// </summary> private static void DrawGuidRow(string guid, int index) { string path = AssetDatabase.GUIDToAssetPath(guid); GUIStyle style = HydraEditorGUIStyles.ArrayElementStyle(index); Object selected = Selection.activeObject; string selectedPath = AssetDatabase.GetAssetPath(selected); if (selectedPath == path) style = HydraEditorGUIStyles.arrayElementSelectedStyle; GUILayout.BeginHorizontal(style); { if (!DrawDeleteButton(guid)) { DrawIcon(guid); if (GUILayout.Button(path, GUI.skin.label)) { Object asset = AssetDatabase.LoadAssetAtPath<Object>(path); Selection.activeObject = asset; EditorGUIUtility.PingObject(asset); } List<string> dependencies = s_CachedGuidDependencies[guid]; if (dependencies.Count > 0) { string dependenciesLabel = string.Format("{0} dependencies", dependencies.Count); GUILayout.Label(dependenciesLabel, HydraEditorGUIStyles.rightAlignedLabelStyle); } } } GUILayout.EndHorizontal(); } /// <summary> /// Draws the delete button. /// </summary> /// <param name="guid">GUID.</param> private static bool DrawDeleteButton(string guid) { bool pressed = GUILayout.Button("X", new GUIStyle("sv_label_6"), GUILayout.Width(24.0f)); if (pressed) Delete(guid); return pressed; } private static void DrawIcon(string guid) { string local = AssetDatabase.GUIDToAssetPath(guid); Texture icon = AssetDatabase.GetCachedIcon(local); if (icon == null) return; Rect position = EditorGUILayout.GetControlRect(false, GUILayout.Width(16.0f)); EditorGUI.DrawTextureTransparent(position, icon); } /// <summary> /// Search. /// </summary> private static void Search() { CacheDependencies(); CacheParents(); CacheOrphans(); EditorUtility.ClearProgressBar(); } private static void UpdateProgressBar(string label, int count) { string title = "Searching for Orphaned Assets"; label = string.Format("{0} {1}", label, count); float progress = ((float)EditorApplication.timeSinceStartup / 3.0f) % 1.0f; EditorUtility.DisplayProgressBar(title, label, progress); } /// <summary> /// Deletes the asset with the specified guid from disk. /// </summary> /// <param name="guid">GUID.</param> private static void Delete(string guid) { string local = AssetDatabase.GUIDToAssetPath(guid); // Remove from disk if (!AssetDatabase.DeleteAsset(local)) { Debug.LogWarning(string.Format("Couldn't delete {0}", local)); return; } // Clear empty directories string directory = Path.GetDirectoryName(local); MaintenanceUtils.RemoveEmptyDirectories(directory); // Update the cache List<string> dependencies = s_CachedGuidDependencies[guid]; s_CachedGuidDependencies.Remove(guid); s_GuidOrphans.Remove(guid); if (dependencies.Count == 0) return; CacheParents(); CacheOrphans(); EditorUtility.ClearProgressBar(); } /// <summary> /// Caches the dependencies. /// </summary> private static void CacheDependencies() { s_CachedGuidDependencies.Clear(); string[] paths = AssetDatabase.GetAllAssetPaths(); for (int index = 0; index < paths.Length; index++) { string path = paths[index]; if (!File.Exists(path)) continue; if (MaintenanceUtils.IsDirectory(path)) continue; if (!MaintenanceUtils.InAssetsDir(path)) continue; List<string> dependencies = new List<string>(); GetDependencies(path, dependencies); string guid = AssetDatabase.AssetPathToGUID(path); s_CachedGuidDependencies[guid] = dependencies; UpdateProgressBar("Caching dependencies:", index + 1); } } /// <summary> /// Caches the parents. /// </summary> private static void CacheParents() { s_CachedGuidParents.Clear(); int count = 0; foreach (KeyValuePair<string, List<string>> pair in s_CachedGuidDependencies) { string guid = pair.Key; if (!s_CachedGuidParents.ContainsKey(guid)) s_CachedGuidParents[guid] = new List<string>(); List<string> dependencies = pair.Value; for (int index = 0; index < dependencies.Count; index++) { string dependent = dependencies[index]; if (dependent == guid) continue; if (!s_CachedGuidParents.ContainsKey(dependent)) s_CachedGuidParents[dependent] = new List<string>(); s_CachedGuidParents[dependent].Add(guid); } count++; UpdateProgressBar("Caching parents:", count); } } /// <summary> /// Caches the orphans. /// </summary> private static void CacheOrphans() { s_GuidOrphans.Clear(); int count = 0; foreach (KeyValuePair<string, List<string>> pair in s_CachedGuidParents) { string guid = pair.Key; string path = AssetDatabase.GUIDToAssetPath(guid); if (IgnorePath(path)) continue; List<string> parents = pair.Value; if (parents.Count == 0) s_GuidOrphans.Add(guid); count++; UpdateProgressBar("Caching orphans:", count); } SortGuidByExt(s_GuidOrphans); } /// <summary> /// Gets the dependencies. /// </summary> /// <returns>The dependencies.</returns> /// <param name="path">Path.</param> private static void GetDependencies(string path, List<string> output) { if (Path.GetExtension(path) == ".unity") { GetSceneDependencies(path, output); return; } string guid = AssetDatabase.AssetPathToGUID(path); Object[] assets = AssetDatabase.LoadAllAssetsAtPath(path); Object[] dependencies = EditorUtility.CollectDependencies(assets); for (int dependencyIndex = 0; dependencyIndex < dependencies.Length; dependencyIndex++) { Object dependency = dependencies[dependencyIndex]; string dependencyPath = AssetDatabase.GetAssetPath(dependency); if (!MaintenanceUtils.InAssetsDir(dependencyPath)) continue; string dependencyGuid = AssetDatabase.AssetPathToGUID(dependencyPath); if (dependencyGuid == guid) continue; output.Add(dependencyGuid); } } /// <summary> /// We can't load the scene to collect dependencies, so let's get dirty and /// parse the file for GUIDs. /// </summary> /// <param name="path">Path.</param> /// <param name="output">Output.</param> private static void GetSceneDependencies(string path, List<string> output) { using (StreamReader reader = new StreamReader(path)) { while (reader.Peek() >= 0) { string line = reader.ReadLine(); if (!line.Contains(GUID_PREFIX)) continue; string guidPart = line.Split(',')[1]; string guid = StringUtils.RemoveSubstring(guidPart, GUID_PREFIX).Trim(); string assetPath = AssetDatabase.GUIDToAssetPath(guid); if (string.IsNullOrEmpty(assetPath)) continue; if (!MaintenanceUtils.InAssetsDir(assetPath)) continue; output.Add(guid); } } } /// <summary> /// Sorts the guid list by extension. /// </summary> private static void SortGuidByExt(List<string> collection) { collection.Sort(delegate(string guid1, string guid2) { string path1 = AssetDatabase.GUIDToAssetPath(guid1); string path2 = AssetDatabase.GUIDToAssetPath(guid2); string ext1 = Path.GetExtension(path1); string ext2 = Path.GetExtension(path2); int result = string.Compare(ext1, ext2); return result != 0 ? result : string.Compare(path1, path2); }); } /// <summary> /// Returns true if the asset at the given path should be ignored. /// </summary> /// <returns><c>true</c>, if path should be ignored, <c>false</c> otherwise.</returns> /// <param name="path">Path.</param> private static bool IgnorePath(string path) { if (!MaintenanceUtils.InAssetsDir(path)) return true; string ext = Path.GetExtension(path); if (Array.Exists(s_ExtIgnore, element => element == ext)) return true; for (int index = 0; index < s_DirIgnore.Length; index++) { string dirName = s_DirIgnore[index]; if (MaintenanceUtils.ContainsDirName(path, dirName)) return true; } return false; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 0.16.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.WebSites { using System; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; /// <summary> /// Extension methods for RecommendationsOperations. /// </summary> public static partial class RecommendationsOperationsExtensions { /// <summary> /// Gets a list of recommendations associated with the specified subscription. /// </summary> /// Gets a list of recommendations associated with the specified subscription. /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='featured'> /// If set, this API returns only the most critical recommendation among the /// others. Otherwise this API returns all recommendations available /// </param> /// <param name='filter'> /// Return only channels specified in the filter. Filter is specified by using /// OData syntax. Example: $filter=channels eq 'Api' or channel eq /// 'Notification' /// </param> public static IList<Recommendation> Get(this IRecommendationsOperations operations, bool? featured = default(bool?), string filter = default(string)) { return Task.Factory.StartNew(s => ((IRecommendationsOperations)s).GetAsync(featured, filter), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets a list of recommendations associated with the specified subscription. /// </summary> /// Gets a list of recommendations associated with the specified subscription. /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='featured'> /// If set, this API returns only the most critical recommendation among the /// others. Otherwise this API returns all recommendations available /// </param> /// <param name='filter'> /// Return only channels specified in the filter. Filter is specified by using /// OData syntax. Example: $filter=channels eq 'Api' or channel eq /// 'Notification' /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IList<Recommendation>> GetAsync(this IRecommendationsOperations operations, bool? featured = default(bool?), string filter = default(string), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetWithHttpMessagesAsync(featured, filter, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets the list of past recommendations optionally specified by the time /// range. /// </summary> /// Gets the list of past recommendations optionally specified by the time /// range. /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Resource group name /// </param> /// <param name='siteName'> /// Site name /// </param> /// <param name='startTime'> /// The start time of a time range to query, e.g. $filter=startTime eq /// '2015-01-01T00:00:00Z' and endTime eq '2015-01-02T00:00:00Z' /// </param> /// <param name='endTime'> /// The end time of a time range to query, e.g. $filter=startTime eq /// '2015-01-01T00:00:00Z' and endTime eq '2015-01-02T00:00:00Z' /// </param> public static IList<Recommendation> ListHistoryForWebApp(this IRecommendationsOperations operations, string resourceGroupName, string siteName, string startTime = default(string), string endTime = default(string)) { return Task.Factory.StartNew(s => ((IRecommendationsOperations)s).ListHistoryForWebAppAsync(resourceGroupName, siteName, startTime, endTime), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets the list of past recommendations optionally specified by the time /// range. /// </summary> /// Gets the list of past recommendations optionally specified by the time /// range. /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Resource group name /// </param> /// <param name='siteName'> /// Site name /// </param> /// <param name='startTime'> /// The start time of a time range to query, e.g. $filter=startTime eq /// '2015-01-01T00:00:00Z' and endTime eq '2015-01-02T00:00:00Z' /// </param> /// <param name='endTime'> /// The end time of a time range to query, e.g. $filter=startTime eq /// '2015-01-01T00:00:00Z' and endTime eq '2015-01-02T00:00:00Z' /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IList<Recommendation>> ListHistoryForWebAppAsync(this IRecommendationsOperations operations, string resourceGroupName, string siteName, string startTime = default(string), string endTime = default(string), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListHistoryForWebAppWithHttpMessagesAsync(resourceGroupName, siteName, startTime, endTime, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets a list of recommendations associated with the specified web site. /// </summary> /// Gets a list of recommendations associated with the specified web site. /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Resource group name /// </param> /// <param name='siteName'> /// Site name /// </param> /// <param name='featured'> /// If set, this API returns only the most critical recommendation among the /// others. Otherwise this API returns all recommendations available /// </param> /// <param name='webAppSku'> /// The name of web app SKU. /// </param> /// <param name='numSlots'> /// The number of site slots associated to the site /// </param> /// <param name='liveHours'> /// If greater than zero, this API scans the last active live site symptoms, /// dynamically generate on-the-fly recommendations /// </param> public static IList<Recommendation> ListRecommendedRulesForWebApp(this IRecommendationsOperations operations, string resourceGroupName, string siteName, bool? featured = default(bool?), string webAppSku = default(string), int? numSlots = default(int?), int? liveHours = default(int?)) { return Task.Factory.StartNew(s => ((IRecommendationsOperations)s).ListRecommendedRulesForWebAppAsync(resourceGroupName, siteName, featured, webAppSku, numSlots, liveHours), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets a list of recommendations associated with the specified web site. /// </summary> /// Gets a list of recommendations associated with the specified web site. /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Resource group name /// </param> /// <param name='siteName'> /// Site name /// </param> /// <param name='featured'> /// If set, this API returns only the most critical recommendation among the /// others. Otherwise this API returns all recommendations available /// </param> /// <param name='webAppSku'> /// The name of web app SKU. /// </param> /// <param name='numSlots'> /// The number of site slots associated to the site /// </param> /// <param name='liveHours'> /// If greater than zero, this API scans the last active live site symptoms, /// dynamically generate on-the-fly recommendations /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IList<Recommendation>> ListRecommendedRulesForWebAppAsync(this IRecommendationsOperations operations, string resourceGroupName, string siteName, bool? featured = default(bool?), string webAppSku = default(string), int? numSlots = default(int?), int? liveHours = default(int?), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListRecommendedRulesForWebAppWithHttpMessagesAsync(resourceGroupName, siteName, featured, webAppSku, numSlots, liveHours, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets the detailed properties of the recommendation object for the /// specified web site. /// </summary> /// Gets the detailed properties of the recommendation object for the /// specified web site. /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Resource group name /// </param> /// <param name='siteName'> /// Name of web app /// </param> /// <param name='name'> /// Recommendation rule name /// </param> /// <param name='updateSeen'> /// If true, the backend updates the last seen timestamp of the recommendation /// object. /// </param> public static RecommendationRule GetRuleDetailsByWebApp(this IRecommendationsOperations operations, string resourceGroupName, string siteName, string name, bool? updateSeen = default(bool?)) { return Task.Factory.StartNew(s => ((IRecommendationsOperations)s).GetRuleDetailsByWebAppAsync(resourceGroupName, siteName, name, updateSeen), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets the detailed properties of the recommendation object for the /// specified web site. /// </summary> /// Gets the detailed properties of the recommendation object for the /// specified web site. /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Resource group name /// </param> /// <param name='siteName'> /// Name of web app /// </param> /// <param name='name'> /// Recommendation rule name /// </param> /// <param name='updateSeen'> /// If true, the backend updates the last seen timestamp of the recommendation /// object. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<RecommendationRule> GetRuleDetailsByWebAppAsync(this IRecommendationsOperations operations, string resourceGroupName, string siteName, string name, bool? updateSeen = default(bool?), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetRuleDetailsByWebAppWithHttpMessagesAsync(resourceGroupName, siteName, name, updateSeen, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }
#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) using System; using Org.BouncyCastle.Crypto.Parameters; namespace Org.BouncyCastle.Crypto.Engines { /** * a class that provides a basic SKIPJACK engine. */ public class SkipjackEngine : IBlockCipher { const int BLOCK_SIZE = 8; static readonly short [] ftable = { 0xa3, 0xd7, 0x09, 0x83, 0xf8, 0x48, 0xf6, 0xf4, 0xb3, 0x21, 0x15, 0x78, 0x99, 0xb1, 0xaf, 0xf9, 0xe7, 0x2d, 0x4d, 0x8a, 0xce, 0x4c, 0xca, 0x2e, 0x52, 0x95, 0xd9, 0x1e, 0x4e, 0x38, 0x44, 0x28, 0x0a, 0xdf, 0x02, 0xa0, 0x17, 0xf1, 0x60, 0x68, 0x12, 0xb7, 0x7a, 0xc3, 0xe9, 0xfa, 0x3d, 0x53, 0x96, 0x84, 0x6b, 0xba, 0xf2, 0x63, 0x9a, 0x19, 0x7c, 0xae, 0xe5, 0xf5, 0xf7, 0x16, 0x6a, 0xa2, 0x39, 0xb6, 0x7b, 0x0f, 0xc1, 0x93, 0x81, 0x1b, 0xee, 0xb4, 0x1a, 0xea, 0xd0, 0x91, 0x2f, 0xb8, 0x55, 0xb9, 0xda, 0x85, 0x3f, 0x41, 0xbf, 0xe0, 0x5a, 0x58, 0x80, 0x5f, 0x66, 0x0b, 0xd8, 0x90, 0x35, 0xd5, 0xc0, 0xa7, 0x33, 0x06, 0x65, 0x69, 0x45, 0x00, 0x94, 0x56, 0x6d, 0x98, 0x9b, 0x76, 0x97, 0xfc, 0xb2, 0xc2, 0xb0, 0xfe, 0xdb, 0x20, 0xe1, 0xeb, 0xd6, 0xe4, 0xdd, 0x47, 0x4a, 0x1d, 0x42, 0xed, 0x9e, 0x6e, 0x49, 0x3c, 0xcd, 0x43, 0x27, 0xd2, 0x07, 0xd4, 0xde, 0xc7, 0x67, 0x18, 0x89, 0xcb, 0x30, 0x1f, 0x8d, 0xc6, 0x8f, 0xaa, 0xc8, 0x74, 0xdc, 0xc9, 0x5d, 0x5c, 0x31, 0xa4, 0x70, 0x88, 0x61, 0x2c, 0x9f, 0x0d, 0x2b, 0x87, 0x50, 0x82, 0x54, 0x64, 0x26, 0x7d, 0x03, 0x40, 0x34, 0x4b, 0x1c, 0x73, 0xd1, 0xc4, 0xfd, 0x3b, 0xcc, 0xfb, 0x7f, 0xab, 0xe6, 0x3e, 0x5b, 0xa5, 0xad, 0x04, 0x23, 0x9c, 0x14, 0x51, 0x22, 0xf0, 0x29, 0x79, 0x71, 0x7e, 0xff, 0x8c, 0x0e, 0xe2, 0x0c, 0xef, 0xbc, 0x72, 0x75, 0x6f, 0x37, 0xa1, 0xec, 0xd3, 0x8e, 0x62, 0x8b, 0x86, 0x10, 0xe8, 0x08, 0x77, 0x11, 0xbe, 0x92, 0x4f, 0x24, 0xc5, 0x32, 0x36, 0x9d, 0xcf, 0xf3, 0xa6, 0xbb, 0xac, 0x5e, 0x6c, 0xa9, 0x13, 0x57, 0x25, 0xb5, 0xe3, 0xbd, 0xa8, 0x3a, 0x01, 0x05, 0x59, 0x2a, 0x46 }; private int[] key0, key1, key2, key3; private bool encrypting; /** * initialise a SKIPJACK cipher. * * @param forEncryption whether or not we are for encryption. * @param parameters the parameters required to set up the cipher. * @exception ArgumentException if the parameters argument is * inappropriate. */ public virtual void Init( bool forEncryption, ICipherParameters parameters) { if (!(parameters is KeyParameter)) throw new ArgumentException("invalid parameter passed to SKIPJACK init - " + parameters.GetType().ToString()); byte[] keyBytes = ((KeyParameter)parameters).GetKey(); this.encrypting = forEncryption; this.key0 = new int[32]; this.key1 = new int[32]; this.key2 = new int[32]; this.key3 = new int[32]; // // expand the key to 128 bytes in 4 parts (saving us a modulo, multiply // and an addition). // for (int i = 0; i < 32; i ++) { key0[i] = keyBytes[(i * 4) % 10] & 0xff; key1[i] = keyBytes[(i * 4 + 1) % 10] & 0xff; key2[i] = keyBytes[(i * 4 + 2) % 10] & 0xff; key3[i] = keyBytes[(i * 4 + 3) % 10] & 0xff; } } public virtual string AlgorithmName { get { return "SKIPJACK"; } } public virtual bool IsPartialBlockOkay { get { return false; } } public virtual int GetBlockSize() { return BLOCK_SIZE; } public virtual int ProcessBlock( byte[] input, int inOff, byte[] output, int outOff) { if (key1 == null) throw new InvalidOperationException("SKIPJACK engine not initialised"); Check.DataLength(input, inOff, BLOCK_SIZE, "input buffer too short"); Check.OutputLength(output, outOff, BLOCK_SIZE, "output buffer too short"); if (encrypting) { EncryptBlock(input, inOff, output, outOff); } else { DecryptBlock(input, inOff, output, outOff); } return BLOCK_SIZE; } public virtual void Reset() { } /** * The G permutation */ private int G( int k, int w) { int g1, g2, g3, g4, g5, g6; g1 = (w >> 8) & 0xff; g2 = w & 0xff; g3 = ftable[g2 ^ key0[k]] ^ g1; g4 = ftable[g3 ^ key1[k]] ^ g2; g5 = ftable[g4 ^ key2[k]] ^ g3; g6 = ftable[g5 ^ key3[k]] ^ g4; return ((g5 << 8) + g6); } public virtual int EncryptBlock( byte[] input, int inOff, byte[] outBytes, int outOff) { int w1 = (input[inOff + 0] << 8) + (input[inOff + 1] & 0xff); int w2 = (input[inOff + 2] << 8) + (input[inOff + 3] & 0xff); int w3 = (input[inOff + 4] << 8) + (input[inOff + 5] & 0xff); int w4 = (input[inOff + 6] << 8) + (input[inOff + 7] & 0xff); int k = 0; for (int t = 0; t < 2; t++) { for(int i = 0; i < 8; i++) { int tmp = w4; w4 = w3; w3 = w2; w2 = G(k, w1); w1 = w2 ^ tmp ^ (k + 1); k++; } for(int i = 0; i < 8; i++) { int tmp = w4; w4 = w3; w3 = w1 ^ w2 ^ (k + 1); w2 = G(k, w1); w1 = tmp; k++; } } outBytes[outOff + 0] = (byte)((w1 >> 8)); outBytes[outOff + 1] = (byte)(w1); outBytes[outOff + 2] = (byte)((w2 >> 8)); outBytes[outOff + 3] = (byte)(w2); outBytes[outOff + 4] = (byte)((w3 >> 8)); outBytes[outOff + 5] = (byte)(w3); outBytes[outOff + 6] = (byte)((w4 >> 8)); outBytes[outOff + 7] = (byte)(w4); return BLOCK_SIZE; } /** * the inverse of the G permutation. */ private int H( int k, int w) { int h1, h2, h3, h4, h5, h6; h1 = w & 0xff; h2 = (w >> 8) & 0xff; h3 = ftable[h2 ^ key3[k]] ^ h1; h4 = ftable[h3 ^ key2[k]] ^ h2; h5 = ftable[h4 ^ key1[k]] ^ h3; h6 = ftable[h5 ^ key0[k]] ^ h4; return ((h6 << 8) + h5); } public virtual int DecryptBlock( byte[] input, int inOff, byte[] outBytes, int outOff) { int w2 = (input[inOff + 0] << 8) + (input[inOff + 1] & 0xff); int w1 = (input[inOff + 2] << 8) + (input[inOff + 3] & 0xff); int w4 = (input[inOff + 4] << 8) + (input[inOff + 5] & 0xff); int w3 = (input[inOff + 6] << 8) + (input[inOff + 7] & 0xff); int k = 31; for (int t = 0; t < 2; t++) { for(int i = 0; i < 8; i++) { int tmp = w4; w4 = w3; w3 = w2; w2 = H(k, w1); w1 = w2 ^ tmp ^ (k + 1); k--; } for(int i = 0; i < 8; i++) { int tmp = w4; w4 = w3; w3 = w1 ^ w2 ^ (k + 1); w2 = H(k, w1); w1 = tmp; k--; } } outBytes[outOff + 0] = (byte)((w2 >> 8)); outBytes[outOff + 1] = (byte)(w2); outBytes[outOff + 2] = (byte)((w1 >> 8)); outBytes[outOff + 3] = (byte)(w1); outBytes[outOff + 4] = (byte)((w4 >> 8)); outBytes[outOff + 5] = (byte)(w4); outBytes[outOff + 6] = (byte)((w3 >> 8)); outBytes[outOff + 7] = (byte)(w3); return BLOCK_SIZE; } } } #endif
// // Copyright (c) 2004-2017 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // #if !SILVERLIGHT && !__ANDROID__ && !__IOS__ && !WINDOWS_UWP // Unfortunately, Xamarin Android and Xamarin iOS don't support mutexes (see https://github.com/mono/mono/blob/3a9e18e5405b5772be88bfc45739d6a350560111/mcs/class/corlib/System.Threading/Mutex.cs#L167) so the BaseFileAppender class now throws an exception in the constructor. #define SupportsMutex #endif #if SupportsMutex namespace NLog.Internal.FileAppenders { using System; using System.IO; using System.Security; using System.Threading; using NLog.Common; /// <summary> /// Provides a multiprocess-safe atomic file appends while /// keeping the files open. /// </summary> /// <remarks> /// On Unix you can get all the appends to be atomic, even when multiple /// processes are trying to write to the same file, because setting the file /// pointer to the end of the file and appending can be made one operation. /// On Win32 we need to maintain some synchronization between processes /// (global named mutex is used for this) /// </remarks> [SecuritySafeCritical] internal class MutexMultiProcessFileAppender : BaseMutexFileAppender { public static readonly IFileAppenderFactory TheFactory = new Factory(); private FileStream _fileStream; private readonly FileCharacteristicsHelper _fileCharacteristicsHelper; private Mutex _mutex; /// <summary> /// Initializes a new instance of the <see cref="MutexMultiProcessFileAppender" /> class. /// </summary> /// <param name="fileName">Name of the file.</param> /// <param name="parameters">The parameters.</param> public MutexMultiProcessFileAppender(string fileName, ICreateFileParameters parameters) : base(fileName, parameters) { try { _mutex = CreateSharableMutex("FileLock"); _fileStream = CreateFileStream(true); _fileCharacteristicsHelper = FileCharacteristicsHelper.CreateHelper(parameters.ForceManaged); } catch { if (_mutex != null) { _mutex.Close(); _mutex = null; } if (_fileStream != null) { _fileStream.Close(); _fileStream = null; } throw; } } /// <summary> /// Writes the specified bytes. /// </summary> /// <param name="bytes">The bytes array.</param> /// <param name="offset">The bytes array offset.</param> /// <param name="count">The number of bytes.</param> public override void Write(byte[] bytes, int offset, int count) { if (_mutex == null || _fileStream == null) { return; } try { _mutex.WaitOne(); } catch (AbandonedMutexException) { // ignore the exception, another process was killed without properly releasing the mutex // the mutex has been acquired, so proceed to writing // See: http://msdn.microsoft.com/en-us/library/system.threading.abandonedmutexexception.aspx } try { _fileStream.Seek(0, SeekOrigin.End); _fileStream.Write(bytes, offset, count); _fileStream.Flush(); if (CaptureLastWriteTime) { FileTouched(); } } finally { _mutex.ReleaseMutex(); } } /// <summary> /// Closes this instance. /// </summary> public override void Close() { if (_mutex == null && _fileStream == null) { return; } InternalLogger.Trace("Closing '{0}'", FileName); try { _mutex?.Close(); } catch (Exception ex) { // Swallow exception as the mutex now is in final state (abandoned instead of closed) InternalLogger.Warn(ex, "Failed to close mutex: '{0}'", FileName); } finally { _mutex = null; } try { _fileStream?.Close(); } catch (Exception ex) { // Swallow exception as the file-stream now is in final state (broken instead of closed) InternalLogger.Warn(ex, "Failed to close file: '{0}'", FileName); AsyncHelpers.WaitForDelay(TimeSpan.FromMilliseconds(1)); // Artificial delay to avoid hammering a bad file location } finally { _fileStream = null; } FileTouched(); } /// <summary> /// Flushes this instance. /// </summary> public override void Flush() { // do nothing, the stream is always flushed } /// <summary> /// Gets the creation time for a file associated with the appender. The time returned is in Coordinated Universal /// Time [UTC] standard. /// </summary> /// <returns>The file creation time.</returns> public override DateTime? GetFileCreationTimeUtc() { return CreationTimeUtc; // File is kept open, so creation time is static } /// <summary> /// Gets the last time the file associated with the appeander is written. The time returned is in Coordinated /// Universal Time [UTC] standard. /// </summary> /// <returns>The time the file was last written to.</returns> public override DateTime? GetFileLastWriteTimeUtc() { var fileChars = GetFileCharacteristics(); return fileChars.LastWriteTimeUtc; } /// <summary> /// Gets the length in bytes of the file associated with the appeander. /// </summary> /// <returns>A long value representing the length of the file in bytes.</returns> public override long? GetFileLength() { var fileChars = GetFileCharacteristics(); return fileChars.FileLength; } private FileCharacteristics GetFileCharacteristics() { // TODO: It is not efficient to read all the whole FileCharacteristics and then using one property. return _fileCharacteristicsHelper.GetFileCharacteristics(FileName, _fileStream); } /// <summary> /// Factory class. /// </summary> private class Factory : IFileAppenderFactory { /// <summary> /// Opens the appender for given file name and parameters. /// </summary> /// <param name="fileName">Name of the file.</param> /// <param name="parameters">Creation parameters.</param> /// <returns> /// Instance of <see cref="BaseFileAppender"/> which can be used to write to the file. /// </returns> BaseFileAppender IFileAppenderFactory.Open(string fileName, ICreateFileParameters parameters) { return new MutexMultiProcessFileAppender(fileName, parameters); } } } } #endif
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // namespace System.Reflection.Emit { using System.Runtime.InteropServices; using System; using CultureInfo = System.Globalization.CultureInfo; using System.Reflection; using System.Diagnostics.Contracts; public sealed class FieldBuilder : FieldInfo { #region Private Data Members private int m_fieldTok; private FieldToken m_tkField; private TypeBuilder m_typeBuilder; private String m_fieldName; private FieldAttributes m_Attributes; private Type m_fieldType; #endregion #region Constructor internal FieldBuilder(TypeBuilder typeBuilder, String fieldName, Type type, Type[] requiredCustomModifiers, Type[] optionalCustomModifiers, FieldAttributes attributes) { if (fieldName == null) throw new ArgumentNullException(nameof(fieldName)); if (fieldName.Length == 0) throw new ArgumentException(SR.Argument_EmptyName, nameof(fieldName)); if (fieldName[0] == '\0') throw new ArgumentException(SR.Argument_IllegalName, nameof(fieldName)); if (type == null) throw new ArgumentNullException(nameof(type)); if (type == typeof(void)) throw new ArgumentException(SR.Argument_BadFieldType); Contract.EndContractBlock(); m_fieldName = fieldName; m_typeBuilder = typeBuilder; m_fieldType = type; m_Attributes = attributes & ~FieldAttributes.ReservedMask; SignatureHelper sigHelp = SignatureHelper.GetFieldSigHelper(m_typeBuilder.Module); sigHelp.AddArgument(type, requiredCustomModifiers, optionalCustomModifiers); int sigLength; byte[] signature = sigHelp.InternalGetSignature(out sigLength); m_fieldTok = TypeBuilder.DefineField(m_typeBuilder.GetModuleBuilder().GetNativeHandle(), typeBuilder.TypeToken.Token, fieldName, signature, sigLength, m_Attributes); m_tkField = new FieldToken(m_fieldTok, type); } #endregion #region Internal Members internal void SetData(byte[] data, int size) { ModuleBuilder.SetFieldRVAContent(m_typeBuilder.GetModuleBuilder().GetNativeHandle(), m_tkField.Token, data, size); } #endregion #region MemberInfo Overrides internal int MetadataTokenInternal { get { return m_fieldTok; } } public override Module Module { get { return m_typeBuilder.Module; } } public override String Name { get { return m_fieldName; } } public override Type DeclaringType { get { if (m_typeBuilder.m_isHiddenGlobalType == true) return null; return m_typeBuilder; } } public override Type ReflectedType { get { if (m_typeBuilder.m_isHiddenGlobalType == true) return null; return m_typeBuilder; } } #endregion #region FieldInfo Overrides public override Type FieldType { get { return m_fieldType; } } public override Object GetValue(Object obj) { // NOTE!! If this is implemented, make sure that this throws // a NotSupportedException for Save-only dynamic assemblies. // Otherwise, it could cause the .cctor to be executed. throw new NotSupportedException(SR.NotSupported_DynamicModule); } public override void SetValue(Object obj, Object val, BindingFlags invokeAttr, Binder binder, CultureInfo culture) { // NOTE!! If this is implemented, make sure that this throws // a NotSupportedException for Save-only dynamic assemblies. // Otherwise, it could cause the .cctor to be executed. throw new NotSupportedException(SR.NotSupported_DynamicModule); } public override RuntimeFieldHandle FieldHandle { get { throw new NotSupportedException(SR.NotSupported_DynamicModule); } } public override FieldAttributes Attributes { get { return m_Attributes; } } #endregion #region ICustomAttributeProvider Implementation public override Object[] GetCustomAttributes(bool inherit) { throw new NotSupportedException(SR.NotSupported_DynamicModule); } public override Object[] GetCustomAttributes(Type attributeType, bool inherit) { throw new NotSupportedException(SR.NotSupported_DynamicModule); } public override bool IsDefined(Type attributeType, bool inherit) { throw new NotSupportedException(SR.NotSupported_DynamicModule); } #endregion #region Public Members public FieldToken GetToken() { return m_tkField; } public void SetOffset(int iOffset) { m_typeBuilder.ThrowIfCreated(); TypeBuilder.SetFieldLayoutOffset(m_typeBuilder.GetModuleBuilder().GetNativeHandle(), GetToken().Token, iOffset); } public void SetConstant(Object defaultValue) { m_typeBuilder.ThrowIfCreated(); TypeBuilder.SetConstantValue(m_typeBuilder.GetModuleBuilder(), GetToken().Token, m_fieldType, defaultValue); } public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute) { if (con == null) throw new ArgumentNullException(nameof(con)); if (binaryAttribute == null) throw new ArgumentNullException(nameof(binaryAttribute)); Contract.EndContractBlock(); ModuleBuilder module = m_typeBuilder.Module as ModuleBuilder; m_typeBuilder.ThrowIfCreated(); TypeBuilder.DefineCustomAttribute(module, m_tkField.Token, module.GetConstructorToken(con).Token, binaryAttribute, false, false); } public void SetCustomAttribute(CustomAttributeBuilder customBuilder) { if (customBuilder == null) throw new ArgumentNullException(nameof(customBuilder)); Contract.EndContractBlock(); m_typeBuilder.ThrowIfCreated(); ModuleBuilder module = m_typeBuilder.Module as ModuleBuilder; customBuilder.CreateCustomAttribute(module, m_tkField.Token); } #endregion } }
using System; using System.Collections.Generic; namespace NServiceKit.ServiceInterface.Auth { /// <summary>Interface for i/o authentication tokens.</summary> public interface IOAuthTokens { /// <summary>Gets or sets the provider.</summary> /// /// <value>The provider.</value> string Provider { get; set; } /// <summary>Gets or sets the identifier of the user.</summary> /// /// <value>The identifier of the user.</value> string UserId { get; set; } /// <summary>Gets or sets the name of the user.</summary> /// /// <value>The name of the user.</value> string UserName { get; set; } /// <summary>Gets or sets the name of the display.</summary> /// /// <value>The name of the display.</value> string DisplayName { get; set; } /// <summary>Gets or sets the person's first name.</summary> /// /// <value>The name of the first.</value> string FirstName { get; set; } /// <summary>Gets or sets the person's last name.</summary> /// /// <value>The name of the last.</value> string LastName { get; set; } /// <summary>Gets or sets the email.</summary> /// /// <value>The email.</value> string Email { get; set; } /// <summary>Gets or sets the birth date.</summary> /// /// <value>The birth date.</value> DateTime? BirthDate { get; set; } /// <summary>Gets or sets the birth date raw.</summary> /// /// <value>The birth date raw.</value> string BirthDateRaw { get; set; } /// <summary>Gets or sets the country.</summary> /// /// <value>The country.</value> string Country { get; set; } /// <summary>Gets or sets the culture.</summary> /// /// <value>The culture.</value> string Culture { get; set; } /// <summary>Gets or sets the name of the full.</summary> /// /// <value>The name of the full.</value> string FullName { get; set; } /// <summary>Gets or sets the gender.</summary> /// /// <value>The gender.</value> string Gender { get; set; } /// <summary>Gets or sets the language.</summary> /// /// <value>The language.</value> string Language { get; set; } /// <summary>Gets or sets the mail address.</summary> /// /// <value>The mail address.</value> string MailAddress { get; set; } /// <summary>Gets or sets the nickname.</summary> /// /// <value>The nickname.</value> string Nickname { get; set; } /// <summary>Gets or sets the postal code.</summary> /// /// <value>The postal code.</value> string PostalCode { get; set; } /// <summary>Gets or sets the time zone.</summary> /// /// <value>The time zone.</value> string TimeZone { get; set; } /// <summary>Gets or sets the access token.</summary> /// /// <value>The access token.</value> string AccessToken { get; set; } /// <summary>Gets or sets the access token secret.</summary> /// /// <value>The access token secret.</value> string AccessTokenSecret { get; set; } /// <summary>Gets or sets the refresh token.</summary> /// /// <value>The refresh token.</value> string RefreshToken { get; set; } /// <summary>Gets or sets the Date/Time of the refresh token expiry.</summary> /// /// <value>The refresh token expiry.</value> DateTime? RefreshTokenExpiry { get; set; } /// <summary>Gets or sets the request token.</summary> /// /// <value>The request token.</value> string RequestToken { get; set; } /// <summary>Gets or sets the request token secret.</summary> /// /// <value>The request token secret.</value> string RequestTokenSecret { get; set; } /// <summary>Gets or sets the items.</summary> /// /// <value>The items.</value> Dictionary<string, string> Items { get; set; } } /// <summary>An authentication tokens.</summary> public class OAuthTokens : IOAuthTokens { /// <summary>Initializes a new instance of the NServiceKit.ServiceInterface.Auth.OAuthTokens class.</summary> public OAuthTokens() { this.Items = new Dictionary<string, string>(); } /// <summary>Gets or sets the provider.</summary> /// /// <value>The provider.</value> public string Provider { get; set; } /// <summary>Gets or sets the identifier of the user.</summary> /// /// <value>The identifier of the user.</value> public string UserId { get; set; } /// <summary>Gets or sets the name of the user.</summary> /// /// <value>The name of the user.</value> public string UserName { get; set; } /// <summary>Gets or sets the name of the display.</summary> /// /// <value>The name of the display.</value> public string DisplayName { get; set; } /// <summary>Gets or sets the person's first name.</summary> /// /// <value>The name of the first.</value> public string FirstName { get; set; } /// <summary>Gets or sets the person's last name.</summary> /// /// <value>The name of the last.</value> public string LastName { get; set; } /// <summary>Gets or sets the email.</summary> /// /// <value>The email.</value> public string Email { get; set; } /// <summary>Gets or sets the birth date.</summary> /// /// <value>The birth date.</value> public DateTime? BirthDate { get; set; } /// <summary>Gets or sets the birth date raw.</summary> /// /// <value>The birth date raw.</value> public string BirthDateRaw { get; set; } /// <summary>Gets or sets the country.</summary> /// /// <value>The country.</value> public string Country { get; set; } /// <summary>Gets or sets the culture.</summary> /// /// <value>The culture.</value> public string Culture { get; set; } /// <summary>Gets or sets the name of the full.</summary> /// /// <value>The name of the full.</value> public string FullName { get; set; } /// <summary>Gets or sets the gender.</summary> /// /// <value>The gender.</value> public string Gender { get; set; } /// <summary>Gets or sets the language.</summary> /// /// <value>The language.</value> public string Language { get; set; } /// <summary>Gets or sets the mail address.</summary> /// /// <value>The mail address.</value> public string MailAddress { get; set; } /// <summary>Gets or sets the nickname.</summary> /// /// <value>The nickname.</value> public string Nickname { get; set; } /// <summary>Gets or sets the postal code.</summary> /// /// <value>The postal code.</value> public string PostalCode { get; set; } /// <summary>Gets or sets the time zone.</summary> /// /// <value>The time zone.</value> public string TimeZone { get; set; } /// <summary>Gets or sets the access token.</summary> /// /// <value>The access token.</value> public string AccessToken { get; set; } /// <summary>Gets or sets the access token secret.</summary> /// /// <value>The access token secret.</value> public string AccessTokenSecret { get; set; } /// <summary>Gets or sets the refresh token.</summary> /// /// <value>The refresh token.</value> public string RefreshToken { get; set; } /// <summary>Gets or sets the Date/Time of the refresh token expiry.</summary> /// /// <value>The refresh token expiry.</value> public DateTime? RefreshTokenExpiry { get; set; } /// <summary>Gets or sets the request token.</summary> /// /// <value>The request token.</value> public string RequestToken { get; set; } /// <summary>Gets or sets the request token secret.</summary> /// /// <value>The request token secret.</value> public string RequestTokenSecret { get; set; } /// <summary>Gets or sets the items.</summary> /// /// <value>The items.</value> public Dictionary<string, string> Items { get; set; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Text; using Internal.TypeSystem; using Debug = System.Diagnostics.Debug; using Interlocked = System.Threading.Interlocked; namespace Internal.IL.Stubs { /// <summary> /// Thunk to dynamically invoke a method using reflection. The method accepts an object[] of parameters /// to target method, lays them out on the stack, and calls the target method. This thunk has heavy /// dependencies on the general dynamic invocation infrastructure in System.InvokeUtils and gets called from there /// at runtime. See comments in System.InvokeUtils for a more thorough explanation. /// </summary> internal partial class DynamicInvokeMethodThunk : ILStubMethod { private TypeDesc _owningType; private DynamicInvokeMethodSignature _targetSignature; private TypeDesc[] _instantiation; private MethodSignature _signature; public DynamicInvokeMethodThunk(TypeDesc owningType, DynamicInvokeMethodSignature signature) { _owningType = owningType; _targetSignature = signature; } public static bool SupportsThunks(TypeSystemContext context) { return context.SystemModule.GetType("System", "InvokeUtils", false) != null; } public override TypeSystemContext Context { get { return _owningType.Context; } } public override TypeDesc OwningType { get { return _owningType; } } private MetadataType InvokeUtilsType { get { return Context.SystemModule.GetKnownType("System", "InvokeUtils"); } } private MetadataType ArgSetupStateType { get { return InvokeUtilsType.GetNestedType("ArgSetupState"); } } public override MethodSignature Signature { get { if (_signature == null) { _signature = new MethodSignature( MethodSignatureFlags.Static, Instantiation.Length, Context.GetWellKnownType(WellKnownType.Object), new TypeDesc[] { Context.GetWellKnownType(WellKnownType.Object), // thisPtr Context.GetWellKnownType(WellKnownType.IntPtr), // methodToCall ArgSetupStateType.MakeByRefType(), // argSetupState Context.GetWellKnownType(WellKnownType.Boolean), // targetIsThisCall }); } return _signature; } } public override Instantiation Instantiation { get { if (_instantiation == null) { TypeDesc[] instantiation = new TypeDesc[_targetSignature.HasReturnValue ? _targetSignature.Length + 1 : _targetSignature.Length]; for (int i = 0; i < _targetSignature.Length; i++) instantiation[i] = new DynamicInvokeThunkGenericParameter(this, i); if (_targetSignature.HasReturnValue) instantiation[_targetSignature.Length] = new DynamicInvokeThunkGenericParameter(this, _targetSignature.Length); Interlocked.CompareExchange(ref _instantiation, instantiation, null); } return new Instantiation(_instantiation); } } public override string Name { get { StringBuilder sb = new StringBuilder("InvokeRet"); if (_targetSignature.HasReturnValue) sb.Append('O'); else sb.Append('V'); for (int i = 0; i < _targetSignature.Length; i++) sb.Append(_targetSignature[i] == DynamicInvokeMethodParameterKind.Value ? 'I' : 'R'); return sb.ToString(); } } public override MethodIL EmitIL() { ILEmitter emitter = new ILEmitter(); ILCodeStream argSetupStream = emitter.NewCodeStream(); ILCodeStream thisCallSiteSetupStream = emitter.NewCodeStream(); ILCodeStream staticCallSiteSetupStream = emitter.NewCodeStream(); // This function will look like // // !For each parameter to the method // !if (parameter is In Parameter) // localX is TypeOfParameterX& // ldtoken TypeOfParameterX // call DynamicInvokeParamHelperIn(RuntimeTypeHandle) // stloc localX // !else // localX is TypeOfParameter // ldtoken TypeOfParameterX // call DynamicInvokeParamHelperRef(RuntimeTypeHandle) // stloc localX // ldarg.2 // call DynamicInvokeArgSetupComplete(ref ArgSetupState) // *** Thiscall instruction stream starts here *** // ldarg.3 // Load targetIsThisCall // brfalse Not_this_call // ldarg.0 // Load this pointer // !For each parameter // !if (parameter is In Parameter) // ldloc localX // ldobj TypeOfParameterX // !else // ldloc localX // ldarg.1 // calli ReturnType thiscall(TypeOfParameter1, ...) // !if ((ReturnType == void) // ldnull // !else // box ReturnType // ret // *** Static call instruction stream starts here *** // Not_this_call: // !For each parameter // !if (parameter is In Parameter) // ldloc localX // ldobj TypeOfParameterX // !else // ldloc localX // ldarg.1 // calli ReturnType (TypeOfParameter1, ...) // !if ((ReturnType == void) // ldnull // !else // box ReturnType // ret ILCodeLabel lStaticCall = emitter.NewCodeLabel(); thisCallSiteSetupStream.EmitLdArg(3); // targetIsThisCall thisCallSiteSetupStream.Emit(ILOpcode.brfalse, lStaticCall); staticCallSiteSetupStream.EmitLabel(lStaticCall); thisCallSiteSetupStream.EmitLdArg(0); // thisPtr ILToken tokDynamicInvokeParamHelperRef = emitter.NewToken(InvokeUtilsType.GetKnownMethod("DynamicInvokeParamHelperRef", null)); ILToken tokDynamicInvokeParamHelperIn = emitter.NewToken(InvokeUtilsType.GetKnownMethod("DynamicInvokeParamHelperIn", null)); TypeDesc[] targetMethodSignature = new TypeDesc[_targetSignature.Length]; for (int paramIndex = 0; paramIndex < _targetSignature.Length; paramIndex++) { TypeDesc paramType = Context.GetSignatureVariable(paramIndex, true); ILToken tokParamType = emitter.NewToken(paramType); ILLocalVariable local = emitter.NewLocal(paramType.MakeByRefType()); thisCallSiteSetupStream.EmitLdLoc(local); staticCallSiteSetupStream.EmitLdLoc(local); argSetupStream.Emit(ILOpcode.ldtoken, tokParamType); if (_targetSignature[paramIndex] == DynamicInvokeMethodParameterKind.Reference) { argSetupStream.Emit(ILOpcode.call, tokDynamicInvokeParamHelperRef); targetMethodSignature[paramIndex] = paramType.MakeByRefType(); } else { argSetupStream.Emit(ILOpcode.call, tokDynamicInvokeParamHelperIn); thisCallSiteSetupStream.Emit(ILOpcode.ldobj, tokParamType); staticCallSiteSetupStream.Emit(ILOpcode.ldobj, tokParamType); targetMethodSignature[paramIndex] = paramType; } argSetupStream.EmitStLoc(local); } argSetupStream.EmitLdArg(2); // argSetupState argSetupStream.Emit(ILOpcode.call, emitter.NewToken(InvokeUtilsType.GetKnownMethod("DynamicInvokeArgSetupComplete", null))); thisCallSiteSetupStream.EmitLdArg(1); // methodToCall staticCallSiteSetupStream.EmitLdArg(1); // methodToCall TypeDesc returnType = _targetSignature.HasReturnValue ? Context.GetSignatureVariable(_targetSignature.Length, true) : Context.GetWellKnownType(WellKnownType.Void); MethodSignature thisCallMethodSig = new MethodSignature(0, 0, returnType, targetMethodSignature); thisCallSiteSetupStream.Emit(ILOpcode.calli, emitter.NewToken(thisCallMethodSig)); MethodSignature staticCallMethodSig = new MethodSignature(MethodSignatureFlags.Static, 0, returnType, targetMethodSignature); staticCallSiteSetupStream.Emit(ILOpcode.calli, emitter.NewToken(staticCallMethodSig)); if (_targetSignature.HasReturnValue) { ILToken tokReturnType = emitter.NewToken(returnType); thisCallSiteSetupStream.Emit(ILOpcode.box, tokReturnType); staticCallSiteSetupStream.Emit(ILOpcode.box, tokReturnType); } else { thisCallSiteSetupStream.Emit(ILOpcode.ldnull); staticCallSiteSetupStream.Emit(ILOpcode.ldnull); } thisCallSiteSetupStream.Emit(ILOpcode.ret); staticCallSiteSetupStream.Emit(ILOpcode.ret); return emitter.Link(this); } private partial class DynamicInvokeThunkGenericParameter : GenericParameterDesc { private DynamicInvokeMethodThunk _owningMethod; public DynamicInvokeThunkGenericParameter(DynamicInvokeMethodThunk owningMethod, int index) { _owningMethod = owningMethod; Index = index; } public override TypeSystemContext Context { get { return _owningMethod.Context; } } public override int Index { get; } public override GenericParameterKind Kind { get { return GenericParameterKind.Method; } } } } internal enum DynamicInvokeMethodParameterKind { None, Value, Reference, } /// <summary> /// Wraps a <see cref="MethodSignature"/> to reduce it's fidelity. /// </summary> internal struct DynamicInvokeMethodSignature : IEquatable<DynamicInvokeMethodSignature> { private MethodSignature _signature; public bool HasReturnValue { get { return !_signature.ReturnType.IsVoid; } } public int Length { get { return _signature.Length; } } public DynamicInvokeMethodParameterKind this[int index] { get { return _signature[index].IsByRef ? DynamicInvokeMethodParameterKind.Reference : DynamicInvokeMethodParameterKind.Value; } } public DynamicInvokeMethodSignature(MethodSignature concreteSignature) { // ByRef returns should have been filtered out elsewhere. We don't handle them // because reflection can't invoke such methods. Debug.Assert(!concreteSignature.ReturnType.IsByRef); _signature = concreteSignature; } public override bool Equals(object obj) { return obj is DynamicInvokeMethodSignature && Equals((DynamicInvokeMethodSignature)obj); } public override int GetHashCode() { int hashCode = HasReturnValue ? 17 : 23; for (int i = 0; i < Length; i++) { int value = (int)this[i] * 0x5498341 + 0x832424; hashCode = hashCode * 31 + value; } return hashCode; } public bool Equals(DynamicInvokeMethodSignature other) { if (HasReturnValue != other.HasReturnValue) return false; if (Length != other.Length) return false; for (int i = 0; i < Length; i++) { if (this[i] != other[i]) return false; } return true; } } }
// *********************************************************************** // Copyright (c) 2012 Charlie Poole // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** using System; using System.Text; using System.Collections; using System.Globalization; using NUnit.Framework.Internal; namespace NUnit.Framework.Constraints { /// <summary> /// Custom value formatter function /// </summary> /// <param name="val">The value</param> /// <returns></returns> public delegate string ValueFormatter(object val); /// <summary> /// Custom value formatter factory function /// </summary> /// <param name="next">The next formatter function</param> /// <returns>ValueFormatter</returns> /// <remarks>If the given formatter is unable to handle a certain format, it must call the next formatter in the chain</remarks> public delegate ValueFormatter ValueFormatterFactory(ValueFormatter next); /// <summary> /// Static methods used in creating messages /// </summary> internal static class MsgUtils { /// <summary> /// Static string used when strings are clipped /// </summary> private const string ELLIPSIS = "..."; /// <summary> /// Formatting strings used for expected and actual _values /// </summary> private static readonly string Fmt_Null = "null"; private static readonly string Fmt_EmptyString = "<string.Empty>"; private static readonly string Fmt_EmptyCollection = "<empty>"; private static readonly string Fmt_String = "\"{0}\""; private static readonly string Fmt_Char = "'{0}'"; private static readonly string Fmt_DateTime = "yyyy-MM-dd HH:mm:ss.fff"; #if !NETCF private static readonly string Fmt_DateTimeOffset = "yyyy-MM-dd HH:mm:ss.fffzzz"; #endif private static readonly string Fmt_ValueType = "{0}"; private static readonly string Fmt_Default = "<{0}>"; /// <summary> /// Current head of chain of value formatters. Public for testing. /// </summary> public static ValueFormatter DefaultValueFormatter { get; set; } static MsgUtils() { // Initialize formatter to default for values of indeterminate type. DefaultValueFormatter = val => string.Format(Fmt_Default, val); AddFormatter(next => val => val is ValueType ? string.Format(Fmt_ValueType, val) : next(val)); AddFormatter(next => val => val is DateTime ? FormatDateTime((DateTime)val) : next(val)); #if !NETCF AddFormatter(next => val => val is DateTimeOffset ? FormatDateTimeOffset ((DateTimeOffset)val) : next (val)); #endif AddFormatter(next => val => val is decimal ? FormatDecimal((decimal)val) : next(val)); AddFormatter(next => val => val is float ? FormatFloat((float)val) : next(val)); AddFormatter(next => val => val is double ? FormatDouble((double)val) : next(val)); AddFormatter(next => val => val is char ? string.Format(Fmt_Char, val) : next(val)); AddFormatter(next => val => val is IEnumerable ? FormatCollection((IEnumerable)val, 0, 10) : next(val)); AddFormatter(next => val => val is string ? FormatString((string)val) : next(val)); AddFormatter(next => val => val.GetType().IsArray ? FormatArray((Array)val) : next(val)); #if NETCF AddFormatter(next => val => { var vi = val as System.Reflection.MethodInfo; return (vi != null && vi.IsGenericMethodDefinition) ? string.Format(Fmt_Default, vi.Name + "<>") : next(val); }); #endif } /// <summary> /// Add a formatter to the chain of responsibility. /// </summary> /// <param name="formatterFactory"></param> public static void AddFormatter(ValueFormatterFactory formatterFactory) { DefaultValueFormatter = formatterFactory(DefaultValueFormatter); } /// <summary> /// Formats text to represent a generalized value. /// </summary> /// <param name="val">The value</param> /// <returns>The formatted text</returns> public static string FormatValue(object val) { if (val == null) return Fmt_Null; var context = TestExecutionContext.CurrentContext; if (context != null) return context.CurrentValueFormatter(val); else return DefaultValueFormatter(val); } /// <summary> /// Formats text for a collection value, /// starting at a particular point, to a max length /// </summary> /// <param name="collection">The collection containing elements to write.</param> /// <param name="start">The starting point of the elements to write</param> /// <param name="max">The maximum number of elements to write</param> public static string FormatCollection(IEnumerable collection, long start, int max) { int count = 0; int index = 0; System.Text.StringBuilder sb = new System.Text.StringBuilder(); foreach (object obj in collection) { if (index++ >= start) { if (++count > max) break; sb.Append(count == 1 ? "< " : ", "); sb.Append(FormatValue(obj)); } } if (count == 0) return Fmt_EmptyCollection; if (count > max) sb.Append("..."); sb.Append(" >"); return sb.ToString(); } private static string FormatArray(Array array) { if (array.Length == 0) return Fmt_EmptyCollection; int rank = array.Rank; int[] products = new int[rank]; for (int product = 1, r = rank; --r >= 0; ) products[r] = product *= array.GetLength(r); int count = 0; System.Text.StringBuilder sb = new System.Text.StringBuilder(); foreach (object obj in array) { if (count > 0) sb.Append(", "); bool startSegment = false; for (int r = 0; r < rank; r++) { startSegment = startSegment || count % products[r] == 0; if (startSegment) sb.Append("< "); } sb.Append(FormatValue(obj)); ++count; bool nextSegment = false; for (int r = 0; r < rank; r++) { nextSegment = nextSegment || count % products[r] == 0; if (nextSegment) sb.Append(" >"); } } return sb.ToString(); } private static string FormatString(string s) { return s == string.Empty ? Fmt_EmptyString : string.Format(Fmt_String, s); } private static string FormatDouble(double d) { if (double.IsNaN(d) || double.IsInfinity(d)) return d.ToString(); else { string s = d.ToString("G17", CultureInfo.InvariantCulture); if (s.IndexOf('.') > 0) return s + "d"; else return s + ".0d"; } } private static string FormatFloat(float f) { if (float.IsNaN(f) || float.IsInfinity(f)) return f.ToString(); else { string s = f.ToString("G9", CultureInfo.InvariantCulture); if (s.IndexOf('.') > 0) return s + "f"; else return s + ".0f"; } } private static string FormatDecimal(Decimal d) { return d.ToString("G29", CultureInfo.InvariantCulture) + "m"; } private static string FormatDateTime(DateTime dt) { return dt.ToString(Fmt_DateTime, CultureInfo.InvariantCulture); } #if !NETCF private static string FormatDateTimeOffset(DateTimeOffset dto) { return dto.ToString(Fmt_DateTimeOffset, CultureInfo.InvariantCulture); } #endif /// <summary> /// Returns the representation of a type as used in NUnitLite. /// This is the same as Type.ToString() except for arrays, /// which are displayed with their declared sizes. /// </summary> /// <param name="obj"></param> /// <returns></returns> public static string GetTypeRepresentation(object obj) { Array array = obj as Array; if (array == null) return string.Format("<{0}>", obj.GetType()); StringBuilder sb = new StringBuilder(); Type elementType = array.GetType(); int nest = 0; while (elementType.IsArray) { elementType = elementType.GetElementType(); ++nest; } sb.Append(elementType.ToString()); sb.Append('['); for (int r = 0; r < array.Rank; r++) { if (r > 0) sb.Append(','); sb.Append(array.GetLength(r)); } sb.Append(']'); while (--nest > 0) sb.Append("[]"); return string.Format("<{0}>", sb.ToString()); } /// <summary> /// Converts any control characters in a string /// to their escaped representation. /// </summary> /// <param name="s">The string to be converted</param> /// <returns>The converted string</returns> public static string EscapeControlChars(string s) { if (s != null) { StringBuilder sb = new StringBuilder(); foreach (char c in s) { switch (c) { //case '\'': // sb.Append("\\\'"); // break; //case '\"': // sb.Append("\\\""); // break; case '\\': sb.Append("\\\\"); break; case '\0': sb.Append("\\0"); break; case '\a': sb.Append("\\a"); break; case '\b': sb.Append("\\b"); break; case '\f': sb.Append("\\f"); break; case '\n': sb.Append("\\n"); break; case '\r': sb.Append("\\r"); break; case '\t': sb.Append("\\t"); break; case '\v': sb.Append("\\v"); break; case '\x0085': case '\x2028': case '\x2029': sb.Append(string.Format("\\x{0:X4}", (int)c)); break; default: sb.Append(c); break; } } s = sb.ToString(); } return s; } /// <summary> /// Return the a string representation for a set of indices into an array /// </summary> /// <param name="indices">Array of indices for which a string is needed</param> public static string GetArrayIndicesAsString(int[] indices) { StringBuilder sb = new StringBuilder(); sb.Append('['); for (int r = 0; r < indices.Length; r++) { if (r > 0) sb.Append(','); sb.Append(indices[r].ToString()); } sb.Append(']'); return sb.ToString(); } /// <summary> /// Get an array of indices representing the point in a collection or /// array corresponding to a single int index into the collection. /// </summary> /// <param name="collection">The collection to which the indices apply</param> /// <param name="index">Index in the collection</param> /// <returns>Array of indices</returns> public static int[] GetArrayIndicesFromCollectionIndex(IEnumerable collection, long index) { Array array = collection as Array; int rank = array == null ? 1 : array.Rank; int[] result = new int[rank]; for (int r = rank; --r > 0; ) { int l = array.GetLength(r); result[r] = (int)index % l; index /= l; } result[0] = (int)index; return result; } /// <summary> /// Clip a string to a given length, starting at a particular offset, returning the clipped /// string with ellipses representing the removed parts /// </summary> /// <param name="s">The string to be clipped</param> /// <param name="maxStringLength">The maximum permitted length of the result string</param> /// <param name="clipStart">The point at which to start clipping</param> /// <returns>The clipped string</returns> public static string ClipString(string s, int maxStringLength, int clipStart) { int clipLength = maxStringLength; StringBuilder sb = new StringBuilder(); if (clipStart > 0) { clipLength -= ELLIPSIS.Length; sb.Append(ELLIPSIS); } if (s.Length - clipStart > clipLength) { clipLength -= ELLIPSIS.Length; sb.Append(s.Substring(clipStart, clipLength)); sb.Append(ELLIPSIS); } else if (clipStart > 0) sb.Append(s.Substring(clipStart)); else sb.Append(s); return sb.ToString(); } /// <summary> /// Clip the expected and actual strings in a coordinated fashion, /// so that they may be displayed together. /// </summary> /// <param name="expected"></param> /// <param name="actual"></param> /// <param name="maxDisplayLength"></param> /// <param name="mismatch"></param> public static void ClipExpectedAndActual(ref string expected, ref string actual, int maxDisplayLength, int mismatch) { // Case 1: Both strings fit on line int maxStringLength = Math.Max(expected.Length, actual.Length); if (maxStringLength <= maxDisplayLength) return; // Case 2: Assume that the tail of each string fits on line int clipLength = maxDisplayLength - ELLIPSIS.Length; int clipStart = maxStringLength - clipLength; // Case 3: If it doesn't, center the mismatch position if (clipStart > mismatch) clipStart = Math.Max(0, mismatch - clipLength / 2); expected = ClipString(expected, maxDisplayLength, clipStart); actual = ClipString(actual, maxDisplayLength, clipStart); } /// <summary> /// Shows the position two strings start to differ. Comparison /// starts at the start index. /// </summary> /// <param name="expected">The expected string</param> /// <param name="actual">The actual string</param> /// <param name="istart">The index in the strings at which comparison should start</param> /// <param name="ignoreCase">Boolean indicating whether case should be ignored</param> /// <returns>-1 if no mismatch found, or the index where mismatch found</returns> static public int FindMismatchPosition(string expected, string actual, int istart, bool ignoreCase) { int length = Math.Min(expected.Length, actual.Length); string s1 = ignoreCase ? expected.ToLower() : expected; string s2 = ignoreCase ? actual.ToLower() : actual; for (int i = istart; i < length; i++) { if (s1[i] != s2[i]) return i; } // // Strings have same content up to the length of the shorter string. // Mismatch occurs because string lengths are different, so show // that they start differing where the shortest string ends // if (expected.Length != actual.Length) return length; // // Same strings : We shouldn't get here // return -1; } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Reflection; using log4net; using Mono.Addins; using Nini.Config; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Services.Interfaces; namespace OpenSim.Region.CoreModules.Avatar.Inventory.Transfer { [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "InventoryTransferModule")] public class InventoryTransferModule : ISharedRegionModule { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); /// <summary> private List<Scene> m_Scenelist = new List<Scene>(); private IMessageTransferModule m_TransferModule; private bool m_Enabled = true; #region Region Module interface public void Initialise(IConfigSource config) { if (config.Configs["Messaging"] != null) { // Allow disabling this module in config // if (config.Configs["Messaging"].GetString( "InventoryTransferModule", "InventoryTransferModule") != "InventoryTransferModule") { m_Enabled = false; return; } } } public void AddRegion(Scene scene) { if (!m_Enabled) return; m_Scenelist.Add(scene); // scene.RegisterModuleInterface<IInventoryTransferModule>(this); scene.EventManager.OnNewClient += OnNewClient; scene.EventManager.OnIncomingInstantMessage += OnGridInstantMessage; } public void RegionLoaded(Scene scene) { if (m_TransferModule == null) { m_TransferModule = m_Scenelist[0].RequestModuleInterface<IMessageTransferModule>(); if (m_TransferModule == null) { m_log.Error("[INVENTORY TRANSFER]: No Message transfer module found, transfers will be local only"); m_Enabled = false; // m_Scenelist.Clear(); // scene.EventManager.OnNewClient -= OnNewClient; scene.EventManager.OnIncomingInstantMessage -= OnGridInstantMessage; } } } public void RemoveRegion(Scene scene) { scene.EventManager.OnNewClient -= OnNewClient; scene.EventManager.OnIncomingInstantMessage -= OnGridInstantMessage; m_Scenelist.Remove(scene); } public void PostInitialise() { } public void Close() { } public string Name { get { return "InventoryModule"; } } public Type ReplaceableInterface { get { return null; } } #endregion private void OnNewClient(IClientAPI client) { // Inventory giving is conducted via instant message client.OnInstantMessage += OnInstantMessage; } private Scene FindClientScene(UUID agentId) { lock (m_Scenelist) { foreach (Scene scene in m_Scenelist) { ScenePresence presence = scene.GetScenePresence(agentId); if (presence != null) return scene; } } return null; } private void OnInstantMessage(IClientAPI client, GridInstantMessage im) { // m_log.DebugFormat( // "[INVENTORY TRANSFER]: {0} IM type received from client {1}. From={2} ({3}), To={4}", // (InstantMessageDialog)im.dialog, client.Name, // im.fromAgentID, im.fromAgentName, im.toAgentID); Scene scene = FindClientScene(client.AgentId); if (scene == null) // Something seriously wrong here. return; if (im.dialog == (byte) InstantMessageDialog.InventoryOffered) { //m_log.DebugFormat("Asset type {0}", ((AssetType)im.binaryBucket[0])); if (im.binaryBucket.Length < 17) // Invalid return; UUID receipientID = new UUID(im.toAgentID); ScenePresence user = scene.GetScenePresence(receipientID); UUID copyID; // First byte is the asset type AssetType assetType = (AssetType)im.binaryBucket[0]; if (AssetType.Folder == assetType) { UUID folderID = new UUID(im.binaryBucket, 1); m_log.DebugFormat( "[INVENTORY TRANSFER]: Inserting original folder {0} into agent {1}'s inventory", folderID, new UUID(im.toAgentID)); InventoryFolderBase folderCopy = scene.GiveInventoryFolder(receipientID, client.AgentId, folderID, UUID.Zero); if (folderCopy == null) { client.SendAgentAlertMessage("Can't find folder to give. Nothing given.", false); return; } // The outgoing binary bucket should contain only the byte which signals an asset folder is // being copied and the following bytes for the copied folder's UUID copyID = folderCopy.ID; byte[] copyIDBytes = copyID.GetBytes(); im.binaryBucket = new byte[1 + copyIDBytes.Length]; im.binaryBucket[0] = (byte)AssetType.Folder; Array.Copy(copyIDBytes, 0, im.binaryBucket, 1, copyIDBytes.Length); if (user != null) user.ControllingClient.SendBulkUpdateInventory(folderCopy); // HACK!! // Insert the ID of the copied folder into the IM so that we know which item to move to trash if it // is rejected. // XXX: This is probably a misuse of the session ID slot. im.imSessionID = copyID.Guid; } else { // First byte of the array is probably the item type // Next 16 bytes are the UUID UUID itemID = new UUID(im.binaryBucket, 1); m_log.DebugFormat("[INVENTORY TRANSFER]: (giving) Inserting item {0} "+ "into agent {1}'s inventory", itemID, new UUID(im.toAgentID)); InventoryItemBase itemCopy = scene.GiveInventoryItem( new UUID(im.toAgentID), client.AgentId, itemID); if (itemCopy == null) { client.SendAgentAlertMessage("Can't find item to give. Nothing given.", false); return; } copyID = itemCopy.ID; Array.Copy(copyID.GetBytes(), 0, im.binaryBucket, 1, 16); if (user != null) user.ControllingClient.SendBulkUpdateInventory(itemCopy); // HACK!! // Insert the ID of the copied item into the IM so that we know which item to move to trash if it // is rejected. // XXX: This is probably a misuse of the session ID slot. im.imSessionID = copyID.Guid; } // Send the IM to the recipient. The item is already // in their inventory, so it will not be lost if // they are offline. // if (user != null) { user.ControllingClient.SendInstantMessage(im); return; } else { if (m_TransferModule != null) m_TransferModule.SendInstantMessage(im, delegate(bool success) { if (!success) client.SendAlertMessage("User not online. Inventory has been saved"); }); } } else if (im.dialog == (byte) InstantMessageDialog.InventoryAccepted) { ScenePresence user = scene.GetScenePresence(new UUID(im.toAgentID)); if (user != null) // Local { user.ControllingClient.SendInstantMessage(im); } else { if (m_TransferModule != null) m_TransferModule.SendInstantMessage(im, delegate(bool success) { // justincc - FIXME: Comment out for now. This code was added in commit db91044 Mon Aug 22 2011 // and is apparently supposed to fix bulk inventory updates after accepting items. But // instead it appears to cause two copies of an accepted folder for the receiving user in // at least some cases. Folder/item update is already done when the offer is made (see code above) // // Send BulkUpdateInventory // IInventoryService invService = scene.InventoryService; // UUID inventoryEntityID = new UUID(im.imSessionID); // The inventory item /folder, back from it's trip // // InventoryFolderBase folder = new InventoryFolderBase(inventoryEntityID, client.AgentId); // folder = invService.GetFolder(folder); // // ScenePresence fromUser = scene.GetScenePresence(new UUID(im.fromAgentID)); // // // If the user has left the scene by the time the message comes back then we can't send // // them the update. // if (fromUser != null) // fromUser.ControllingClient.SendBulkUpdateInventory(folder); }); } } // XXX: This code was placed here to try and accomodate RLV which moves given folders named #RLV/~<name> // to the requested folder, which in this case is #RLV. However, it is the viewer that appears to be // response from renaming the #RLV/~example folder to ~example. For some reason this is not yet // happening, possibly because we are not sending the correct inventory update messages with the correct // transaction IDs else if (im.dialog == (byte) InstantMessageDialog.TaskInventoryAccepted) { UUID destinationFolderID = UUID.Zero; if (im.binaryBucket != null && im.binaryBucket.Length >= 16) { destinationFolderID = new UUID(im.binaryBucket, 0); } if (destinationFolderID != UUID.Zero) { InventoryFolderBase destinationFolder = new InventoryFolderBase(destinationFolderID, client.AgentId); if (destinationFolder == null) { m_log.WarnFormat( "[INVENTORY TRANSFER]: TaskInventoryAccepted message from {0} in {1} specified folder {2} which does not exist", client.Name, scene.Name, destinationFolderID); return; } IInventoryService invService = scene.InventoryService; UUID inventoryID = new UUID(im.imSessionID); // The inventory item/folder, back from it's trip InventoryItemBase item = new InventoryItemBase(inventoryID, client.AgentId); item = invService.GetItem(item); InventoryFolderBase folder = null; UUID? previousParentFolderID = null; if (item != null) // It's an item { previousParentFolderID = item.Folder; item.Folder = destinationFolderID; invService.DeleteItems(item.Owner, new List<UUID>() { item.ID }); scene.AddInventoryItem(client, item); } else { folder = new InventoryFolderBase(inventoryID, client.AgentId); folder = invService.GetFolder(folder); if (folder != null) // It's a folder { previousParentFolderID = folder.ParentID; folder.ParentID = destinationFolderID; invService.MoveFolder(folder); } } // Tell client about updates to original parent and new parent (this should probably be factored with existing move item/folder code). if (previousParentFolderID != null) { InventoryFolderBase previousParentFolder = new InventoryFolderBase((UUID)previousParentFolderID, client.AgentId); previousParentFolder = invService.GetFolder(previousParentFolder); scene.SendInventoryUpdate(client, previousParentFolder, true, true); scene.SendInventoryUpdate(client, destinationFolder, true, true); } } } else if ( im.dialog == (byte)InstantMessageDialog.InventoryDeclined || im.dialog == (byte)InstantMessageDialog.TaskInventoryDeclined) { // Here, the recipient is local and we can assume that the // inventory is loaded. Courtesy of the above bulk update, // It will have been pushed to the client, too // IInventoryService invService = scene.InventoryService; InventoryFolderBase trashFolder = invService.GetFolderForType(client.AgentId, AssetType.TrashFolder); UUID inventoryID = new UUID(im.imSessionID); // The inventory item/folder, back from it's trip InventoryItemBase item = new InventoryItemBase(inventoryID, client.AgentId); item = invService.GetItem(item); InventoryFolderBase folder = null; UUID? previousParentFolderID = null; if (item != null && trashFolder != null) { previousParentFolderID = item.Folder; item.Folder = trashFolder.ID; // Diva comment: can't we just update this item??? List<UUID> uuids = new List<UUID>(); uuids.Add(item.ID); invService.DeleteItems(item.Owner, uuids); scene.AddInventoryItem(client, item); } else { folder = new InventoryFolderBase(inventoryID, client.AgentId); folder = invService.GetFolder(folder); if (folder != null & trashFolder != null) { previousParentFolderID = folder.ParentID; folder.ParentID = trashFolder.ID; invService.MoveFolder(folder); } } if ((null == item && null == folder) | null == trashFolder) { string reason = String.Empty; if (trashFolder == null) reason += " Trash folder not found."; if (item == null) reason += " Item not found."; if (folder == null) reason += " Folder not found."; client.SendAgentAlertMessage("Unable to delete "+ "received inventory" + reason, false); } // Tell client about updates to original parent and new parent (this should probably be factored with existing move item/folder code). else if (previousParentFolderID != null) { InventoryFolderBase previousParentFolder = new InventoryFolderBase((UUID)previousParentFolderID, client.AgentId); previousParentFolder = invService.GetFolder(previousParentFolder); scene.SendInventoryUpdate(client, previousParentFolder, true, true); scene.SendInventoryUpdate(client, trashFolder, true, true); } if (im.dialog == (byte)InstantMessageDialog.InventoryDeclined) { ScenePresence user = scene.GetScenePresence(new UUID(im.toAgentID)); if (user != null) // Local { user.ControllingClient.SendInstantMessage(im); } else { if (m_TransferModule != null) m_TransferModule.SendInstantMessage(im, delegate(bool success) { }); } } } } /// <summary> /// /// </summary> /// <param name="im"></param> private void OnGridInstantMessage(GridInstantMessage im) { // Check if it's a type of message that we should handle if (!((im.dialog == (byte) InstantMessageDialog.InventoryOffered) || (im.dialog == (byte) InstantMessageDialog.InventoryAccepted) || (im.dialog == (byte) InstantMessageDialog.InventoryDeclined) || (im.dialog == (byte) InstantMessageDialog.TaskInventoryDeclined))) return; m_log.DebugFormat( "[INVENTORY TRANSFER]: {0} IM type received from grid. From={1} ({2}), To={3}", (InstantMessageDialog)im.dialog, im.fromAgentID, im.fromAgentName, im.toAgentID); // Check if this is ours to handle // Scene scene = FindClientScene(new UUID(im.toAgentID)); if (scene == null) return; // Find agent to deliver to // ScenePresence user = scene.GetScenePresence(new UUID(im.toAgentID)); if (user != null) { user.ControllingClient.SendInstantMessage(im); if (im.dialog == (byte)InstantMessageDialog.InventoryOffered) { AssetType assetType = (AssetType)im.binaryBucket[0]; UUID inventoryID = new UUID(im.binaryBucket, 1); IInventoryService invService = scene.InventoryService; InventoryNodeBase node = null; if (AssetType.Folder == assetType) { InventoryFolderBase folder = new InventoryFolderBase(inventoryID, new UUID(im.toAgentID)); node = invService.GetFolder(folder); } else { InventoryItemBase item = new InventoryItemBase(inventoryID, new UUID(im.toAgentID)); node = invService.GetItem(item); } if (node != null) user.ControllingClient.SendBulkUpdateInventory(node); } } } } }
// <copyright file="DesiredCapabilities.cs" company="WebDriver Committers"> // Licensed to the Software Freedom Conservancy (SFC) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The SFC licenses this file // to you under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> using System; using System.Collections.Generic; using System.Globalization; namespace OpenQA.Selenium.Remote { /// <summary> /// Class to Create the capabilities of the browser you require for <see cref="IWebDriver"/>. /// If you wish to use default values use the static methods /// </summary> public class DesiredCapabilities : ICapabilities, ISpecificationCompliant { private readonly Dictionary<string, object> capabilities = new Dictionary<string, object>(); private bool isSpecCompliant; /// <summary> /// Initializes a new instance of the <see cref="DesiredCapabilities"/> class /// </summary> /// <param name="browser">Name of the browser e.g. firefox, internet explorer, safari</param> /// <param name="version">Version of the browser</param> /// <param name="platform">The platform it works on</param> public DesiredCapabilities(string browser, string version, Platform platform) { this.SetCapability(CapabilityType.BrowserName, browser); this.SetCapability(CapabilityType.Version, version); this.SetCapability(CapabilityType.Platform, platform); } /// <summary> /// Initializes a new instance of the <see cref="DesiredCapabilities"/> class /// </summary> public DesiredCapabilities() { } /// <summary> /// Initializes a new instance of the <see cref="DesiredCapabilities"/> class /// </summary> /// <param name="rawMap">Dictionary of items for the remote driver</param> /// <example> /// <code> /// DesiredCapabilities capabilities = new DesiredCapabilities(new Dictionary<![CDATA[<string,object>]]>(){["browserName","firefox"],["version",string.Empty],["javaScript",true]}); /// </code> /// </example> public DesiredCapabilities(Dictionary<string, object> rawMap) { if (rawMap != null) { foreach (string key in rawMap.Keys) { if (key == CapabilityType.Platform) { object raw = rawMap[CapabilityType.Platform]; string rawAsString = raw as string; Platform rawAsPlatform = raw as Platform; if (rawAsString != null) { this.SetCapability(CapabilityType.Platform, Platform.FromString(rawAsString)); } else if (rawAsPlatform != null) { this.SetCapability(CapabilityType.Platform, rawAsPlatform); } } else { this.SetCapability(key, rawMap[key]); } } } } /// <summary> /// Initializes a new instance of the <see cref="DesiredCapabilities"/> class /// </summary> /// <param name="browser">Name of the browser e.g. firefox, internet explorer, safari</param> /// <param name="version">Version of the browser</param> /// <param name="platform">The platform it works on</param> /// <param name="isSpecCompliant">Sets a value indicating whether the capabilities are /// compliant with the W3C WebDriver specification.</param> internal DesiredCapabilities(string browser, string version, Platform platform, bool isSpecCompliant) { this.SetCapability(CapabilityType.BrowserName, browser); this.SetCapability(CapabilityType.Version, version); this.SetCapability(CapabilityType.Platform, platform); this.isSpecCompliant = isSpecCompliant; } /// <summary> /// Gets the browser name /// </summary> public string BrowserName { get { string name = string.Empty; object capabilityValue = this.GetCapability(CapabilityType.BrowserName); if (capabilityValue != null) { name = capabilityValue.ToString(); } return name; } } /// <summary> /// Gets or sets the platform /// </summary> public Platform Platform { get { return this.GetCapability(CapabilityType.Platform) as Platform ?? new Platform(PlatformType.Any); } set { this.SetCapability(CapabilityType.Platform, value); } } /// <summary> /// Gets the browser version /// </summary> public string Version { get { string browserVersion = string.Empty; object capabilityValue = this.GetCapability(CapabilityType.Version); if (capabilityValue != null) { browserVersion = capabilityValue.ToString(); } return browserVersion; } } /// <summary> /// Gets or sets a value indicating whether the browser accepts SSL certificates. /// </summary> public bool AcceptInsecureCerts { get { bool acceptSSLCerts = false; object capabilityValue = this.GetCapability(CapabilityType.AcceptInsecureCertificates); if (capabilityValue != null) { acceptSSLCerts = (bool)capabilityValue; } return acceptSSLCerts; } set { this.SetCapability(CapabilityType.AcceptInsecureCertificates, value); } } /// <summary> /// Gets or sets a value indicating whether this set of capabilities is compliant with the W3C WebDriver specification. /// </summary> bool ISpecificationCompliant.IsSpecificationCompliant { get { return this.isSpecCompliant; } set { this.isSpecCompliant = value; } } /// <summary> /// Gets the internal capabilities dictionary. /// </summary> internal Dictionary<string, object> CapabilitiesDictionary { get { return this.capabilities; } } /// <summary> /// Method to return a new DesiredCapabilities using defaults /// </summary> /// <returns>New instance of DesiredCapabilities for use with Firefox</returns> [Obsolete("Use the FirefoxOptions class to set capabilities for use with Firefox. For use with the Java remote server or grid, use the ToCapabilites method of the FirefoxOptions class.")] public static DesiredCapabilities Firefox() { DesiredCapabilities dc = new DesiredCapabilities("firefox", string.Empty, new Platform(PlatformType.Any)); dc.AcceptInsecureCerts = true; return dc; } /// <summary> /// Method to return a new DesiredCapabilities using defaults /// </summary> /// <returns>New instance of DesiredCapabilities for use with Firefox</returns> public static DesiredCapabilities PhantomJS() { DesiredCapabilities dc = new DesiredCapabilities("phantomjs", string.Empty, new Platform(PlatformType.Any)); dc.isSpecCompliant = false; return dc; } /// <summary> /// Method to return a new DesiredCapabilities using defaults /// </summary> /// <returns>New instance of DesiredCapabilities for use with Internet Explorer</returns> [Obsolete("Use the InternetExplorerOptions class to set capabilities for use with Internet Explorer. For use with the Java remote server or grid, use the ToCapabilites method of the InternetExplorerOptions class.")] public static DesiredCapabilities InternetExplorer() { return new DesiredCapabilities("internet explorer", string.Empty, new Platform(PlatformType.Windows)); } /// <summary> /// Method to return a new DesiredCapabilities using defaults /// </summary> /// <returns>New instance of DesiredCapabilities for use with Microsoft Edge</returns> [Obsolete("Use the EdgeOptions class to set capabilities for use with Edge. For use with the Java remote server or grid, use the ToCapabilites method of the EdgeOptions class.")] public static DesiredCapabilities Edge() { DesiredCapabilities dc = new DesiredCapabilities("MicrosoftEdge", string.Empty, new Platform(PlatformType.Windows)); dc.isSpecCompliant = false; return dc; } /// <summary> /// Method to return a new DesiredCapabilities using defaults /// </summary> /// <returns>New instance of DesiredCapabilities for use with HTMLUnit</returns> public static DesiredCapabilities HtmlUnit() { DesiredCapabilities dc = new DesiredCapabilities("htmlunit", string.Empty, new Platform(PlatformType.Any)); dc.isSpecCompliant = false; return dc; } /// <summary> /// Method to return a new DesiredCapabilities using defaults /// </summary> /// <returns>New instance of DesiredCapabilities for use with HTMLUnit with JS</returns> public static DesiredCapabilities HtmlUnitWithJavaScript() { DesiredCapabilities dc = new DesiredCapabilities("htmlunit", string.Empty, new Platform(PlatformType.Any)); dc.SetCapability(CapabilityType.IsJavaScriptEnabled, true); dc.isSpecCompliant = false; return dc; } /// <summary> /// Method to return a new DesiredCapabilities using defaults /// </summary> /// <returns>New instance of DesiredCapabilities for use with iPhone</returns> [Obsolete("Selenium no longer provides an iOS device driver.")] public static DesiredCapabilities IPhone() { return new DesiredCapabilities("iPhone", string.Empty, new Platform(PlatformType.Mac)); } /// <summary> /// Method to return a new DesiredCapabilities using defaults /// </summary> /// <returns>New instance of DesiredCapabilities for use with iPad</returns> [Obsolete("Selenium no longer provides an iOS device driver.")] public static DesiredCapabilities IPad() { return new DesiredCapabilities("iPad", string.Empty, new Platform(PlatformType.Mac)); } /// <summary> /// Method to return a new DesiredCapabilities using defaults /// </summary> /// <returns>New instance of DesiredCapabilities for use with Chrome</returns> [Obsolete("Use the ChromeOptions class to set capabilities for use with Chrome. For use with the Java remote server or grid, use the ToCapabilites method of the ChromeOptions class.")] public static DesiredCapabilities Chrome() { // This is strangely inconsistent. DesiredCapabilities dc = new DesiredCapabilities("chrome", string.Empty, new Platform(PlatformType.Any)); dc.isSpecCompliant = false; return dc; } /// <summary> /// Method to return a new DesiredCapabilities using defaults /// </summary> /// <returns>New instance of DesiredCapabilities for use with Android</returns> [Obsolete("Selenium no longer provides an Android device driver.")] public static DesiredCapabilities Android() { return new DesiredCapabilities("android", string.Empty, new Platform(PlatformType.Android)); } /// <summary> /// Method to return a new DesiredCapabilities using defaults /// </summary> /// <returns>New instance of DesiredCapabilities for use with Opera</returns> [Obsolete("Use the OperaOptions class to set capabilities for use with Opera. For use with the Java remote server or grid, use the ToCapabilites method of the OperaOptions class.")] public static DesiredCapabilities Opera() { DesiredCapabilities dc = new DesiredCapabilities("opera", string.Empty, new Platform(PlatformType.Any)); dc.isSpecCompliant = false; return dc; } /// <summary> /// Method to return a new DesiredCapabilities using defaults /// </summary> /// <returns>New instance of DesiredCapabilities for use with Safari</returns> [Obsolete("Use the SafariOptions class to set capabilities for use with Safari. For use with the Java remote server or grid, use the ToCapabilites method of the SafariOptions class.")] public static DesiredCapabilities Safari() { DesiredCapabilities dc = new DesiredCapabilities("safari", string.Empty, new Platform(PlatformType.Mac)); dc.isSpecCompliant = false; return dc; } /// <summary> /// Gets a value indicating whether the browser has a given capability. /// </summary> /// <param name="capability">The capability to get.</param> /// <returns>Returns <see langword="true"/> if the browser has the capability; otherwise, <see langword="false"/>.</returns> public bool HasCapability(string capability) { return this.capabilities.ContainsKey(capability); } /// <summary> /// Gets a capability of the browser. /// </summary> /// <param name="capability">The capability to get.</param> /// <returns>An object associated with the capability, or <see langword="null"/> /// if the capability is not set on the browser.</returns> public object GetCapability(string capability) { object capabilityValue = null; if (this.capabilities.ContainsKey(capability)) { capabilityValue = this.capabilities[capability]; string capabilityValueString = capabilityValue as string; if (capability == CapabilityType.Platform && capabilityValueString != null) { capabilityValue = Platform.FromString(capabilityValue.ToString()); } } return capabilityValue; } /// <summary> /// Sets a capability of the browser. /// </summary> /// <param name="capability">The capability to get.</param> /// <param name="capabilityValue">The value for the capability.</param> public void SetCapability(string capability, object capabilityValue) { // Handle the special case of Platform objects. These should // be stored in the underlying dictionary as their protocol // string representation. Platform platformCapabilityValue = capabilityValue as Platform; if (platformCapabilityValue != null) { this.capabilities[capability] = platformCapabilityValue.ProtocolPlatformType; } else { this.capabilities[capability] = capabilityValue; } } /// <summary> /// Converts the <see cref="ICapabilities"/> object to a <see cref="Dictionary{TKey, TValue}"/>. /// </summary> /// <returns>The <see cref="Dictionary{TKey, TValue}"/> containing the capabilities.</returns> public Dictionary<string, object> ToDictionary() { // CONSIDER: Instead of returning the raw internal member, // we might want to copy/clone it instead. return this.capabilities; } /// <summary> /// Return HashCode for the DesiredCapabilities that has been created /// </summary> /// <returns>Integer of HashCode generated</returns> public override int GetHashCode() { int result; result = this.BrowserName != null ? this.BrowserName.GetHashCode() : 0; result = (31 * result) + (this.Version != null ? this.Version.GetHashCode() : 0); result = (31 * result) + (this.Platform != null ? this.Platform.GetHashCode() : 0); return result; } /// <summary> /// Return a string of capabilities being used /// </summary> /// <returns>String of capabilities being used</returns> public override string ToString() { return string.Format(CultureInfo.InvariantCulture, "Capabilities [BrowserName={0}, Platform={1}, Version={2}]", this.BrowserName, this.Platform.PlatformType.ToString(), this.Version); } /// <summary> /// Compare two DesiredCapabilities and will return either true or false /// </summary> /// <param name="obj">DesiredCapabilities you wish to compare</param> /// <returns>true if they are the same or false if they are not</returns> public override bool Equals(object obj) { if (this == obj) { return true; } DesiredCapabilities other = obj as DesiredCapabilities; if (other == null) { return false; } if (this.BrowserName != null ? this.BrowserName != other.BrowserName : other.BrowserName != null) { return false; } if (!this.Platform.IsPlatformType(other.Platform.PlatformType)) { return false; } if (this.Version != null ? this.Version != other.Version : other.Version != null) { return false; } return true; } } }
#region Apache License // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion // .NET Compact Framework has no support for Win32 Console API's #if !NETCF using System; using System.Globalization; using System.Runtime.InteropServices; using log4net.Layout; using log4net.Util; namespace log4net.Appender { /// <summary> /// Appends logging events to the console. /// </summary> /// <remarks> /// <para> /// ColoredConsoleAppender appends log events to the standard output stream /// or the error output stream using a layout specified by the /// user. It also allows the color of a specific type of message to be set. /// </para> /// <para> /// By default, all output is written to the console's standard output stream. /// The <see cref="Target"/> property can be set to direct the output to the /// error stream. /// </para> /// <para> /// NOTE: This appender writes directly to the application's attached console /// not to the <c>System.Console.Out</c> or <c>System.Console.Error</c> <c>TextWriter</c>. /// The <c>System.Console.Out</c> and <c>System.Console.Error</c> streams can be /// programmatically redirected (for example NUnit does this to capture program output). /// This appender will ignore these redirections because it needs to use Win32 /// API calls to colorize the output. To respect these redirections the <see cref="ConsoleAppender"/> /// must be used. /// </para> /// <para> /// When configuring the colored console appender, mapping should be /// specified to map a logging level to a color. For example: /// </para> /// <code lang="XML" escaped="true"> /// <mapping> /// <level value="ERROR" /> /// <foreColor value="White" /> /// <backColor value="Red, HighIntensity" /> /// </mapping> /// <mapping> /// <level value="DEBUG" /> /// <backColor value="Green" /> /// </mapping> /// </code> /// <para> /// The Level is the standard log4net logging level and ForeColor and BackColor can be any /// combination of the following values: /// <list type="bullet"> /// <item><term>Blue</term><description></description></item> /// <item><term>Green</term><description></description></item> /// <item><term>Red</term><description></description></item> /// <item><term>White</term><description></description></item> /// <item><term>Yellow</term><description></description></item> /// <item><term>Purple</term><description></description></item> /// <item><term>Cyan</term><description></description></item> /// <item><term>HighIntensity</term><description></description></item> /// </list> /// </para> /// </remarks> /// <author>Rick Hobbs</author> /// <author>Nicko Cadell</author> public class ColoredConsoleAppender : AppenderSkeleton { #region Colors Enum /// <summary> /// The enum of possible color values for use with the color mapping method /// </summary> /// <remarks> /// <para> /// The following flags can be combined together to /// form the colors. /// </para> /// </remarks> /// <seealso cref="ColoredConsoleAppender" /> [Flags] public enum Colors : int { /// <summary> /// color is blue /// </summary> Blue = 0x0001, /// <summary> /// color is green /// </summary> Green = 0x0002, /// <summary> /// color is red /// </summary> Red = 0x0004, /// <summary> /// color is white /// </summary> White = Blue | Green | Red, /// <summary> /// color is yellow /// </summary> Yellow = Red | Green, /// <summary> /// color is purple /// </summary> Purple = Red | Blue, /// <summary> /// color is cyan /// </summary> Cyan = Green | Blue, /// <summary> /// color is intensified /// </summary> HighIntensity = 0x0008, } #endregion // Colors Enum #region Public Instance Constructors /// <summary> /// Initializes a new instance of the <see cref="ColoredConsoleAppender" /> class. /// </summary> /// <remarks> /// The instance of the <see cref="ColoredConsoleAppender" /> class is set up to write /// to the standard output stream. /// </remarks> public ColoredConsoleAppender() { } /// <summary> /// Initializes a new instance of the <see cref="ColoredConsoleAppender" /> class /// with the specified layout. /// </summary> /// <param name="layout">the layout to use for this appender</param> /// <remarks> /// The instance of the <see cref="ColoredConsoleAppender" /> class is set up to write /// to the standard output stream. /// </remarks> [Obsolete("Instead use the default constructor and set the Layout property")] public ColoredConsoleAppender(ILayout layout) : this(layout, false) { } /// <summary> /// Initializes a new instance of the <see cref="ColoredConsoleAppender" /> class /// with the specified layout. /// </summary> /// <param name="layout">the layout to use for this appender</param> /// <param name="writeToErrorStream">flag set to <c>true</c> to write to the console error stream</param> /// <remarks> /// When <paramref name="writeToErrorStream" /> is set to <c>true</c>, output is written to /// the standard error output stream. Otherwise, output is written to the standard /// output stream. /// </remarks> [Obsolete("Instead use the default constructor and set the Layout & Target properties")] public ColoredConsoleAppender(ILayout layout, bool writeToErrorStream) { Layout = layout; m_writeToErrorStream = writeToErrorStream; } #endregion // Public Instance Constructors #region Public Instance Properties /// <summary> /// Target is the value of the console output stream. /// This is either <c>"Console.Out"</c> or <c>"Console.Error"</c>. /// </summary> /// <value> /// Target is the value of the console output stream. /// This is either <c>"Console.Out"</c> or <c>"Console.Error"</c>. /// </value> /// <remarks> /// <para> /// Target is the value of the console output stream. /// This is either <c>"Console.Out"</c> or <c>"Console.Error"</c>. /// </para> /// </remarks> virtual public string Target { get { return m_writeToErrorStream ? ConsoleError : ConsoleOut; } set { string v = value.Trim(); if (string.Compare(ConsoleError, v, true, CultureInfo.InvariantCulture) == 0) { m_writeToErrorStream = true; } else { m_writeToErrorStream = false; } } } /// <summary> /// Add a mapping of level to color - done by the config file /// </summary> /// <param name="mapping">The mapping to add</param> /// <remarks> /// <para> /// Add a <see cref="LevelColors"/> mapping to this appender. /// Each mapping defines the foreground and background colors /// for a level. /// </para> /// </remarks> public void AddMapping(LevelColors mapping) { m_levelMapping.Add(mapping); } #endregion // Public Instance Properties #region Override implementation of AppenderSkeleton /// <summary> /// This method is called by the <see cref="M:AppenderSkeleton.DoAppend(log4net.Core.LoggingEvent)"/> method. /// </summary> /// <param name="loggingEvent">The event to log.</param> /// <remarks> /// <para> /// Writes the event to the console. /// </para> /// <para> /// The format of the output will depend on the appender's layout. /// </para> /// </remarks> #if FRAMEWORK_4_0_OR_ABOVE [System.Security.SecuritySafeCritical] #endif [System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand, UnmanagedCode = true)] override protected void Append(log4net.Core.LoggingEvent loggingEvent) { if (m_consoleOutputWriter != null) { IntPtr consoleHandle = IntPtr.Zero; if (m_writeToErrorStream) { // Write to the error stream consoleHandle = GetStdHandle(STD_ERROR_HANDLE); } else { // Write to the output stream consoleHandle = GetStdHandle(STD_OUTPUT_HANDLE); } // Default to white on black ushort colorInfo = (ushort)Colors.White; // see if there is a specified lookup LevelColors levelColors = m_levelMapping.Lookup(loggingEvent.Level) as LevelColors; if (levelColors != null) { colorInfo = levelColors.CombinedColor; } // Render the event to a string string strLoggingMessage = RenderLoggingEvent(loggingEvent); // get the current console color - to restore later CONSOLE_SCREEN_BUFFER_INFO bufferInfo; GetConsoleScreenBufferInfo(consoleHandle, out bufferInfo); // set the console colors SetConsoleTextAttribute(consoleHandle, colorInfo); // Using WriteConsoleW seems to be unreliable. // If a large buffer is written, say 15,000 chars // Followed by a larger buffer, say 20,000 chars // then WriteConsoleW will fail, last error 8 // 'Not enough storage is available to process this command.' // // Although the documentation states that the buffer must // be less that 64KB (i.e. 32,000 WCHARs) the longest string // that I can write out a the first call to WriteConsoleW // is only 30,704 chars. // // Unlike the WriteFile API the WriteConsoleW method does not // seem to be able to partially write out from the input buffer. // It does have a lpNumberOfCharsWritten parameter, but this is // either the length of the input buffer if any output was written, // or 0 when an error occurs. // // All results above were observed on Windows XP SP1 running // .NET runtime 1.1 SP1. // // Old call to WriteConsoleW: // // WriteConsoleW( // consoleHandle, // strLoggingMessage, // (UInt32)strLoggingMessage.Length, // out (UInt32)ignoreWrittenCount, // IntPtr.Zero); // // Instead of calling WriteConsoleW we use WriteFile which // handles large buffers correctly. Because WriteFile does not // handle the codepage conversion as WriteConsoleW does we // need to use a System.IO.StreamWriter with the appropriate // Encoding. The WriteFile calls are wrapped up in the // System.IO.__ConsoleStream internal class obtained through // the System.Console.OpenStandardOutput method. // // See the ActivateOptions method below for the code that // retrieves and wraps the stream. // The windows console uses ScrollConsoleScreenBuffer internally to // scroll the console buffer when the display buffer of the console // has been used up. ScrollConsoleScreenBuffer fills the area uncovered // by moving the current content with the background color // currently specified on the console. This means that it fills the // whole line in front of the cursor position with the current // background color. // This causes an issue when writing out text with a non default // background color. For example; We write a message with a Blue // background color and the scrollable area of the console is full. // When we write the newline at the end of the message the console // needs to scroll the buffer to make space available for the new line. // The ScrollConsoleScreenBuffer internals will fill the newly created // space with the current background color: Blue. // We then change the console color back to default (White text on a // Black background). We write some text to the console, the text is // written correctly in White with a Black background, however the // remainder of the line still has a Blue background. // // This causes a disjointed appearance to the output where the background // colors change. // // This can be remedied by restoring the console colors before causing // the buffer to scroll, i.e. before writing the last newline. This does // assume that the rendered message will end with a newline. // // Therefore we identify a trailing newline in the message and don't // write this to the output, then we restore the console color and write // a newline. Note that we must AutoFlush before we restore the console // color otherwise we will have no effect. // // There will still be a slight artefact for the last line of the message // will have the background extended to the end of the line, however this // is unlikely to cause any user issues. // // Note that none of the above is visible while the console buffer is scrollable // within the console window viewport, the effects only arise when the actual // buffer is full and needs to be scrolled. char[] messageCharArray = strLoggingMessage.ToCharArray(); int arrayLength = messageCharArray.Length; bool appendNewline = false; // Trim off last newline, if it exists if (arrayLength > 1 && messageCharArray[arrayLength-2] == '\r' && messageCharArray[arrayLength-1] == '\n') { arrayLength -= 2; appendNewline = true; } // Write to the output stream m_consoleOutputWriter.Write(messageCharArray, 0, arrayLength); // Restore the console back to its previous color scheme SetConsoleTextAttribute(consoleHandle, bufferInfo.wAttributes); if (appendNewline) { // Write the newline, after changing the color scheme m_consoleOutputWriter.Write(s_windowsNewline, 0, 2); } } } private static readonly char[] s_windowsNewline = {'\r', '\n'}; /// <summary> /// This appender requires a <see cref="Layout"/> to be set. /// </summary> /// <value><c>true</c></value> /// <remarks> /// <para> /// This appender requires a <see cref="Layout"/> to be set. /// </para> /// </remarks> override protected bool RequiresLayout { get { return true; } } /// <summary> /// Initialize the options for this appender /// </summary> /// <remarks> /// <para> /// Initialize the level to color mappings set on this appender. /// </para> /// </remarks> #if FRAMEWORK_4_0_OR_ABOVE [System.Security.SecuritySafeCritical] #endif [System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand, UnmanagedCode=true)] public override void ActivateOptions() { base.ActivateOptions(); m_levelMapping.ActivateOptions(); System.IO.Stream consoleOutputStream = null; // Use the Console methods to open a Stream over the console std handle if (m_writeToErrorStream) { // Write to the error stream consoleOutputStream = Console.OpenStandardError(); } else { // Write to the output stream consoleOutputStream = Console.OpenStandardOutput(); } // Lookup the codepage encoding for the console System.Text.Encoding consoleEncoding = System.Text.Encoding.GetEncoding(GetConsoleOutputCP()); // Create a writer around the console stream m_consoleOutputWriter = new System.IO.StreamWriter(consoleOutputStream, consoleEncoding, 0x100); m_consoleOutputWriter.AutoFlush = true; // SuppressFinalize on m_consoleOutputWriter because all it will do is flush // and close the file handle. Because we have set AutoFlush the additional flush // is not required. The console file handle should not be closed, so we don't call // Dispose, Close or the finalizer. GC.SuppressFinalize(m_consoleOutputWriter); } #endregion // Override implementation of AppenderSkeleton #region Public Static Fields /// <summary> /// The <see cref="ColoredConsoleAppender.Target"/> to use when writing to the Console /// standard output stream. /// </summary> /// <remarks> /// <para> /// The <see cref="ColoredConsoleAppender.Target"/> to use when writing to the Console /// standard output stream. /// </para> /// </remarks> public const string ConsoleOut = "Console.Out"; /// <summary> /// The <see cref="ColoredConsoleAppender.Target"/> to use when writing to the Console /// standard error output stream. /// </summary> /// <remarks> /// <para> /// The <see cref="ColoredConsoleAppender.Target"/> to use when writing to the Console /// standard error output stream. /// </para> /// </remarks> public const string ConsoleError = "Console.Error"; #endregion // Public Static Fields #region Private Instances Fields /// <summary> /// Flag to write output to the error stream rather than the standard output stream /// </summary> private bool m_writeToErrorStream = false; /// <summary> /// Mapping from level object to color value /// </summary> private LevelMapping m_levelMapping = new LevelMapping(); /// <summary> /// The console output stream writer to write to /// </summary> /// <remarks> /// <para> /// This writer is not thread safe. /// </para> /// </remarks> private System.IO.StreamWriter m_consoleOutputWriter = null; #endregion // Private Instances Fields #region Win32 Methods [DllImport("Kernel32.dll", SetLastError=true, CharSet=CharSet.Auto)] private static extern int GetConsoleOutputCP(); [DllImport("Kernel32.dll", SetLastError=true, CharSet=CharSet.Auto)] private static extern bool SetConsoleTextAttribute( IntPtr consoleHandle, ushort attributes); [DllImport("Kernel32.dll", SetLastError=true, CharSet=CharSet.Auto)] private static extern bool GetConsoleScreenBufferInfo( IntPtr consoleHandle, out CONSOLE_SCREEN_BUFFER_INFO bufferInfo); // [DllImport("Kernel32.dll", SetLastError=true, CharSet=CharSet.Unicode)] // private static extern bool WriteConsoleW( // IntPtr hConsoleHandle, // [MarshalAs(UnmanagedType.LPWStr)] string strBuffer, // UInt32 bufferLen, // out UInt32 written, // IntPtr reserved); //private const UInt32 STD_INPUT_HANDLE = unchecked((UInt32)(-10)); private const UInt32 STD_OUTPUT_HANDLE = unchecked((UInt32)(-11)); private const UInt32 STD_ERROR_HANDLE = unchecked((UInt32)(-12)); [DllImport("Kernel32.dll", SetLastError=true, CharSet=CharSet.Auto)] private static extern IntPtr GetStdHandle( UInt32 type); [StructLayout(LayoutKind.Sequential)] private struct COORD { public UInt16 x; public UInt16 y; } [StructLayout(LayoutKind.Sequential)] private struct SMALL_RECT { public UInt16 Left; public UInt16 Top; public UInt16 Right; public UInt16 Bottom; } [StructLayout(LayoutKind.Sequential)] private struct CONSOLE_SCREEN_BUFFER_INFO { public COORD dwSize; public COORD dwCursorPosition; public ushort wAttributes; public SMALL_RECT srWindow; public COORD dwMaximumWindowSize; } #endregion // Win32 Methods #region LevelColors LevelMapping Entry /// <summary> /// A class to act as a mapping between the level that a logging call is made at and /// the color it should be displayed as. /// </summary> /// <remarks> /// <para> /// Defines the mapping between a level and the color it should be displayed in. /// </para> /// </remarks> public class LevelColors : LevelMappingEntry { private Colors m_foreColor; private Colors m_backColor; private ushort m_combinedColor = 0; /// <summary> /// The mapped foreground color for the specified level /// </summary> /// <remarks> /// <para> /// Required property. /// The mapped foreground color for the specified level. /// </para> /// </remarks> public Colors ForeColor { get { return m_foreColor; } set { m_foreColor = value; } } /// <summary> /// The mapped background color for the specified level /// </summary> /// <remarks> /// <para> /// Required property. /// The mapped background color for the specified level. /// </para> /// </remarks> public Colors BackColor { get { return m_backColor; } set { m_backColor = value; } } /// <summary> /// Initialize the options for the object /// </summary> /// <remarks> /// <para> /// Combine the <see cref="ForeColor"/> and <see cref="BackColor"/> together. /// </para> /// </remarks> public override void ActivateOptions() { base.ActivateOptions(); m_combinedColor = (ushort)( (int)m_foreColor + (((int)m_backColor) << 4) ); } /// <summary> /// The combined <see cref="ForeColor"/> and <see cref="BackColor"/> suitable for /// setting the console color. /// </summary> internal ushort CombinedColor { get { return m_combinedColor; } } } #endregion // LevelColors LevelMapping Entry } } #endif // !NETCF
//--------------------------------------------------------------------------- // // Copyright (C) Microsoft Corporation. All rights reserved. // //--------------------------------------------------------------------------- using System; using System.Collections; using System.ComponentModel; using System.Diagnostics; using System.Windows; using System.Windows.Data; using System.Windows.Input; namespace System.Windows.Controls { /// <summary> /// A column that displays a drop-down list while in edit mode. /// </summary> public class DataGridComboBoxColumn : DataGridColumn { #region Constructors static DataGridComboBoxColumn() { SortMemberPathProperty.OverrideMetadata(typeof(DataGridComboBoxColumn), new FrameworkPropertyMetadata(null, OnCoerceSortMemberPath)); } #endregion #region Helper Type for Styling internal class TextBlockComboBox : ComboBox { static TextBlockComboBox() { DefaultStyleKeyProperty.OverrideMetadata(typeof(TextBlockComboBox), new FrameworkPropertyMetadata(DataGridComboBoxColumn.TextBlockComboBoxStyleKey)); KeyboardNavigation.IsTabStopProperty.OverrideMetadata(typeof(TextBlockComboBox), new FrameworkPropertyMetadata(false)); } } /// <summary> /// Style key for TextBlockComboBox /// </summary> public static ComponentResourceKey TextBlockComboBoxStyleKey { get { return SystemResourceKey.DataGridComboBoxColumnTextBlockComboBoxStyleKey; } } #endregion #region Binding private static object OnCoerceSortMemberPath(DependencyObject d, object baseValue) { var column = (DataGridComboBoxColumn)d; var sortMemberPath = (string)baseValue; if (string.IsNullOrEmpty(sortMemberPath)) { var bindingSortMemberPath = DataGridHelper.GetPathFromBinding(column.EffectiveBinding as Binding); if (!string.IsNullOrEmpty(bindingSortMemberPath)) { sortMemberPath = bindingSortMemberPath; } } return sortMemberPath; } /// <summary> /// Chooses either SelectedItemBinding, TextBinding, SelectedValueBinding or based which are set. /// </summary> private BindingBase EffectiveBinding { get { if (SelectedItemBinding != null) { return SelectedItemBinding; } else if (SelectedValueBinding != null) { return SelectedValueBinding; } else { return TextBinding; } } } /// <summary> /// The binding that will be applied to the SelectedValue property of the ComboBox. This works in conjunction with SelectedValuePath /// </summary> /// <remarks> /// This isn't a DP because if it were getting the value would evaluate the binding. /// </remarks> public virtual BindingBase SelectedValueBinding { get { return _selectedValueBinding; } set { if (_selectedValueBinding != value) { BindingBase oldBinding = _selectedValueBinding; _selectedValueBinding = value; CoerceValue(IsReadOnlyProperty); CoerceValue(SortMemberPathProperty); OnSelectedValueBindingChanged(oldBinding, _selectedValueBinding); } } } protected override bool OnCoerceIsReadOnly(bool baseValue) { if (DataGridHelper.IsOneWay(EffectiveBinding)) { return true; } // only call the base if we dont want to force IsReadOnly true return base.OnCoerceIsReadOnly(baseValue); } /// <summary> /// The binding that will be applied to the SelectedItem property of the ComboBoxValue. /// </summary> /// <remarks> /// This isn't a DP because if it were getting the value would evaluate the binding. /// </remarks> public virtual BindingBase SelectedItemBinding { get { return _selectedItemBinding; } set { if (_selectedItemBinding != value) { BindingBase oldBinding = _selectedItemBinding; _selectedItemBinding = value; CoerceValue(IsReadOnlyProperty); CoerceValue(SortMemberPathProperty); OnSelectedItemBindingChanged(oldBinding, _selectedItemBinding); } } } /// <summary> /// The binding that will be applied to the Text property of the ComboBoxValue. /// </summary> /// <remarks> /// This isn't a DP because if it were getting the value would evaluate the binding. /// </remarks> public virtual BindingBase TextBinding { get { return _textBinding; } set { if (_textBinding != value) { BindingBase oldBinding = _textBinding; _textBinding = value; CoerceValue(IsReadOnlyProperty); CoerceValue(SortMemberPathProperty); OnTextBindingChanged(oldBinding, _textBinding); } } } /// <summary> /// Called when SelectedValueBinding changes. /// </summary> /// <param name="oldBinding">The old binding.</param> /// <param name="newBinding">The new binding.</param> protected virtual void OnSelectedValueBindingChanged(BindingBase oldBinding, BindingBase newBinding) { NotifyPropertyChanged("SelectedValueBinding"); } /// <summary> /// Called when SelectedItemBinding changes. /// </summary> /// <param name="oldBinding">The old binding.</param> /// <param name="newBinding">The new binding.</param> protected virtual void OnSelectedItemBindingChanged(BindingBase oldBinding, BindingBase newBinding) { NotifyPropertyChanged("SelectedItemBinding"); } /// <summary> /// Called when TextBinding changes. /// </summary> /// <param name="oldBinding">The old binding.</param> /// <param name="newBinding">The new binding.</param> protected virtual void OnTextBindingChanged(BindingBase oldBinding, BindingBase newBinding) { NotifyPropertyChanged("TextBinding"); } #endregion #region Styling /// <summary> /// The default value of the ElementStyle property. /// This value can be used as the BasedOn for new styles. /// </summary> public static Style DefaultElementStyle { get { if (_defaultElementStyle == null) { Style style = new Style(typeof(ComboBox)); // Set IsSynchronizedWithCurrentItem to false by default style.Setters.Add(new Setter(ComboBox.IsSynchronizedWithCurrentItemProperty, false)); style.Seal(); _defaultElementStyle = style; } return _defaultElementStyle; } } /// <summary> /// The default value of the EditingElementStyle property. /// This value can be used as the BasedOn for new styles. /// </summary> public static Style DefaultEditingElementStyle { get { // return the same as that of DefaultElementStyle return DefaultElementStyle; } } /// <summary> /// A style that is applied to the generated element when not editing. /// The TargetType of the style depends on the derived column class. /// </summary> public Style ElementStyle { get { return (Style)GetValue(ElementStyleProperty); } set { SetValue(ElementStyleProperty, value); } } /// <summary> /// The DependencyProperty for the ElementStyle property. /// </summary> public static readonly DependencyProperty ElementStyleProperty = DataGridBoundColumn.ElementStyleProperty.AddOwner(typeof(DataGridComboBoxColumn), new FrameworkPropertyMetadata(DefaultElementStyle)); /// <summary> /// A style that is applied to the generated element when editing. /// The TargetType of the style depends on the derived column class. /// </summary> public Style EditingElementStyle { get { return (Style)GetValue(EditingElementStyleProperty); } set { SetValue(EditingElementStyleProperty, value); } } /// <summary> /// The DependencyProperty for the EditingElementStyle property. /// </summary> public static readonly DependencyProperty EditingElementStyleProperty = DataGridBoundColumn.EditingElementStyleProperty.AddOwner(typeof(DataGridComboBoxColumn), new FrameworkPropertyMetadata(DefaultEditingElementStyle)); /// <summary> /// Assigns the ElementStyle to the desired property on the given element. /// </summary> private void ApplyStyle(bool isEditing, bool defaultToElementStyle, FrameworkElement element) { Style style = PickStyle(isEditing, defaultToElementStyle); if (style != null) { element.Style = style; } } /// <summary> /// Assigns the ElementStyle to the desired property on the given element. /// </summary> internal void ApplyStyle(bool isEditing, bool defaultToElementStyle, FrameworkContentElement element) { Style style = PickStyle(isEditing, defaultToElementStyle); if (style != null) { element.Style = style; } } private Style PickStyle(bool isEditing, bool defaultToElementStyle) { Style style = isEditing ? EditingElementStyle : ElementStyle; if (isEditing && defaultToElementStyle && (style == null)) { style = ElementStyle; } return style; } /// <summary> /// Assigns the Binding to the desired property on the target object. /// </summary> private static void ApplyBinding(BindingBase binding, DependencyObject target, DependencyProperty property) { if (binding != null) { BindingOperations.SetBinding(target, property, binding); } else { BindingOperations.ClearBinding(target, property); } } #endregion #region Clipboard Copy/Paste /// <summary> /// If base ClipboardContentBinding is not set we use Binding. /// </summary> public override BindingBase ClipboardContentBinding { get { return base.ClipboardContentBinding ?? EffectiveBinding; } set { base.ClipboardContentBinding = value; } } #endregion #region ComboBox Column Properties /// <summary> /// The ComboBox will attach to this ItemsSource. /// </summary> public IEnumerable ItemsSource { get { return (IEnumerable)GetValue(ItemsSourceProperty); } set { SetValue(ItemsSourceProperty, value); } } /// <summary> /// The DependencyProperty for ItemsSource. /// </summary> public static readonly DependencyProperty ItemsSourceProperty = ComboBox.ItemsSourceProperty.AddOwner(typeof(DataGridComboBoxColumn), new FrameworkPropertyMetadata(null, DataGridColumn.NotifyPropertyChangeForRefreshContent)); /// <summary> /// DisplayMemberPath is a simple way to define a default template /// that describes how to convert Items into UI elements by using /// the specified path. /// </summary> public string DisplayMemberPath { get { return (string)GetValue(DisplayMemberPathProperty); } set { SetValue(DisplayMemberPathProperty, value); } } /// <summary> /// The DependencyProperty for the DisplayMemberPath property. /// </summary> public static readonly DependencyProperty DisplayMemberPathProperty = ComboBox.DisplayMemberPathProperty.AddOwner(typeof(DataGridComboBoxColumn), new FrameworkPropertyMetadata(string.Empty, DataGridColumn.NotifyPropertyChangeForRefreshContent)); /// <summary> /// The path used to retrieve the SelectedValue from the SelectedItem /// </summary> public string SelectedValuePath { get { return (string)GetValue(SelectedValuePathProperty); } set { SetValue(SelectedValuePathProperty, value); } } /// <summary> /// SelectedValuePath DependencyProperty /// </summary> public static readonly DependencyProperty SelectedValuePathProperty = ComboBox.SelectedValuePathProperty.AddOwner(typeof(DataGridComboBoxColumn), new FrameworkPropertyMetadata(string.Empty, DataGridColumn.NotifyPropertyChangeForRefreshContent)); #endregion #region Property Changed Handler protected internal override void RefreshCellContent(FrameworkElement element, string propertyName) { DataGridCell cell = element as DataGridCell; if (cell != null) { bool isCellEditing = cell.IsEditing; if ((string.Compare(propertyName, "ElementStyle", StringComparison.Ordinal) == 0 && !isCellEditing) || (string.Compare(propertyName, "EditingElementStyle", StringComparison.Ordinal) == 0 && isCellEditing)) { cell.BuildVisualTree(); } else { ComboBox comboBox = cell.Content as ComboBox; switch (propertyName) { case "SelectedItemBinding": ApplyBinding(SelectedItemBinding, comboBox, ComboBox.SelectedItemProperty); break; case "SelectedValueBinding": ApplyBinding(SelectedValueBinding, comboBox, ComboBox.SelectedValueProperty); break; case "TextBinding": ApplyBinding(TextBinding, comboBox, ComboBox.TextProperty); break; case "SelectedValuePath": DataGridHelper.SyncColumnProperty(this, comboBox, ComboBox.SelectedValuePathProperty, SelectedValuePathProperty); break; case "DisplayMemberPath": DataGridHelper.SyncColumnProperty(this, comboBox, ComboBox.DisplayMemberPathProperty, DisplayMemberPathProperty); break; case "ItemsSource": DataGridHelper.SyncColumnProperty(this, comboBox, ComboBox.ItemsSourceProperty, ItemsSourceProperty); break; default: base.RefreshCellContent(element, propertyName); break; } } } else { base.RefreshCellContent(element, propertyName); } } #endregion #region BindingTarget Helpers /// <summary> /// Helper method which returns selection value from /// combobox based on which Binding's were set. /// </summary> /// <param name="comboBox"></param> /// <returns></returns> private object GetComboBoxSelectionValue(ComboBox comboBox) { if (SelectedItemBinding != null) { return comboBox.SelectedItem; } else if (SelectedValueBinding != null) { return comboBox.SelectedValue; } else { return comboBox.Text; } } #endregion #region Element Generation /// <summary> /// Creates the visual tree for text based cells. /// </summary> protected override FrameworkElement GenerateElement(DataGridCell cell, object dataItem) { TextBlockComboBox comboBox = new TextBlockComboBox(); ApplyStyle(/* isEditing = */ false, /* defaultToElementStyle = */ false, comboBox); ApplyColumnProperties(comboBox); DataGridHelper.RestoreFlowDirection(comboBox, cell); return comboBox; } /// <summary> /// Creates the visual tree for text based cells. /// </summary> protected override FrameworkElement GenerateEditingElement(DataGridCell cell, object dataItem) { ComboBox comboBox = new ComboBox(); ApplyStyle(/* isEditing = */ true, /* defaultToElementStyle = */ false, comboBox); ApplyColumnProperties(comboBox); DataGridHelper.RestoreFlowDirection(comboBox, cell); return comboBox; } private void ApplyColumnProperties(ComboBox comboBox) { ApplyBinding(SelectedItemBinding, comboBox, ComboBox.SelectedItemProperty); ApplyBinding(SelectedValueBinding, comboBox, ComboBox.SelectedValueProperty); ApplyBinding(TextBinding, comboBox, ComboBox.TextProperty); DataGridHelper.SyncColumnProperty(this, comboBox, ComboBox.SelectedValuePathProperty, SelectedValuePathProperty); DataGridHelper.SyncColumnProperty(this, comboBox, ComboBox.DisplayMemberPathProperty, DisplayMemberPathProperty); DataGridHelper.SyncColumnProperty(this, comboBox, ComboBox.ItemsSourceProperty, ItemsSourceProperty); } #endregion #region Editing /// <summary> /// Called when a cell has just switched to edit mode. /// </summary> /// <param name="editingElement">A reference to element returned by GenerateEditingElement.</param> /// <param name="editingEventArgs">The event args of the input event that caused the cell to go into edit mode. May be null.</param> /// <returns>The unedited value of the cell.</returns> protected override object PrepareCellForEdit(FrameworkElement editingElement, RoutedEventArgs editingEventArgs) { ComboBox comboBox = editingElement as ComboBox; if (comboBox != null) { comboBox.Focus(); object originalValue = GetComboBoxSelectionValue(comboBox); if (IsComboBoxOpeningInputEvent(editingEventArgs)) { comboBox.IsDropDownOpen = true; } return originalValue; } return null; } /// <summary> /// Called when a cell's value is to be restored to its original value, /// just before it exits edit mode. /// </summary> /// <param name="editingElement">A reference to element returned by GenerateEditingElement.</param> /// <param name="uneditedValue">The original, unedited value of the cell.</param> protected override void CancelCellEdit(FrameworkElement editingElement, object uneditedValue) { ComboBox cb = editingElement as ComboBox; if (cb != null && cb.EditableTextBoxSite != null) { DataGridHelper.CacheFlowDirection(cb.EditableTextBoxSite, cb.Parent as DataGridCell); DataGridHelper.CacheFlowDirection(cb, cb.Parent as DataGridCell); } base.CancelCellEdit(editingElement, uneditedValue); } /// <summary> /// Called when a cell's value is to be committed, just before it exits edit mode. /// </summary> /// <param name="editingElement">A reference to element returned by GenerateEditingElement.</param> /// <returns>false if there is a validation error. true otherwise.</returns> protected override bool CommitCellEdit(FrameworkElement editingElement) { ComboBox cb = editingElement as ComboBox; if (cb != null && cb.EditableTextBoxSite != null) { DataGridHelper.CacheFlowDirection(cb.EditableTextBoxSite, cb.Parent as DataGridCell); DataGridHelper.CacheFlowDirection(cb, cb.Parent as DataGridCell); } return base.CommitCellEdit(editingElement); } internal override void OnInput(InputEventArgs e) { if (IsComboBoxOpeningInputEvent(e)) { BeginEdit(e, true); } } private static bool IsComboBoxOpeningInputEvent(RoutedEventArgs e) { KeyEventArgs keyArgs = e as KeyEventArgs; if ((keyArgs != null) && keyArgs.RoutedEvent == Keyboard.KeyDownEvent && ((keyArgs.KeyStates & KeyStates.Down) == KeyStates.Down)) { bool isAltDown = (keyArgs.KeyboardDevice.Modifiers & ModifierKeys.Alt) == ModifierKeys.Alt; // We want to handle the ALT key. Get the real key if it is Key.System. Key key = keyArgs.Key; if (key == Key.System) { key = keyArgs.SystemKey; } // F4 alone or ALT+Up or ALT+Down will open the drop-down return ((key == Key.F4) && !isAltDown) || (((key == Key.Up) || (key == Key.Down)) && isAltDown); } return false; } #endregion #region Data private static Style _defaultElementStyle; private BindingBase _selectedValueBinding; private BindingBase _selectedItemBinding; private BindingBase _textBinding; #endregion } }
// "Therefore those skilled at the unorthodox // are infinite as heaven and earth, // inexhaustible as the great rivers. // When they come to an end, // they begin again, // like the days and months; // they die and are reborn, // like the four seasons." // // - Sun Tsu, // "The Art of War" #if !MONO using System; using System.Drawing; using System.Runtime.InteropServices; namespace Scientia.HtmlRenderer.WinForms.Utilities { /// <summary> /// Utility for Win32 API. /// </summary> internal static class Win32Utils { public const int WsBorder = 0x00800000; public const int WsExClientEdge = 0x200; /// <summary> /// Const for BitBlt copy raster-operation code. /// </summary> public const int BitBltCopy = 0x00CC0020; /// <summary> /// Const for BitBlt paint raster-operation code. /// </summary> public const int BitBltPaint = 0x00EE0086; public const int WmSetCursor = 0x20; public const int IdcHand = 32649; public const int TextAlignDefault = 0; public const int TextAlignRtl = 256; public const int TextAlignBaseline = 24; public const int TextAlignBaselineRtl = 256 + 24; [DllImport("user32.dll")] public static extern int SetCursor(int hCursor); [DllImport("user32.dll")] public static extern int LoadCursor(int hInstance, int lpCursorName); /// <summary> /// Create a compatible memory HDC from the given HDC.<br/> /// The memory HDC can be rendered into without effecting the original HDC.<br/> /// The returned memory HDC and <paramref name="dib"/> must be released using <see cref="ReleaseMemoryHdc"/>. /// </summary> /// <param name="hdc">the HDC to create memory HDC from</param> /// <param name="width">the width of the memory HDC to create</param> /// <param name="height">the height of the memory HDC to create</param> /// <param name="dib">returns used bitmap memory section that must be released when done with memory HDC</param> /// <returns>memory HDC</returns> public static IntPtr CreateMemoryHdc(IntPtr hdc, int width, int height, out IntPtr dib) { // Create a memory DC so we can work off-screen IntPtr memoryHdc = CreateCompatibleDC(hdc); SetBkMode(memoryHdc, 1); // Create a device-independent bitmap and select it into our DC var info = new BitMapInfo(); info.Size = Marshal.SizeOf(info); info.Width = width; info.Height = -height; info.Planes = 1; info.BitCount = 32; info.Compression = 0; // BI_RGB IntPtr ppvBits; dib = CreateDIBSection(hdc, ref info, 0, out ppvBits, IntPtr.Zero, 0); SelectObject(memoryHdc, dib); return memoryHdc; } /// <summary> /// Release the given memory HDC and dib section created from <see cref="CreateMemoryHdc"/>. /// </summary> /// <param name="memoryHdc">Memory HDC to release</param> /// <param name="dib">bitmap section to release</param> public static void ReleaseMemoryHdc(IntPtr memoryHdc, IntPtr dib) { DeleteObject(dib); DeleteDC(memoryHdc); } [DllImport("user32.dll")] public static extern bool IsWindowVisible(IntPtr hWnd); [DllImport("user32.dll")] public static extern IntPtr WindowFromDC(IntPtr hdc); /// <summary> /// Retrieves the dimensions of the bounding rectangle of the specified window. The dimensions are given in screen coordinates that are relative to the upper-left corner of the screen. /// </summary> /// <remarks> /// In conformance with conventions for the RECT structure, the bottom-right coordinates of the returned rectangle are exclusive. In other words, /// the pixel at (right, bottom) lies immediately outside the rectangle. /// </remarks> /// <param name="hWnd">A handle to the window.</param> /// <param name="lpRect">A pointer to a RECT structure that receives the screen coordinates of the upper-left and lower-right corners of the window.</param> /// <returns>If the function succeeds, the return value is nonzero.</returns> [DllImport("User32", SetLastError = true)] public static extern int GetWindowRect(IntPtr hWnd, out Rectangle lpRect); /// <summary> /// Retrieves the dimensions of the bounding rectangle of the specified window. The dimensions are given in screen coordinates that are relative to the upper-left corner of the screen. /// </summary> /// <remarks> /// In conformance with conventions for the RECT structure, the bottom-right coordinates of the returned rectangle are exclusive. In other words, /// the pixel at (right, bottom) lies immediately outside the rectangle. /// </remarks> /// <param name="handle">A handle to the window.</param> /// <returns>RECT structure that receives the screen coordinates of the upper-left and lower-right corners of the window.</returns> public static Rectangle GetWindowRectangle(IntPtr handle) { Rectangle rect; GetWindowRect(handle, out rect); return new Rectangle(rect.Left, rect.Top, rect.Right - rect.Left, rect.Bottom - rect.Top); } [DllImport("User32.dll")] public static extern bool MoveWindow(IntPtr handle, int x, int y, int width, int height, bool redraw); [DllImport("gdi32.dll")] public static extern int SetTextAlign(IntPtr hdc, uint fMode); [DllImport("gdi32.dll")] public static extern int SetBkMode(IntPtr hdc, int mode); [DllImport("gdi32.dll")] public static extern IntPtr SelectObject(IntPtr hdc, IntPtr hgdiObj); [DllImport("gdi32.dll")] public static extern uint SetTextColor(IntPtr hdc, int color); [DllImport("gdi32.dll", CharSet = CharSet.Unicode)] public static extern bool GetTextMetrics(IntPtr hdc, out TextMetric lptm); [DllImport("gdi32.dll", EntryPoint = "GetTextExtentPoint32W", CharSet = CharSet.Unicode)] public static extern int GetTextExtentPoint32(IntPtr hdc, [MarshalAs(UnmanagedType.LPWStr)] string str, int len, ref Size size); [DllImport("gdi32.dll", EntryPoint = "GetTextExtentExPointW", CharSet = CharSet.Unicode)] public static extern bool GetTextExtentExPoint(IntPtr hDc, [MarshalAs(UnmanagedType.LPWStr)] string str, int nLength, int nMaxExtent, int[] lpnFit, int[] alpDx, ref Size size); [DllImport("gdi32.dll", EntryPoint = "TextOutW", CharSet = CharSet.Unicode)] public static extern bool TextOut(IntPtr hdc, int x, int y, [MarshalAs(UnmanagedType.LPWStr)] string str, int len); [DllImport("gdi32.dll")] public static extern IntPtr CreateRectRgn(int nLeftRect, int nTopRect, int nRightRect, int nBottomRect); [DllImport("gdi32.dll")] public static extern int GetClipBox(IntPtr hdc, out Rectangle lprc); [DllImport("gdi32.dll")] public static extern int SelectClipRgn(IntPtr hdc, IntPtr hrgn); [DllImport("gdi32.dll")] public static extern bool DeleteObject(IntPtr hObject); [DllImport("gdi32.dll")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool BitBlt(IntPtr hdc, int nXDest, int nYDest, int nWidth, int nHeight, IntPtr hdcSrc, int nXSrc, int nYSrc, uint dwRop); [DllImport("gdi32.dll", EntryPoint = "GdiAlphaBlend")] public static extern bool AlphaBlend(IntPtr hdcDest, int nXOriginDest, int nYOriginDest, int nWidthDest, int nHeightDest, IntPtr hdcSrc, int nXOriginSrc, int nYOriginSrc, int nWidthSrc, int nHeightSrc, BlendFunction blendFunction); [DllImport("gdi32.dll", ExactSpelling = true, SetLastError = true)] public static extern bool DeleteDC(IntPtr hdc); [DllImport("gdi32.dll", ExactSpelling = true, SetLastError = true)] public static extern IntPtr CreateCompatibleDC(IntPtr hdc); [DllImport("gdi32.dll")] public static extern IntPtr CreateDIBSection(IntPtr hdc, [In] ref BitMapInfo pbmi, uint iUsage, out IntPtr ppvBits, IntPtr hSection, uint dwOffset); } [StructLayout(LayoutKind.Sequential)] internal struct BlendFunction { public byte BlendOp; public byte BlendFlags; public byte SourceConstantAlpha; public byte AlphaFormat; public BlendFunction(byte alpha) { this.BlendOp = 0; this.BlendFlags = 0; this.AlphaFormat = 0; this.SourceConstantAlpha = alpha; } } [StructLayout(LayoutKind.Sequential)] internal struct BitMapInfo { public int Size; public int Width; public int Height; public short Planes; public short BitCount; public int Compression; public int SizeImage; public int XPelsPerMeter; public int YPelsPerMeter; public int ClrUsed; public int ClrImportant; public byte ColorsRgbBlue; public byte ColorsRgbGreen; public byte ColorsRgbRed; public byte ColorsRgbReserved; } [StructLayout(LayoutKind.Sequential, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] internal struct TextMetric { public int Height; public int Ascent; public int Descent; public int InternalLeading; public int ExternalLeading; public int AveCharWidth; public int MaxCharWidth; public int Weight; public int Overhang; public int DigitizedAspectX; public int DigitizedAspectY; public char FirstChar; public char LastChar; public char DefaultChar; public char BreakChar; public byte Italic; public byte Underlined; public byte StruckOut; public byte PitchAndFamily; public byte CharSet; } } #endif
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void RoundToNegativeInfinityDouble() { var test = new SimpleUnaryOpTest__RoundToNegativeInfinityDouble(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local works test.RunLclFldScenario(); // Validates passing an instance member works test.RunFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleUnaryOpTest__RoundToNegativeInfinityDouble { private const int VectorSize = 32; private const int Op1ElementCount = VectorSize / sizeof(Double); private const int RetElementCount = VectorSize / sizeof(Double); private static Double[] _data = new Double[Op1ElementCount]; private static Vector256<Double> _clsVar; private Vector256<Double> _fld; private SimpleUnaryOpTest__DataTable<Double, Double> _dataTable; static SimpleUnaryOpTest__RoundToNegativeInfinityDouble() { var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (double)(random.NextDouble()); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _clsVar), ref Unsafe.As<Double, byte>(ref _data[0]), VectorSize); } public SimpleUnaryOpTest__RoundToNegativeInfinityDouble() { Succeeded = true; var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (double)(random.NextDouble()); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _fld), ref Unsafe.As<Double, byte>(ref _data[0]), VectorSize); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (double)(random.NextDouble()); } _dataTable = new SimpleUnaryOpTest__DataTable<Double, Double>(_data, new Double[RetElementCount], VectorSize); } public bool IsSupported => Avx.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { var result = Avx.RoundToNegativeInfinity( Unsafe.Read<Vector256<Double>>(_dataTable.inArrayPtr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { var result = Avx.RoundToNegativeInfinity( Avx.LoadVector256((Double*)(_dataTable.inArrayPtr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { var result = Avx.RoundToNegativeInfinity( Avx.LoadAlignedVector256((Double*)(_dataTable.inArrayPtr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { var result = typeof(Avx).GetMethod(nameof(Avx.RoundToNegativeInfinity), new Type[] { typeof(Vector256<Double>) }) .Invoke(null, new object[] { Unsafe.Read<Vector256<Double>>(_dataTable.inArrayPtr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Double>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { var result = typeof(Avx).GetMethod(nameof(Avx.RoundToNegativeInfinity), new Type[] { typeof(Vector256<Double>) }) .Invoke(null, new object[] { Avx.LoadVector256((Double*)(_dataTable.inArrayPtr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Double>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { var result = typeof(Avx).GetMethod(nameof(Avx.RoundToNegativeInfinity), new Type[] { typeof(Vector256<Double>) }) .Invoke(null, new object[] { Avx.LoadAlignedVector256((Double*)(_dataTable.inArrayPtr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Double>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { var result = Avx.RoundToNegativeInfinity( _clsVar ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { var firstOp = Unsafe.Read<Vector256<Double>>(_dataTable.inArrayPtr); var result = Avx.RoundToNegativeInfinity(firstOp); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { var firstOp = Avx.LoadVector256((Double*)(_dataTable.inArrayPtr)); var result = Avx.RoundToNegativeInfinity(firstOp); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { var firstOp = Avx.LoadAlignedVector256((Double*)(_dataTable.inArrayPtr)); var result = Avx.RoundToNegativeInfinity(firstOp); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclFldScenario() { var test = new SimpleUnaryOpTest__RoundToNegativeInfinityDouble(); var result = Avx.RoundToNegativeInfinity(test._fld); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunFldScenario() { var result = Avx.RoundToNegativeInfinity(_fld); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld, _dataTable.outArrayPtr); } public void RunUnsupportedScenario() { Succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector256<Double> firstOp, void* result, [CallerMemberName] string method = "") { Double[] inArray = new Double[Op1ElementCount]; Double[] outArray = new Double[RetElementCount]; Unsafe.Write(Unsafe.AsPointer(ref inArray[0]), firstOp); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray, outArray, method); } private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "") { Double[] inArray = new Double[Op1ElementCount]; Double[] outArray = new Double[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray, outArray, method); } private void ValidateResult(Double[] firstOp, Double[] result, [CallerMemberName] string method = "") { if (BitConverter.DoubleToInt64Bits(result[0]) != BitConverter.DoubleToInt64Bits(Math.Floor(firstOp[0]))) { Succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (BitConverter.DoubleToInt64Bits(result[i]) != BitConverter.DoubleToInt64Bits(Math.Floor(firstOp[i]))) { Succeeded = false; break; } } } if (!Succeeded) { Console.WriteLine($"{nameof(Avx)}.{nameof(Avx.RoundToNegativeInfinity)}<Double>(Vector256<Double>): {method} failed:"); Console.WriteLine($" firstOp: ({string.Join(", ", firstOp)})"); Console.WriteLine($" result: ({string.Join(", ", result)})"); Console.WriteLine(); } } } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gax = Google.Api.Gax; using gcrv = Google.Cloud.Retail.V2; using sys = System; namespace Google.Cloud.Retail.V2 { /// <summary>Resource name for the <c>Product</c> resource.</summary> public sealed partial class ProductName : gax::IResourceName, sys::IEquatable<ProductName> { /// <summary>The possible contents of <see cref="ProductName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern /// <c>projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}</c>. /// </summary> ProjectLocationCatalogBranchProduct = 1, } private static gax::PathTemplate s_projectLocationCatalogBranchProduct = new gax::PathTemplate("projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}"); /// <summary>Creates a <see cref="ProductName"/> containing an unparsed resource name.</summary> /// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param> /// <returns> /// A new instance of <see cref="ProductName"/> containing the provided <paramref name="unparsedResourceName"/>. /// </returns> public static ProductName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new ProductName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="ProductName"/> with the pattern /// <c>projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="catalogId">The <c>Catalog</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="branchId">The <c>Branch</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="productId">The <c>Product</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="ProductName"/> constructed from the provided ids.</returns> public static ProductName FromProjectLocationCatalogBranchProduct(string projectId, string locationId, string catalogId, string branchId, string productId) => new ProductName(ResourceNameType.ProjectLocationCatalogBranchProduct, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), catalogId: gax::GaxPreconditions.CheckNotNullOrEmpty(catalogId, nameof(catalogId)), branchId: gax::GaxPreconditions.CheckNotNullOrEmpty(branchId, nameof(branchId)), productId: gax::GaxPreconditions.CheckNotNullOrEmpty(productId, nameof(productId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="ProductName"/> with pattern /// <c>projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="catalogId">The <c>Catalog</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="branchId">The <c>Branch</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="productId">The <c>Product</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="ProductName"/> with pattern /// <c>projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}</c>. /// </returns> public static string Format(string projectId, string locationId, string catalogId, string branchId, string productId) => FormatProjectLocationCatalogBranchProduct(projectId, locationId, catalogId, branchId, productId); /// <summary> /// Formats the IDs into the string representation of this <see cref="ProductName"/> with pattern /// <c>projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="catalogId">The <c>Catalog</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="branchId">The <c>Branch</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="productId">The <c>Product</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="ProductName"/> with pattern /// <c>projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}</c>. /// </returns> public static string FormatProjectLocationCatalogBranchProduct(string projectId, string locationId, string catalogId, string branchId, string productId) => s_projectLocationCatalogBranchProduct.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(catalogId, nameof(catalogId)), gax::GaxPreconditions.CheckNotNullOrEmpty(branchId, nameof(branchId)), gax::GaxPreconditions.CheckNotNullOrEmpty(productId, nameof(productId))); /// <summary>Parses the given resource name string into a new <see cref="ProductName"/> instance.</summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}</c> /// </description> /// </item> /// </list> /// </remarks> /// <param name="productName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="ProductName"/> if successful.</returns> public static ProductName Parse(string productName) => Parse(productName, false); /// <summary> /// Parses the given resource name string into a new <see cref="ProductName"/> instance; optionally allowing an /// unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}</c> /// </description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="productName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <returns>The parsed <see cref="ProductName"/> if successful.</returns> public static ProductName Parse(string productName, bool allowUnparsed) => TryParse(productName, allowUnparsed, out ProductName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern."); /// <summary> /// Tries to parse the given resource name string into a new <see cref="ProductName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}</c> /// </description> /// </item> /// </list> /// </remarks> /// <param name="productName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="ProductName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string productName, out ProductName result) => TryParse(productName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="ProductName"/> instance; optionally /// allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}</c> /// </description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="productName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <param name="result"> /// When this method returns, the parsed <see cref="ProductName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string productName, bool allowUnparsed, out ProductName result) { gax::GaxPreconditions.CheckNotNull(productName, nameof(productName)); gax::TemplatedResourceName resourceName; if (s_projectLocationCatalogBranchProduct.TryParseName(productName, out resourceName)) { result = FromProjectLocationCatalogBranchProduct(resourceName[0], resourceName[1], resourceName[2], resourceName[3], resourceName[4]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(productName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private ProductName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string branchId = null, string catalogId = null, string locationId = null, string productId = null, string projectId = null) { Type = type; UnparsedResource = unparsedResourceName; BranchId = branchId; CatalogId = catalogId; LocationId = locationId; ProductId = productId; ProjectId = projectId; } /// <summary> /// Constructs a new instance of a <see cref="ProductName"/> class from the component parts of pattern /// <c>projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}</c> /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="catalogId">The <c>Catalog</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="branchId">The <c>Branch</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="productId">The <c>Product</c> ID. Must not be <c>null</c> or empty.</param> public ProductName(string projectId, string locationId, string catalogId, string branchId, string productId) : this(ResourceNameType.ProjectLocationCatalogBranchProduct, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), catalogId: gax::GaxPreconditions.CheckNotNullOrEmpty(catalogId, nameof(catalogId)), branchId: gax::GaxPreconditions.CheckNotNullOrEmpty(branchId, nameof(branchId)), productId: gax::GaxPreconditions.CheckNotNullOrEmpty(productId, nameof(productId))) { } /// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary> public ResourceNameType Type { get; } /// <summary> /// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an /// unparsed resource name. /// </summary> public gax::UnparsedResourceName UnparsedResource { get; } /// <summary> /// The <c>Branch</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string BranchId { get; } /// <summary> /// The <c>Catalog</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string CatalogId { get; } /// <summary> /// The <c>Location</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string LocationId { get; } /// <summary> /// The <c>Product</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string ProductId { get; } /// <summary> /// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string ProjectId { get; } /// <summary>Whether this instance contains a resource name with a known pattern.</summary> public bool IsKnownPattern => Type != ResourceNameType.Unparsed; /// <summary>The string representation of the resource name.</summary> /// <returns>The string representation of the resource name.</returns> public override string ToString() { switch (Type) { case ResourceNameType.Unparsed: return UnparsedResource.ToString(); case ResourceNameType.ProjectLocationCatalogBranchProduct: return s_projectLocationCatalogBranchProduct.Expand(ProjectId, LocationId, CatalogId, BranchId, ProductId); default: throw new sys::InvalidOperationException("Unrecognized resource-type."); } } /// <summary>Returns a hash code for this resource name.</summary> public override int GetHashCode() => ToString().GetHashCode(); /// <inheritdoc/> public override bool Equals(object obj) => Equals(obj as ProductName); /// <inheritdoc/> public bool Equals(ProductName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(ProductName a, ProductName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(ProductName a, ProductName b) => !(a == b); } /// <summary>Resource name for the <c>Branch</c> resource.</summary> public sealed partial class BranchName : gax::IResourceName, sys::IEquatable<BranchName> { /// <summary>The possible contents of <see cref="BranchName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern /// <c>projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}</c>. /// </summary> ProjectLocationCatalogBranch = 1, } private static gax::PathTemplate s_projectLocationCatalogBranch = new gax::PathTemplate("projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}"); /// <summary>Creates a <see cref="BranchName"/> containing an unparsed resource name.</summary> /// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param> /// <returns> /// A new instance of <see cref="BranchName"/> containing the provided <paramref name="unparsedResourceName"/>. /// </returns> public static BranchName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new BranchName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="BranchName"/> with the pattern /// <c>projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="catalogId">The <c>Catalog</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="branchId">The <c>Branch</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="BranchName"/> constructed from the provided ids.</returns> public static BranchName FromProjectLocationCatalogBranch(string projectId, string locationId, string catalogId, string branchId) => new BranchName(ResourceNameType.ProjectLocationCatalogBranch, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), catalogId: gax::GaxPreconditions.CheckNotNullOrEmpty(catalogId, nameof(catalogId)), branchId: gax::GaxPreconditions.CheckNotNullOrEmpty(branchId, nameof(branchId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="BranchName"/> with pattern /// <c>projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="catalogId">The <c>Catalog</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="branchId">The <c>Branch</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="BranchName"/> with pattern /// <c>projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}</c>. /// </returns> public static string Format(string projectId, string locationId, string catalogId, string branchId) => FormatProjectLocationCatalogBranch(projectId, locationId, catalogId, branchId); /// <summary> /// Formats the IDs into the string representation of this <see cref="BranchName"/> with pattern /// <c>projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="catalogId">The <c>Catalog</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="branchId">The <c>Branch</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="BranchName"/> with pattern /// <c>projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}</c>. /// </returns> public static string FormatProjectLocationCatalogBranch(string projectId, string locationId, string catalogId, string branchId) => s_projectLocationCatalogBranch.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(catalogId, nameof(catalogId)), gax::GaxPreconditions.CheckNotNullOrEmpty(branchId, nameof(branchId))); /// <summary>Parses the given resource name string into a new <see cref="BranchName"/> instance.</summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}</c> /// </description> /// </item> /// </list> /// </remarks> /// <param name="branchName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="BranchName"/> if successful.</returns> public static BranchName Parse(string branchName) => Parse(branchName, false); /// <summary> /// Parses the given resource name string into a new <see cref="BranchName"/> instance; optionally allowing an /// unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}</c> /// </description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="branchName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <returns>The parsed <see cref="BranchName"/> if successful.</returns> public static BranchName Parse(string branchName, bool allowUnparsed) => TryParse(branchName, allowUnparsed, out BranchName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern."); /// <summary> /// Tries to parse the given resource name string into a new <see cref="BranchName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}</c> /// </description> /// </item> /// </list> /// </remarks> /// <param name="branchName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="BranchName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string branchName, out BranchName result) => TryParse(branchName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="BranchName"/> instance; optionally /// allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}</c> /// </description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="branchName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <param name="result"> /// When this method returns, the parsed <see cref="BranchName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string branchName, bool allowUnparsed, out BranchName result) { gax::GaxPreconditions.CheckNotNull(branchName, nameof(branchName)); gax::TemplatedResourceName resourceName; if (s_projectLocationCatalogBranch.TryParseName(branchName, out resourceName)) { result = FromProjectLocationCatalogBranch(resourceName[0], resourceName[1], resourceName[2], resourceName[3]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(branchName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private BranchName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string branchId = null, string catalogId = null, string locationId = null, string projectId = null) { Type = type; UnparsedResource = unparsedResourceName; BranchId = branchId; CatalogId = catalogId; LocationId = locationId; ProjectId = projectId; } /// <summary> /// Constructs a new instance of a <see cref="BranchName"/> class from the component parts of pattern /// <c>projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}</c> /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="catalogId">The <c>Catalog</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="branchId">The <c>Branch</c> ID. Must not be <c>null</c> or empty.</param> public BranchName(string projectId, string locationId, string catalogId, string branchId) : this(ResourceNameType.ProjectLocationCatalogBranch, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), catalogId: gax::GaxPreconditions.CheckNotNullOrEmpty(catalogId, nameof(catalogId)), branchId: gax::GaxPreconditions.CheckNotNullOrEmpty(branchId, nameof(branchId))) { } /// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary> public ResourceNameType Type { get; } /// <summary> /// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an /// unparsed resource name. /// </summary> public gax::UnparsedResourceName UnparsedResource { get; } /// <summary> /// The <c>Branch</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string BranchId { get; } /// <summary> /// The <c>Catalog</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string CatalogId { get; } /// <summary> /// The <c>Location</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string LocationId { get; } /// <summary> /// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string ProjectId { get; } /// <summary>Whether this instance contains a resource name with a known pattern.</summary> public bool IsKnownPattern => Type != ResourceNameType.Unparsed; /// <summary>The string representation of the resource name.</summary> /// <returns>The string representation of the resource name.</returns> public override string ToString() { switch (Type) { case ResourceNameType.Unparsed: return UnparsedResource.ToString(); case ResourceNameType.ProjectLocationCatalogBranch: return s_projectLocationCatalogBranch.Expand(ProjectId, LocationId, CatalogId, BranchId); default: throw new sys::InvalidOperationException("Unrecognized resource-type."); } } /// <summary>Returns a hash code for this resource name.</summary> public override int GetHashCode() => ToString().GetHashCode(); /// <inheritdoc/> public override bool Equals(object obj) => Equals(obj as BranchName); /// <inheritdoc/> public bool Equals(BranchName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(BranchName a, BranchName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(BranchName a, BranchName b) => !(a == b); } public partial class Product { /// <summary> /// <see cref="gcrv::ProductName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcrv::ProductName ProductName { get => string.IsNullOrEmpty(Name) ? null : gcrv::ProductName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } }
using System; using System.Collections.Generic; using System.Linq; using Nop.Core.Caching; using Nop.Core.Data; using Nop.Core.Domain.Customers; using Nop.Services.Events; namespace Nop.Services.Customers { /// <summary> /// Customer attribute service /// </summary> public partial class CustomerAttributeService : ICustomerAttributeService { #region Constants /// <summary> /// Key for caching /// </summary> private const string CUSTOMERATTRIBUTES_ALL_KEY = "Nop.customerattribute.all"; /// <summary> /// Key for caching /// </summary> /// <remarks> /// {0} : customer attribute ID /// </remarks> private const string CUSTOMERATTRIBUTES_BY_ID_KEY = "Nop.customerattribute.id-{0}"; /// <summary> /// Key for caching /// </summary> /// <remarks> /// {0} : customer attribute ID /// </remarks> private const string CUSTOMERATTRIBUTEVALUES_ALL_KEY = "Nop.customerattributevalue.all-{0}"; /// <summary> /// Key for caching /// </summary> /// <remarks> /// {0} : customer attribute value ID /// </remarks> private const string CUSTOMERATTRIBUTEVALUES_BY_ID_KEY = "Nop.customerattributevalue.id-{0}"; /// <summary> /// Key pattern to clear cache /// </summary> private const string CUSTOMERATTRIBUTES_PATTERN_KEY = "Nop.customerattribute."; /// <summary> /// Key pattern to clear cache /// </summary> private const string CUSTOMERATTRIBUTEVALUES_PATTERN_KEY = "Nop.customerattributevalue."; #endregion #region Fields private readonly IRepository<CustomerAttribute> _customerAttributeRepository; private readonly IRepository<CustomerAttributeValue> _customerAttributeValueRepository; private readonly IEventPublisher _eventPublisher; private readonly ICacheManager _cacheManager; #endregion #region Ctor /// <summary> /// Ctor /// </summary> /// <param name="cacheManager">Cache manager</param> /// <param name="customerAttributeRepository">Customer attribute repository</param> /// <param name="customerAttributeValueRepository">Customer attribute value repository</param> /// <param name="eventPublisher">Event published</param> public CustomerAttributeService(ICacheManager cacheManager, IRepository<CustomerAttribute> customerAttributeRepository, IRepository<CustomerAttributeValue> customerAttributeValueRepository, IEventPublisher eventPublisher) { this._cacheManager = cacheManager; this._customerAttributeRepository = customerAttributeRepository; this._customerAttributeValueRepository = customerAttributeValueRepository; this._eventPublisher = eventPublisher; } #endregion #region Methods /// <summary> /// Deletes a customer attribute /// </summary> /// <param name="customerAttribute">Customer attribute</param> public virtual void DeleteCustomerAttribute(CustomerAttribute customerAttribute) { if (customerAttribute == null) throw new ArgumentNullException("customerAttribute"); _customerAttributeRepository.Delete(customerAttribute); _cacheManager.RemoveByPattern(CUSTOMERATTRIBUTES_PATTERN_KEY); _cacheManager.RemoveByPattern(CUSTOMERATTRIBUTEVALUES_PATTERN_KEY); //event notification _eventPublisher.EntityDeleted(customerAttribute); } /// <summary> /// Gets all customer attributes /// </summary> /// <returns>Customer attributes</returns> public virtual IList<CustomerAttribute> GetAllCustomerAttributes() { string key = CUSTOMERATTRIBUTES_ALL_KEY; return _cacheManager.Get(key, () => { var query = from ca in _customerAttributeRepository.Table orderby ca.DisplayOrder select ca; return query.ToList(); }); } /// <summary> /// Gets a customer attribute /// </summary> /// <param name="customerAttributeId">Customer attribute identifier</param> /// <returns>Customer attribute</returns> public virtual CustomerAttribute GetCustomerAttributeById(int customerAttributeId) { if (customerAttributeId == 0) return null; string key = string.Format(CUSTOMERATTRIBUTES_BY_ID_KEY, customerAttributeId); return _cacheManager.Get(key, () => { return _customerAttributeRepository.GetById(customerAttributeId); }); } /// <summary> /// Inserts a customer attribute /// </summary> /// <param name="customerAttribute">Customer attribute</param> public virtual void InsertCustomerAttribute(CustomerAttribute customerAttribute) { if (customerAttribute == null) throw new ArgumentNullException("customerAttribute"); _customerAttributeRepository.Insert(customerAttribute); _cacheManager.RemoveByPattern(CUSTOMERATTRIBUTES_PATTERN_KEY); _cacheManager.RemoveByPattern(CUSTOMERATTRIBUTEVALUES_PATTERN_KEY); //event notification _eventPublisher.EntityInserted(customerAttribute); } /// <summary> /// Updates the customer attribute /// </summary> /// <param name="customerAttribute">Customer attribute</param> public virtual void UpdateCustomerAttribute(CustomerAttribute customerAttribute) { if (customerAttribute == null) throw new ArgumentNullException("customerAttribute"); _customerAttributeRepository.Update(customerAttribute); _cacheManager.RemoveByPattern(CUSTOMERATTRIBUTES_PATTERN_KEY); _cacheManager.RemoveByPattern(CUSTOMERATTRIBUTEVALUES_PATTERN_KEY); //event notification _eventPublisher.EntityUpdated(customerAttribute); } /// <summary> /// Deletes a customer attribute value /// </summary> /// <param name="customerAttributeValue">Customer attribute value</param> public virtual void DeleteCustomerAttributeValue(CustomerAttributeValue customerAttributeValue) { if (customerAttributeValue == null) throw new ArgumentNullException("customerAttributeValue"); _customerAttributeValueRepository.Delete(customerAttributeValue); _cacheManager.RemoveByPattern(CUSTOMERATTRIBUTES_PATTERN_KEY); _cacheManager.RemoveByPattern(CUSTOMERATTRIBUTEVALUES_PATTERN_KEY); //event notification _eventPublisher.EntityDeleted(customerAttributeValue); } /// <summary> /// Gets customer attribute values by customer attribute identifier /// </summary> /// <param name="customerAttributeId">The customer attribute identifier</param> /// <returns>Customer attribute values</returns> public virtual IList<CustomerAttributeValue> GetCustomerAttributeValues(int customerAttributeId) { string key = string.Format(CUSTOMERATTRIBUTEVALUES_ALL_KEY, customerAttributeId); return _cacheManager.Get(key, () => { var query = from cav in _customerAttributeValueRepository.Table orderby cav.DisplayOrder where cav.CustomerAttributeId == customerAttributeId select cav; var customerAttributeValues = query.ToList(); return customerAttributeValues; }); } /// <summary> /// Gets a customer attribute value /// </summary> /// <param name="customerAttributeValueId">Customer attribute value identifier</param> /// <returns>Customer attribute value</returns> public virtual CustomerAttributeValue GetCustomerAttributeValueById(int customerAttributeValueId) { if (customerAttributeValueId == 0) return null; string key = string.Format(CUSTOMERATTRIBUTEVALUES_BY_ID_KEY, customerAttributeValueId); return _cacheManager.Get(key, () => { return _customerAttributeValueRepository.GetById(customerAttributeValueId); }); } /// <summary> /// Inserts a customer attribute value /// </summary> /// <param name="customerAttributeValue">Customer attribute value</param> public virtual void InsertCustomerAttributeValue(CustomerAttributeValue customerAttributeValue) { if (customerAttributeValue == null) throw new ArgumentNullException("customerAttributeValue"); _customerAttributeValueRepository.Insert(customerAttributeValue); _cacheManager.RemoveByPattern(CUSTOMERATTRIBUTES_PATTERN_KEY); _cacheManager.RemoveByPattern(CUSTOMERATTRIBUTEVALUES_PATTERN_KEY); //event notification _eventPublisher.EntityInserted(customerAttributeValue); } /// <summary> /// Updates the customer attribute value /// </summary> /// <param name="customerAttributeValue">Customer attribute value</param> public virtual void UpdateCustomerAttributeValue(CustomerAttributeValue customerAttributeValue) { if (customerAttributeValue == null) throw new ArgumentNullException("customerAttributeValue"); _customerAttributeValueRepository.Update(customerAttributeValue); _cacheManager.RemoveByPattern(CUSTOMERATTRIBUTES_PATTERN_KEY); _cacheManager.RemoveByPattern(CUSTOMERATTRIBUTEVALUES_PATTERN_KEY); //event notification _eventPublisher.EntityUpdated(customerAttributeValue); } #endregion } }
// Visual Studio Shared Project // Copyright(c) Microsoft Corporation // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the License); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABLITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using System; using System.Collections.Generic; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; using Microsoft.VisualStudio.OLE.Interop; using Microsoft.VisualStudio.Shell.Interop; using VSConstants = Microsoft.VisualStudio.VSConstants; namespace Microsoft.VisualStudioTools.Navigation { /// <summary> /// Implements a simple library that tracks project symbols, objects etc. /// </summary> sealed class Library : IVsSimpleLibrary2, IDisposable { private Guid _guid; private _LIB_FLAGS2 _capabilities; private readonly SemaphoreSlim _searching; private LibraryNode _root; private uint _updateCount; private enum UpdateType { Add, Remove } private readonly List<KeyValuePair<UpdateType, LibraryNode>> _updates; public Library(Guid libraryGuid) { _guid = libraryGuid; _root = new LibraryNode(null, String.Empty, String.Empty, LibraryNodeType.Package); _updates = new List<KeyValuePair<UpdateType, LibraryNode>>(); _searching = new SemaphoreSlim(1); } public void Dispose() { _searching.Dispose(); } public _LIB_FLAGS2 LibraryCapabilities { get { return _capabilities; } set { _capabilities = value; } } private void ApplyUpdates(bool assumeLockHeld) { if (!assumeLockHeld) { if (!_searching.Wait(0)) { // Didn't get the lock immediately, which means we are // currently searching. Once the search is done, updates // will be applied. return; } } try { lock (_updates) { if (_updates.Count == 0) { return; } // re-create root node here because we may have handed out // the node before and don't want to mutate it's list. _root = _root.Clone(); _updateCount += 1; foreach (var kv in _updates) { switch (kv.Key) { case UpdateType.Add: _root.AddNode(kv.Value); break; case UpdateType.Remove: _root.RemoveNode(kv.Value); break; default: Debug.Fail("Unsupported update type " + kv.Key.ToString()); break; } } _updates.Clear(); } } finally { if (!assumeLockHeld) { _searching.Release(); } } } internal async void AddNode(LibraryNode node) { lock (_updates) { _updates.Add(new KeyValuePair<UpdateType, LibraryNode>(UpdateType.Add, node)); } ApplyUpdates(false); } internal void RemoveNode(LibraryNode node) { lock (_updates) { _updates.Add(new KeyValuePair<UpdateType, LibraryNode>(UpdateType.Remove, node)); } ApplyUpdates(false); } #region IVsSimpleLibrary2 Members public int AddBrowseContainer(VSCOMPONENTSELECTORDATA[] pcdComponent, ref uint pgrfOptions, out string pbstrComponentAdded) { pbstrComponentAdded = null; return VSConstants.E_NOTIMPL; } public int CreateNavInfo(SYMBOL_DESCRIPTION_NODE[] rgSymbolNodes, uint ulcNodes, out IVsNavInfo ppNavInfo) { ppNavInfo = null; return VSConstants.E_NOTIMPL; } public int GetBrowseContainersForHierarchy(IVsHierarchy pHierarchy, uint celt, VSBROWSECONTAINER[] rgBrowseContainers, uint[] pcActual) { return VSConstants.E_NOTIMPL; } public int GetGuid(out Guid pguidLib) { pguidLib = _guid; return VSConstants.S_OK; } public int GetLibFlags2(out uint pgrfFlags) { pgrfFlags = (uint)LibraryCapabilities; return VSConstants.S_OK; } public int GetList2(uint ListType, uint flags, VSOBSEARCHCRITERIA2[] pobSrch, out IVsSimpleObjectList2 ppIVsSimpleObjectList2) { if ((flags & (uint)_LIB_LISTFLAGS.LLF_RESOURCEVIEW) != 0) { ppIVsSimpleObjectList2 = null; return VSConstants.E_NOTIMPL; } ICustomSearchListProvider listProvider; if (pobSrch != null && pobSrch.Length > 0) { if ((listProvider = pobSrch[0].pIVsNavInfo as ICustomSearchListProvider) != null) { switch ((_LIB_LISTTYPE)ListType) { case _LIB_LISTTYPE.LLT_NAMESPACES: ppIVsSimpleObjectList2 = listProvider.GetSearchList(); break; default: ppIVsSimpleObjectList2 = null; return VSConstants.E_FAIL; } } else { if (pobSrch[0].eSrchType == VSOBSEARCHTYPE.SO_ENTIREWORD && ListType == (uint)_LIB_LISTTYPE.LLT_MEMBERS) { string srchText = pobSrch[0].szName; int colonIndex; if ((colonIndex = srchText.LastIndexOf(':')) != -1) { string filename = srchText.Substring(0, srchText.LastIndexOf(':')); foreach (ProjectLibraryNode project in _root.Children) { foreach (var item in project.Children) { if (item.FullName == filename) { ppIVsSimpleObjectList2 = item.DoSearch(pobSrch[0]); if (ppIVsSimpleObjectList2 != null) { return VSConstants.S_OK; } } } } } ppIVsSimpleObjectList2 = null; return VSConstants.E_FAIL; } else if (pobSrch[0].eSrchType == VSOBSEARCHTYPE.SO_SUBSTRING && ListType == (uint)_LIB_LISTTYPE.LLT_NAMESPACES) { var lib = new LibraryNode(null, "Search results " + pobSrch[0].szName, "Search results " + pobSrch[0].szName, LibraryNodeType.Package); foreach (var item in SearchNodes(pobSrch[0], new SimpleObjectList<LibraryNode>(), _root).Children) { lib.Children.Add(item); } ppIVsSimpleObjectList2 = lib; return VSConstants.S_OK; } else if ((pobSrch[0].grfOptions & (uint)_VSOBSEARCHOPTIONS.VSOBSO_LOOKINREFS) != 0 && ListType == (uint)_LIB_LISTTYPE.LLT_HIERARCHY) { LibraryNode node = pobSrch[0].pIVsNavInfo as LibraryNode; if (node != null) { var refs = node.FindReferences(); if (refs != null) { ppIVsSimpleObjectList2 = refs; return VSConstants.S_OK; } } } ppIVsSimpleObjectList2 = null; return VSConstants.E_FAIL; } } else { ppIVsSimpleObjectList2 = _root as IVsSimpleObjectList2; } return VSConstants.S_OK; } private static SimpleObjectList<LibraryNode> SearchNodes(VSOBSEARCHCRITERIA2 srch, SimpleObjectList<LibraryNode> list, LibraryNode curNode) { foreach (var child in curNode.Children) { if (child.Name.IndexOf(srch.szName, StringComparison.OrdinalIgnoreCase) != -1) { list.Children.Add(child.Clone(child.Name)); } SearchNodes(srch, list, child); } return list; } internal async Task VisitNodesAsync(ILibraryNodeVisitor visitor, CancellationToken ct = default(CancellationToken)) { await _searching.WaitAsync(ct); try { await Task.Run(() => _root.Visit(visitor, ct)); ApplyUpdates(true); } finally { _searching.Release(); } } public int GetSeparatorStringWithOwnership(out string pbstrSeparator) { pbstrSeparator = "."; return VSConstants.S_OK; } public int GetSupportedCategoryFields2(int Category, out uint pgrfCatField) { pgrfCatField = (uint)_LIB_CATEGORY2.LC_HIERARCHYTYPE | (uint)_LIB_CATEGORY2.LC_PHYSICALCONTAINERTYPE; return VSConstants.S_OK; } public int LoadState(IStream pIStream, LIB_PERSISTTYPE lptType) { return VSConstants.S_OK; } public int RemoveBrowseContainer(uint dwReserved, string pszLibName) { return VSConstants.E_NOTIMPL; } public int SaveState(IStream pIStream, LIB_PERSISTTYPE lptType) { return VSConstants.S_OK; } public int UpdateCounter(out uint pCurUpdate) { pCurUpdate = _updateCount; return VSConstants.S_OK; } public void Update() { _updateCount++; _root.Update(); } #endregion } }
using System; using System.Collections.Generic; using NUnit.Framework; namespace ServiceStack.Text.Tests.UseCases { /// <summary> /// Solution in response to: /// http://stackoverflow.com/questions/5057684/json-c-deserializing-a-changing-content-or-a-piece-of-json-response /// </summary> public class CentroidTests { public class Centroid { public Centroid(decimal latitude, decimal longitude) { Latitude = latitude; Longitude = longitude; } public string LatLon { get { return String.Format("{0};{1}", Latitude, Longitude); } } public decimal Latitude { get; set; } public decimal Longitude { get; set; } } public class BoundingBox { public Centroid SouthWest { get; set; } public Centroid NorthEast { get; set; } } public class Place { public int WoeId { get; set; } public string PlaceTypeName { get; set; } public string Name { get; set; } public Dictionary<string, string> PlaceTypeNameAttrs { get; set; } public string Country { get; set; } public Dictionary<string, string> CountryAttrs { get; set; } public string Admin1 { get; set; } public Dictionary<string, string> Admin1Attrs { get; set; } public string Admin2 { get; set; } public string Admin3 { get; set; } public string Locality1 { get; set; } public string Locality2 { get; set; } public string Postal { get; set; } public Centroid Centroid { get; set; } public BoundingBox BoundingBox { get; set; } public int AreaRank { get; set; } public int PopRank { get; set; } public string Uri { get; set; } public string Lang { get; set; } } private const string JsonCentroid = @"{ ""place"":{ ""woeid"":12345, ""placeTypeName"":""State"", ""placeTypeName attrs"":{ ""code"":8 }, ""name"":""My Region"", ""country"":"""", ""country attrs"":{ ""type"":""Country"", ""code"":""XX"" }, ""admin1"":""My Region"", ""admin1 attrs"":{ ""type"":""Region"", ""code"":"""" }, ""admin2"":"""", ""admin3"":"""", ""locality1"":"""", ""locality2"":"""", ""postal"":"""", ""centroid"":{ ""latitude"":30.12345, ""longitude"":40.761292 }, ""boundingBox"":{ ""southWest"":{ ""latitude"":32.2799, ""longitude"":50.715958 }, ""northEast"":{ ""latitude"":29.024891, ""longitude"":12.1234 } }, ""areaRank"":10, ""popRank"":0, ""uri"":""http:\/\/where.yahooapis.com"", ""lang"":""en-US"" } }"; [Test] public void Can_Parse_Centroid_using_JsonObject() { Func<JsonObject, Centroid> toCentroid = map => new Centroid(map.Get<decimal>("latitude"), map.Get<decimal>("longitude")); var place = JsonObject.Parse(JsonCentroid) .Object("place") .ConvertTo(x => new Place { WoeId = x.Get<int>("woeid"), PlaceTypeName = x.Get(""), PlaceTypeNameAttrs = x.Object("placeTypeName attrs"), Name = x.Get("Name"), Country = x.Get("Country"), CountryAttrs = x.Object("country attrs"), Admin1 = x.Get("admin1"), Admin1Attrs = x.Object("admin1 attrs"), Admin2 = x.Get("admin2"), Admin3 = x.Get("admin3"), Locality1 = x.Get("locality1"), Locality2 = x.Get("locality2"), Postal = x.Get("postal"), Centroid = x.Object("centroid") .ConvertTo(toCentroid), BoundingBox = x.Object("boundingBox") .ConvertTo(y => new BoundingBox { SouthWest = y.Object("southWest").ConvertTo(toCentroid), NorthEast = y.Object("northEast").ConvertTo(toCentroid) }), AreaRank = x.Get<int>("areaRank"), PopRank = x.Get<int>("popRank"), Uri = x.Get("uri"), Lang = x.Get("lang"), }); Console.WriteLine(place.Dump()); /*Outputs: { WoeId: 12345, PlaceTypeNameAttrs: { code: 8 }, CountryAttrs: { type: Country, code: XX }, Admin1: My Region, Admin1Attrs: { type: Region, code: }, Admin2: , Admin3: , Locality1: , Locality2: , Postal: , Centroid: { LatLon: 30.12345;40.761292, Latitude: 30.12345, Longitude: 40.761292 }, BoundingBox: { SouthWest: { LatLon: 32.2799;50.715958, Latitude: 32.2799, Longitude: 50.715958 }, NorthEast: { LatLon: 29.024891;12.1234, Latitude: 29.024891, Longitude: 12.1234 } }, AreaRank: 10, PopRank: 0, Uri: "http://where.yahooapis.com", Lang: en-US } **/ } } }
// // Copyright (c) 2008-2011, Kenneth Bell // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // namespace DiscUtils.Iso9660 { using System.IO; using DiscUtils.Vfs; /// <summary> /// Class for reading existing ISO images. /// </summary> public class CDReader : VfsFileSystemFacade, IClusterBasedFileSystem, IUnixFileSystem { /// <summary> /// Initializes a new instance of the CDReader class. /// </summary> /// <param name="data">The stream to read the ISO image from.</param> /// <param name="joliet">Whether to read Joliet extensions.</param> public CDReader(Stream data, bool joliet) : base(new VfsCDReader(data, joliet, false)) { } /// <summary> /// Initializes a new instance of the CDReader class. /// </summary> /// <param name="data">The stream to read the ISO image from.</param> /// <param name="joliet">Whether to read Joliet extensions.</param> /// <param name="hideVersions">Hides version numbers (e.g. ";1") from the end of files</param> public CDReader(Stream data, bool joliet, bool hideVersions) : base(new VfsCDReader(data, joliet, hideVersions)) { } /// <summary> /// Gets a value indicating whether a boot image is present. /// </summary> public bool HasBootImage { get { return GetRealFileSystem<VfsCDReader>().HasBootImage; } } /// <summary> /// Gets the emulation requested of BIOS when the image is loaded. /// </summary> public BootDeviceEmulation BootEmulation { get { return GetRealFileSystem<VfsCDReader>().BootEmulation; } } /// <summary> /// Gets the memory segment the image should be loaded into (0 for default). /// </summary> public int BootLoadSegment { get { return GetRealFileSystem<VfsCDReader>().BootLoadSegment; } } /// <summary> /// Gets the absolute start position (in bytes) of the boot image, or zero if not found. /// </summary> public long BootImageStart { get { return GetRealFileSystem<VfsCDReader>().BootImageStart; } } /// <summary> /// Gets the size (in bytes) of each cluster. /// </summary> public long ClusterSize { get { return GetRealFileSystem<VfsCDReader>().ClusterSize; } } /// <summary> /// Gets the total number of clusters managed by the file system. /// </summary> public long TotalClusters { get { return GetRealFileSystem<VfsCDReader>().TotalClusters; } } /// <summary> /// Gets which of the Iso9660 variants is being used. /// </summary> public Iso9660Variant ActiveVariant { get { return GetRealFileSystem<VfsCDReader>().ActiveVariant; } } /// <summary> /// Detects if a stream contains a valid ISO file system. /// </summary> /// <param name="data">The stream to inspect</param> /// <returns><c>true</c> if the stream contains an ISO file system, else false.</returns> public static bool Detect(Stream data) { byte[] buffer = new byte[IsoUtilities.SectorSize]; if (data.Length < 0x8000 + IsoUtilities.SectorSize) { return false; } data.Position = 0x8000; int numRead = Utilities.ReadFully(data, buffer, 0, IsoUtilities.SectorSize); if (numRead != IsoUtilities.SectorSize) { return false; } BaseVolumeDescriptor bvd = new BaseVolumeDescriptor(buffer, 0); return bvd.StandardIdentifier == "CD001"; } /// <summary> /// Opens a stream containing the boot image. /// </summary> /// <returns>The boot image as a stream</returns> public Stream OpenBootImage() { return GetRealFileSystem<VfsCDReader>().OpenBootImage(); } /// <summary> /// Converts a cluster (index) into an absolute byte position in the underlying stream. /// </summary> /// <param name="cluster">The cluster to convert</param> /// <returns>The corresponding absolute byte position.</returns> public long ClusterToOffset(long cluster) { return GetRealFileSystem<VfsCDReader>().ClusterToOffset(cluster); } /// <summary> /// Converts an absolute byte position in the underlying stream to a cluster (index). /// </summary> /// <param name="offset">The byte position to convert</param> /// <returns>The cluster containing the specified byte</returns> public long OffsetToCluster(long offset) { return GetRealFileSystem<VfsCDReader>().OffsetToCluster(offset); } /// <summary> /// Converts a file name to the list of clusters occupied by the file's data. /// </summary> /// <param name="path">The path to inspect</param> /// <returns>The clusters</returns> /// <remarks>Note that in some file systems, small files may not have dedicated /// clusters. Only dedicated clusters will be returned.</remarks> public Range<long, long>[] PathToClusters(string path) { return GetRealFileSystem<VfsCDReader>().PathToClusters(path); } /// <summary> /// Converts a file name to the extents containing its data. /// </summary> /// <param name="path">The path to inspect</param> /// <returns>The file extents, as absolute byte positions in the underlying stream</returns> /// <remarks>Use this method with caution - not all file systems will store all bytes /// directly in extents. Files may be compressed, sparse or encrypted. This method /// merely indicates where file data is stored, not what's stored.</remarks> public StreamExtent[] PathToExtents(string path) { return GetRealFileSystem<VfsCDReader>().PathToExtents(path); } /// <summary> /// Gets an object that can convert between clusters and files. /// </summary> /// <returns>The cluster map</returns> public ClusterMap BuildClusterMap() { return GetRealFileSystem<VfsCDReader>().BuildClusterMap(); } /// <summary> /// Retrieves Unix-specific information about a file or directory. /// </summary> /// <param name="path">Path to the file or directory</param> /// <returns>Information about the owner, group, permissions and type of the /// file or directory.</returns> public UnixFileSystemInfo GetUnixFileInfo(string path) { return GetRealFileSystem<VfsCDReader>().GetUnixFileInfo(path); } } }
using UnityEngine; using UnityEditor; using System.Collections; using System.Collections.Generic; using DecalFramework; public class ProjectedStaticDecal : MonoBehaviour { [HideInInspector] public NDPlane yPosPlane = new NDPlane(); [HideInInspector] public NDPlane yNegPlane = new NDPlane(); [HideInInspector] public NDPlane xPosPlane = new NDPlane(); [HideInInspector] public NDPlane xNegPlane = new NDPlane(); [HideInInspector] public NDPlane zPosPlane = new NDPlane(); [HideInInspector] public NDPlane zNegPlane = new NDPlane(); [HideInInspector] public List<Vector3> vertexPoints = new List<Vector3>(); [HideInInspector] public List<int> indexPoints = new List<int>(); [HideInInspector] public List<Vector2> uvPoints = new List<Vector2>(); [HideInInspector] public OOBB oobb = new OOBB(); public Material material; public int layer = 1; private static float offset = 0.0015f; [HideInInspector] public bool updateEnabled = true; [HideInInspector] public bool rtUpdateEnabled = false; [HideInInspector] public bool collInEditor = false; public bool cubeMap = false; //GameObject projection; //private Mesh decalMesh; [HideInInspector] public SceneData data; public void create(SceneData data) { this.data = data; //material = Resources.LoadAssetAtPath("Assets/DecalFramework/Textures/DefaultDecal.mat", typeof(Material)) as Material; offset = 0.01f; //decalMesh = new Mesh(); /*if (projection == null) { projection = new GameObject(); projection.name = gameObject.name + "_proj"; projectionFilter = (MeshFilter)projection.AddComponent(typeof(MeshFilter)); projection.AddComponent(typeof(MeshRenderer)); projectionFilter.sharedMesh = new Mesh(); //projection.transform.position = offset; projection.transform.parent = transform.parent; }*/ oobb.update(gameObject); } public void clear(SceneData data) { create(data); } void OnDrawGizmos() { Vector3 size = new Vector3(0.02f,0.02f,0.02f); if (Selection.Contains(gameObject)) { oobb.update(gameObject); // render the AABB in green Gizmos.color = new Color(0,1,0,1); // draw the center Gizmos.DrawCube(oobb.center, size); // draw the corners for (int i = 0; i < 8; i++) { Gizmos.DrawCube(oobb.aabbCoordsTrans[i], size); } // draw the edges - total of 12 edges for AABB Gizmos.DrawLine(oobb.aabbCoordsTrans[0], oobb.aabbCoordsTrans[1]); Gizmos.DrawLine(oobb.aabbCoordsTrans[0], oobb.aabbCoordsTrans[2]); Gizmos.DrawLine(oobb.aabbCoordsTrans[0], oobb.aabbCoordsTrans[4]); Gizmos.DrawLine(oobb.aabbCoordsTrans[1], oobb.aabbCoordsTrans[3]); Gizmos.DrawLine(oobb.aabbCoordsTrans[1], oobb.aabbCoordsTrans[5]); Gizmos.DrawLine(oobb.aabbCoordsTrans[2], oobb.aabbCoordsTrans[6]); Gizmos.DrawLine(oobb.aabbCoordsTrans[2], oobb.aabbCoordsTrans[3]); Gizmos.DrawLine(oobb.aabbCoordsTrans[3], oobb.aabbCoordsTrans[7]); Gizmos.DrawLine(oobb.aabbCoordsTrans[4], oobb.aabbCoordsTrans[5]); Gizmos.DrawLine(oobb.aabbCoordsTrans[4], oobb.aabbCoordsTrans[6]); Gizmos.DrawLine(oobb.aabbCoordsTrans[5], oobb.aabbCoordsTrans[7]); Gizmos.DrawLine(oobb.aabbCoordsTrans[6], oobb.aabbCoordsTrans[7]); // render the OOBB in red Gizmos.color = new Color(1,0,0,1); // draw the corners for (int i = 0; i < 8; i++) { Gizmos.DrawCube(oobb.oobbCoordsTrans[i], size); } // draw the edges - total of 12 edges for OOBB Gizmos.DrawLine(oobb.oobbCoordsTrans[0], oobb.oobbCoordsTrans[1]); Gizmos.DrawLine(oobb.oobbCoordsTrans[0], oobb.oobbCoordsTrans[2]); Gizmos.DrawLine(oobb.oobbCoordsTrans[0], oobb.oobbCoordsTrans[4]); Gizmos.DrawLine(oobb.oobbCoordsTrans[1], oobb.oobbCoordsTrans[3]); Gizmos.DrawLine(oobb.oobbCoordsTrans[1], oobb.oobbCoordsTrans[5]); Gizmos.DrawLine(oobb.oobbCoordsTrans[2], oobb.oobbCoordsTrans[6]); Gizmos.DrawLine(oobb.oobbCoordsTrans[2], oobb.oobbCoordsTrans[3]); Gizmos.DrawLine(oobb.oobbCoordsTrans[3], oobb.oobbCoordsTrans[7]); Gizmos.DrawLine(oobb.oobbCoordsTrans[4], oobb.oobbCoordsTrans[5]); Gizmos.DrawLine(oobb.oobbCoordsTrans[4], oobb.oobbCoordsTrans[6]); Gizmos.DrawLine(oobb.oobbCoordsTrans[5], oobb.oobbCoordsTrans[7]); Gizmos.DrawLine(oobb.oobbCoordsTrans[6], oobb.oobbCoordsTrans[7]); // draw intersection points if any /*Gizmos.color = new Color(0,0,1,1); for (int i = 0; i < vertexPoints.Count; i++) { Gizmos.DrawCube(vertexPoints[i], size); } for (int i = 0; i < indexPoints.Count; i+=3) { Gizmos.DrawLine(vertexPoints[indexPoints[i]], vertexPoints[indexPoints[i + 1]]); Gizmos.DrawLine(vertexPoints[indexPoints[i + 1]], vertexPoints[indexPoints[i + 2]]); Gizmos.DrawLine(vertexPoints[indexPoints[i + 2]], vertexPoints[indexPoints[i]]); }*/ } } private List<Vector3> points = new List<Vector3>(); private List<Vector3> lpoints = new List<Vector3>(); private List<Vector3> newTris = new List<Vector3>(); public void updateMesh() { vertexPoints.Clear(); indexPoints.Clear(); uvPoints.Clear(); oobb.update(gameObject); Vector3 dirUp = gameObject.transform.TransformDirection(Vector3.up); Vector3 dirUpPos = gameObject.transform.position - (dirUp * gameObject.transform.localScale.y); Vector3 dirDown = gameObject.transform.TransformDirection(Vector3.down); Vector3 dirDownPos = gameObject.transform.position - (dirDown * gameObject.transform.localScale.y); Vector3 dirForward = gameObject.transform.TransformDirection(Vector3.forward); Vector3 dirForwardPos = gameObject.transform.position - (dirForward * gameObject.transform.localScale.z); Vector3 dirBack = gameObject.transform.TransformDirection(Vector3.back); Vector3 dirBackPos = gameObject.transform.position - (dirBack * gameObject.transform.localScale.z); Vector3 dirLeft = gameObject.transform.TransformDirection(Vector3.left); Vector3 dirLeftPos = gameObject.transform.position - (dirLeft * gameObject.transform.localScale.x); Vector3 dirRight = gameObject.transform.TransformDirection(Vector3.right); Vector3 dirRightPos = gameObject.transform.position - (dirRight * gameObject.transform.localScale.x); yPosPlane.SetValues(dirUp, dirUpPos); yNegPlane.SetValues(dirDown, dirDownPos); zPosPlane.SetValues(dirForward, dirForwardPos); zNegPlane.SetValues(dirBack, dirBackPos); xPosPlane.SetValues(dirLeft, dirLeftPos); xNegPlane.SetValues(dirRight, dirRightPos); if (data != null) { List<TriangleData> tris = data.getTrianglesInOOBB(oobb); //Debug.Log(tris.Count); Vector3 lineInt = new Vector3(); for (int i = 0; i < tris.Count; i++) { Vector3[] pts = tris[i].getTransformedPoints(); Vector3 point1 = pts[0]; Vector3 point2 = pts[1]; Vector3 point3 = pts[2]; Vector3 n = Vector3.Cross(point2 - point1, point3 - point1); n.Normalize(); points.Clear(); newTris.Clear(); lpoints.Clear(); if (TriangleTests.IntersectLineTriangle(ref oobb.oobbCoordsTrans[0], ref oobb.oobbCoordsTrans[1], ref point1, ref point2, ref point3, ref lineInt)) lpoints.Add(lineInt); if (TriangleTests.IntersectLineTriangle(ref oobb.oobbCoordsTrans[0], ref oobb.oobbCoordsTrans[2], ref point1, ref point2, ref point3, ref lineInt)) lpoints.Add(lineInt); if (TriangleTests.IntersectLineTriangle(ref oobb.oobbCoordsTrans[0], ref oobb.oobbCoordsTrans[4], ref point1, ref point2, ref point3, ref lineInt)) lpoints.Add(lineInt); if (TriangleTests.IntersectLineTriangle(ref oobb.oobbCoordsTrans[1], ref oobb.oobbCoordsTrans[3], ref point1, ref point2, ref point3, ref lineInt)) lpoints.Add(lineInt); if (TriangleTests.IntersectLineTriangle(ref oobb.oobbCoordsTrans[1], ref oobb.oobbCoordsTrans[5], ref point1, ref point2, ref point3, ref lineInt)) lpoints.Add(lineInt); if (TriangleTests.IntersectLineTriangle(ref oobb.oobbCoordsTrans[2], ref oobb.oobbCoordsTrans[6], ref point1, ref point2, ref point3, ref lineInt)) lpoints.Add(lineInt); if (TriangleTests.IntersectLineTriangle(ref oobb.oobbCoordsTrans[2], ref oobb.oobbCoordsTrans[3], ref point1, ref point2, ref point3, ref lineInt)) lpoints.Add(lineInt); if (TriangleTests.IntersectLineTriangle(ref oobb.oobbCoordsTrans[3], ref oobb.oobbCoordsTrans[7], ref point1, ref point2, ref point3, ref lineInt)) lpoints.Add(lineInt); if (TriangleTests.IntersectLineTriangle(ref oobb.oobbCoordsTrans[4], ref oobb.oobbCoordsTrans[5], ref point1, ref point2, ref point3, ref lineInt)) lpoints.Add(lineInt); if (TriangleTests.IntersectLineTriangle(ref oobb.oobbCoordsTrans[4], ref oobb.oobbCoordsTrans[6], ref point1, ref point2, ref point3, ref lineInt)) lpoints.Add(lineInt); if (TriangleTests.IntersectLineTriangle(ref oobb.oobbCoordsTrans[5], ref oobb.oobbCoordsTrans[7], ref point1, ref point2, ref point3, ref lineInt)) lpoints.Add(lineInt); if (TriangleTests.IntersectLineTriangle(ref oobb.oobbCoordsTrans[6], ref oobb.oobbCoordsTrans[7], ref point1, ref point2, ref point3, ref lineInt)) lpoints.Add(lineInt); NDPlane.IntersectSixPlanesTriangle(xPosPlane, xNegPlane, yPosPlane, yNegPlane, zPosPlane, zNegPlane, ref point1, ref point2, ref point3, lpoints); NDPlane.SideOfSixPlanesFilter(xPosPlane, xNegPlane, yPosPlane, yNegPlane, zPosPlane, zNegPlane, lpoints, points); HullTests.ConvexHull2DTriangulated(points, newTris, ref n); for (int j = 0; j < newTris.Count; j += 3) { Vector3 v1 = newTris[j + 0]; Vector3 v2 = newTris[j + 1]; Vector3 v3 = newTris[j + 2]; float tolerance = layer * offset; Vector3 dist = n * tolerance; v1 = v1 + dist; v2 = v2 + dist; v3 = v3 + dist; int vec1 = 0; int vec2 = 0; int vec3 = 0; // point is new, compute new UV coordinates for it if (!NearestPointTest.approxContains(vertexPoints, v1, tolerance, ref vec1)) { Vector3 transVec = gameObject.transform.InverseTransformPoint(vertexPoints[vec1]); if (!cubeMap) { uvPoints.Add(new Vector2((transVec.y + 1) / 2, (transVec.z + 1) / 2)); } else { uvPoints.Add(HullTests.CubeMap3DV(ref transVec, ref n)); } } if (!NearestPointTest.approxContains(vertexPoints, v2, tolerance, ref vec2)) { Vector3 transVec = gameObject.transform.InverseTransformPoint(vertexPoints[vec2]); if (!cubeMap) { uvPoints.Add(new Vector2((transVec.y + 1) / 2, (transVec.z + 1) / 2)); } else { uvPoints.Add(HullTests.CubeMap3DV(ref transVec, ref n)); } } if (!NearestPointTest.approxContains(vertexPoints, v3, tolerance, ref vec3)) { Vector3 transVec = gameObject.transform.InverseTransformPoint(vertexPoints[vec3]); if (!cubeMap) { uvPoints.Add(new Vector2((transVec.y + 1) / 2, (transVec.z + 1) / 2)); } else { uvPoints.Add(HullTests.CubeMap3DV(ref transVec, ref n)); } } //Debug.Log(vertexPoints.Count + " " + vec1 + " " + vec2 + " " + vec3); if (HullTests.IsTriClockwise(vertexPoints[vec1], vertexPoints[vec2], vertexPoints[vec3], n)) { indexPoints.Add(vec1); indexPoints.Add(vec2); indexPoints.Add(vec3); } else { indexPoints.Add(vec1); indexPoints.Add(vec3); indexPoints.Add(vec2); } } } } } public void selectObj() { GameObject[] gos = new GameObject[2]; gos[0] = gameObject; //gos[1] = projection; Selection.objects = gos; } public void destroy() { //DestroyImmediate(projection); DestroyImmediate(gameObject); } public bool isUpdateEnabled() { return updateEnabled; } public bool isRtUpdateEnabled() { return rtUpdateEnabled; } public void setUpdateEnabled(bool enabled) { updateEnabled = enabled; } public void setRtUpdateEnabled(bool enabled) { rtUpdateEnabled = enabled; } public void fillBatchData(MeshBatchFiller batch) { //Debug.Log("Asking for Batch"); batch.vertices = vertexPoints; batch.indices = indexPoints; batch.uv = uvPoints; batch.material = material; } }
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.Net.Http; using System.Threading; using System.Linq.Expressions; /// <summary> /// The type UserCalendarViewCollectionRequest. /// </summary> public partial class UserCalendarViewCollectionRequest : BaseRequest, IUserCalendarViewCollectionRequest { /// <summary> /// Constructs a new UserCalendarViewCollectionRequest. /// </summary> /// <param name="requestUrl">The URL for the built request.</param> /// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param> /// <param name="options">Query and header option name value pairs for the request.</param> public UserCalendarViewCollectionRequest( string requestUrl, IBaseClient client, IEnumerable<Option> options) : base(requestUrl, client, options) { } /// <summary> /// Adds the specified Event to the collection via POST. /// </summary> /// <param name="calendarViewEvent">The Event to add.</param> /// <returns>The created Event.</returns> public System.Threading.Tasks.Task<Event> AddAsync(Event calendarViewEvent) { return this.AddAsync(calendarViewEvent, CancellationToken.None); } /// <summary> /// Adds the specified Event to the collection via POST. /// </summary> /// <param name="calendarViewEvent">The Event to add.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The created Event.</returns> public System.Threading.Tasks.Task<Event> AddAsync(Event calendarViewEvent, CancellationToken cancellationToken) { this.ContentType = "application/json"; this.Method = "POST"; return this.SendAsync<Event>(calendarViewEvent, cancellationToken); } /// <summary> /// Gets the collection page. /// </summary> /// <returns>The collection page.</returns> public System.Threading.Tasks.Task<IUserCalendarViewCollectionPage> GetAsync() { return this.GetAsync(CancellationToken.None); } /// <summary> /// Gets the collection page. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The collection page.</returns> public async System.Threading.Tasks.Task<IUserCalendarViewCollectionPage> GetAsync(CancellationToken cancellationToken) { this.Method = "GET"; var response = await this.SendAsync<UserCalendarViewCollectionResponse>(null, cancellationToken).ConfigureAwait(false); if (response != null && response.Value != null && response.Value.CurrentPage != null) { if (response.AdditionalData != null) { object nextPageLink; response.AdditionalData.TryGetValue("@odata.nextLink", out nextPageLink); var nextPageLinkString = nextPageLink as string; if (!string.IsNullOrEmpty(nextPageLinkString)) { response.Value.InitializeNextPageRequest( this.Client, nextPageLinkString); } // Copy the additional data collection to the page itself so that information is not lost response.Value.AdditionalData = response.AdditionalData; } return response.Value; } return null; } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="value">The expand value.</param> /// <returns>The request object to send.</returns> public IUserCalendarViewCollectionRequest Expand(string value) { this.QueryOptions.Add(new QueryOption("$expand", value)); return this; } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="expandExpression">The expression from which to calculate the expand value.</param> /// <returns>The request object to send.</returns> public IUserCalendarViewCollectionRequest Expand(Expression<Func<Event, object>> expandExpression) { if (expandExpression == null) { throw new ArgumentNullException(nameof(expandExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(expandExpression)); } else { this.QueryOptions.Add(new QueryOption("$expand", value)); } return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="value">The select value.</param> /// <returns>The request object to send.</returns> public IUserCalendarViewCollectionRequest Select(string value) { this.QueryOptions.Add(new QueryOption("$select", value)); return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="selectExpression">The expression from which to calculate the select value.</param> /// <returns>The request object to send.</returns> public IUserCalendarViewCollectionRequest Select(Expression<Func<Event, object>> selectExpression) { if (selectExpression == null) { throw new ArgumentNullException(nameof(selectExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(selectExpression)); } else { this.QueryOptions.Add(new QueryOption("$select", value)); } return this; } /// <summary> /// Adds the specified top value to the request. /// </summary> /// <param name="value">The top value.</param> /// <returns>The request object to send.</returns> public IUserCalendarViewCollectionRequest Top(int value) { this.QueryOptions.Add(new QueryOption("$top", value.ToString())); return this; } /// <summary> /// Adds the specified filter value to the request. /// </summary> /// <param name="value">The filter value.</param> /// <returns>The request object to send.</returns> public IUserCalendarViewCollectionRequest Filter(string value) { this.QueryOptions.Add(new QueryOption("$filter", value)); return this; } /// <summary> /// Adds the specified skip value to the request. /// </summary> /// <param name="value">The skip value.</param> /// <returns>The request object to send.</returns> public IUserCalendarViewCollectionRequest Skip(int value) { this.QueryOptions.Add(new QueryOption("$skip", value.ToString())); return this; } /// <summary> /// Adds the specified orderby value to the request. /// </summary> /// <param name="value">The orderby value.</param> /// <returns>The request object to send.</returns> public IUserCalendarViewCollectionRequest OrderBy(string value) { this.QueryOptions.Add(new QueryOption("$orderby", value)); return this; } } }
using BTDB.IOC; using BTDB.KVDBLayer; using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Reflection; using System.Threading.Tasks; using Xunit; namespace BTDBTest; using IOCDomain; public class IocTests { [Fact] public void AlwaysNew() { var builder = new ContainerBuilder(); builder.RegisterType<Logger>().As<ILogger>(); var container = builder.BuildAndVerify(); var log1 = container.Resolve<ILogger>(); Assert.NotNull(log1); var log2 = container.Resolve<ILogger>(); Assert.NotNull(log2); Assert.NotSame(log1, log2); } [Fact] public void Singleton() { var builder = new ContainerBuilder(); builder.RegisterType<Logger>().As<ILogger>().SingleInstance(); var container = builder.BuildAndVerify(); var log1 = container.Resolve<ILogger>(); Assert.NotNull(log1); var log2 = container.Resolve<ILogger>(); Assert.NotNull(log2); Assert.Same(log1, log2); } [Fact] public void CreatesFuncFactory() { var builder = new ContainerBuilder(); builder.RegisterType<Logger>().As<ILogger>(); var container = builder.Build(); var logFactory = container.Resolve<Func<ILogger>>(); var log1 = logFactory(); Assert.NotNull(log1); var log2 = logFactory(); Assert.NotNull(log2); Assert.NotSame(log1, log2); } [Fact] public void CreatesLazyFactory() { var builder = new ContainerBuilder(); builder.RegisterType<Logger>().As<ILogger>(); var container = builder.Build(); var lazyLog = container.Resolve<Lazy<ILogger>>(); var log = lazyLog.Value; Assert.NotNull(log); } [Fact] public void InjectionToConstructorWithOneParameterAlwaysNew() { var builder = new ContainerBuilder(); builder.RegisterType<Logger>().As<ILogger>(); builder.RegisterType<ErrorHandler>().As<IErrorHandler>(); var container = builder.Build(); var obj = container.Resolve<IErrorHandler>(); Assert.NotNull(obj); Assert.NotNull(obj.Logger); var obj2 = container.Resolve<IErrorHandler>(); Assert.NotNull(obj2); Assert.NotNull(obj2.Logger); Assert.NotSame(obj, obj2); Assert.NotSame(obj.Logger, obj2.Logger); } [Fact] public void InjectionToConstructorWithOneParameterSingleton() { var builder = new ContainerBuilder(); builder.RegisterType<Logger>().As<ILogger>().SingleInstance(); builder.RegisterType<ErrorHandler>().As<IErrorHandler>(); var container = builder.Build(); var obj = container.Resolve<IErrorHandler>(); Assert.NotNull(obj); Assert.NotNull(obj.Logger); var obj2 = container.Resolve<IErrorHandler>(); Assert.NotNull(obj2); Assert.NotNull(obj2.Logger); Assert.NotSame(obj, obj2); Assert.Same(obj.Logger, obj2.Logger); } [Fact] public void ReusingSingletonMultipleTimesInOneResolve() { var builder = new ContainerBuilder(); builder.RegisterType<Logger>().As<ILogger>().SingleInstance(); builder.RegisterType<ErrorHandler>().As<IErrorHandler>(); builder.RegisterType<Database>().As<IDatabase>(); var container = builder.Build(); var obj = container.Resolve<IDatabase>(); Assert.NotNull(obj); Assert.NotNull(obj.ErrorHandler); Assert.NotNull(obj.Logger); Assert.Same(obj.Logger, obj.ErrorHandler.Logger); } public class SpecialCase { public SpecialCase(IErrorHandler simple, IDatabase complex) { } } [Fact] public void SingletonInSecondParameterTransientAsSecondParameterToTransient() { var builder = new ContainerBuilder(); builder.RegisterType<Logger>().As<ILogger>().SingleInstance(); builder.RegisterInstance<IErrorHandler>(null); builder.RegisterType<Database>().As<IDatabase>(); builder.RegisterType<SpecialCase>(); var container = builder.Build(); container.Resolve<SpecialCase>(); } [Fact] public void ReusingSingletonMultipleTimesInOneResolveOnceInSingleton() { var builder = new ContainerBuilder(); builder.RegisterType<Logger>().As<ILogger>().SingleInstance(); builder.RegisterType<ErrorHandler>().As<IErrorHandler>().SingleInstance(); builder.RegisterType<Database>().As<IDatabase>(); var container = builder.BuildAndVerify(); var obj = container.Resolve<IDatabase>(); Assert.NotNull(obj); Assert.NotNull(obj.ErrorHandler); Assert.NotNull(obj.Logger); Assert.Same(obj.Logger, obj.ErrorHandler.Logger); var obj2 = container.Resolve<IDatabase>(); Assert.NotNull(obj2); Assert.NotSame(obj, obj2); Assert.Same(obj.ErrorHandler, obj2.ErrorHandler); Assert.Same(obj.Logger, obj2.Logger); } [Fact] public void CreatesFastFuncFactory() { var builder = new ContainerBuilder(); builder.RegisterType<Logger>().As<ILogger>().SingleInstance(); var container = builder.Build(); var obj = container.Resolve<ILogger>(); var fastFactory = container.Resolve<Func<ILogger>>(); var obj2 = fastFactory(); Assert.Same(obj, obj2); } [Fact] public void InjectionToConstructorWithOneParameterSingletonWithOptimization() { var builder = new ContainerBuilder(); builder.RegisterType<Logger>().As<ILogger>().SingleInstance(); builder.RegisterType<ErrorHandler>().As<IErrorHandler>(); var container = builder.Build(); var obj = container.Resolve<ILogger>(); Assert.NotNull(obj); var obj2 = container.Resolve<IErrorHandler>(); Assert.NotNull(obj2); Assert.NotNull(obj2.Logger); Assert.NotSame(obj, obj2); Assert.Same(obj, obj2.Logger); } [Fact] public void CanRegisterInstance() { var builder = new ContainerBuilder(); var instance = new Logger(); builder.RegisterInstance(instance).As<ILogger>(); var container = builder.Build(); var obj = container.Resolve<ILogger>(); Assert.Same(instance, obj); } public interface ICycle1 { ICycle2 Cycle2Prop { get; } } public interface ICycle2 { ICycle1 Cycle1Prop { get; } } public class Cycle1 : ICycle1 { readonly Lazy<ICycle2> _cycle2; public Cycle1(Lazy<ICycle2> cycle2) { _cycle2 = cycle2; } public ICycle2 Cycle2Prop => _cycle2.Value; } public class Cycle2 : ICycle2 { readonly Lazy<ICycle1> _cycle1; public Cycle2(Lazy<ICycle1> cycle1) { _cycle1 = cycle1; } public ICycle1 Cycle1Prop => _cycle1.Value; } [Fact] public void CanBuildLazyCycle() { var builder = new ContainerBuilder(); builder.RegisterType<Cycle1>().As<ICycle1>().SingleInstance(); builder.RegisterType<Cycle2>().As<ICycle2>(); var container = builder.Build(); var obj1 = container.Resolve<ICycle1>(); var obj2 = obj1.Cycle2Prop; Assert.Same(obj1, obj2.Cycle1Prop); } public class InjectingContainer { readonly IContainer _container; public InjectingContainer(IContainer container) { _container = container; } public IContainer Container => _container; } [Fact] public void CanInjectContainer() { var builder = new ContainerBuilder(); builder.RegisterType<InjectingContainer>().As<InjectingContainer>(); var container = builder.Build(); var obj = container.Resolve<InjectingContainer>(); Assert.Same(container, obj.Container); } [Fact] public void RegisterFactory() { var builder = new ContainerBuilder(); builder.RegisterFactory(c => new InjectingContainer(c)).As<InjectingContainer>(); var container = builder.Build(); var obj = container.Resolve<InjectingContainer>(); Assert.Same(container, obj.Container); Assert.NotSame(obj, container.Resolve<InjectingContainer>()); } [Fact] public void RegisterFactoryAsSingleton() { var builder = new ContainerBuilder(); builder.RegisterFactory(c => new InjectingContainer(c)).As<InjectingContainer>().SingleInstance(); var container = builder.Build(); var obj = container.Resolve<InjectingContainer>(); Assert.Same(container, obj.Container); Assert.Same(obj, container.Resolve<InjectingContainer>()); } [Fact] public void RegisterAsImplementedInterfaces() { var builder = new ContainerBuilder(); builder.RegisterType<Logger>().AsImplementedInterfaces(); var container = builder.Build(); var log = container.Resolve<ILogger>(); Assert.NotNull(log); } [Fact] public void RegisterAsSelf() { var builder = new ContainerBuilder(); builder.RegisterType<Logger>().AsSelf(); var container = builder.Build(); var log = container.Resolve<Logger>(); Assert.NotNull(log); } [Fact] public void RegisterDefaultAsSelf() { var builder = new ContainerBuilder(); builder.RegisterType<Logger>(); var container = builder.Build(); var log = container.Resolve<Logger>(); Assert.NotNull(log); } [Fact] public void UnresolvableThrowsException() { var builder = new ContainerBuilder(); var container = builder.Build(); Assert.Throws<ArgumentException>(() => container.Resolve<string>()); } [Fact] public void RegisterAssemblyTypes() { var builder = new ContainerBuilder(); builder.RegisterAssemblyTypes(typeof(Logger).Assembly); var container = builder.Build(); var log = container.Resolve<Logger>(); Assert.NotNull(log); } [Fact] public void RegisterAssemblyTypesWithWhereAndAsImplementedInterfaces() { var builder = new ContainerBuilder(); builder.RegisterAssemblyTypes(typeof(Logger).Assembly) .Where(t => t.Namespace == "BTDBTest.IOCDomain" && !t.Name.Contains("WithProps")) .AsImplementedInterfaces(); var container = builder.Build(); var root = container.Resolve<IWebService>(); Assert.NotNull(root); Assert.NotNull(root.Authenticator.Database.Logger); Assert.NotSame(root.StockQuote.ErrorHandler.Logger, root.Authenticator.Database.Logger); } [Fact] public void RegisterAssemblyTypesWithWhereAndAsImplementedInterfaces2() { var builder = new ContainerBuilder(); builder.RegisterAssemblyTypes(typeof(Logger).Assembly) .Where(t => t.Namespace == "BTDBTest.IOCDomain" && t.Name != "Database").AsImplementedInterfaces() .PropertiesAutowired(); var container = builder.Build(); var root = container.Resolve<IWebService>(); Assert.NotNull(root); Assert.NotNull(root.Authenticator.Database.Logger); Assert.NotSame(root.StockQuote.ErrorHandler.Logger, root.Authenticator.Database.Logger); } [Fact] public void RegisterAssemblyTypesWithWhereAndAsImplementedInterfacesAsSingleton() { var builder = new ContainerBuilder(); builder.RegisterAssemblyTypes(typeof(Logger).Assembly) .Where(t => t.Namespace == "BTDBTest.IOCDomain" && !t.Name.Contains("WithProps")) .AsImplementedInterfaces().SingleInstance(); var container = builder.Build(); var root = container.Resolve<IWebService>(); Assert.NotNull(root); Assert.NotNull(root.Authenticator.Database.Logger); Assert.Same(root.StockQuote.ErrorHandler.Logger, root.Authenticator.Database.Logger); } [Fact] public void RegisterAssemblyTypesWithWhereAndAsImplementedInterfacesAsSingleton2() { var builder = new ContainerBuilder(); builder.RegisterAssemblyTypes(typeof(Logger).Assembly) .Where(t => t.Namespace == "BTDBTest.IOCDomain" && t.Name != "Database").AsImplementedInterfaces() .SingleInstance().PropertiesAutowired(); var container = builder.Build(); var root = container.Resolve<IWebService>(); Assert.NotNull(root); Assert.NotNull(root.Authenticator.Database.Logger); Assert.Same(root.StockQuote.ErrorHandler.Logger, root.Authenticator.Database.Logger); } [Fact] public void RegisterNamedService() { var builder = new ContainerBuilder(); builder.RegisterType<Logger>().Named<ILogger>("log"); var container = builder.Build(); var log = container.ResolveNamed<ILogger>("log"); Assert.NotNull(log); } [Fact] public void RegisterKeyedService() { var builder = new ContainerBuilder(); builder.RegisterType<Logger>().Keyed<ILogger>(true); var container = builder.Build(); var log = container.ResolveKeyed<ILogger>(true); Assert.NotNull(log); } [Fact] public void LastRegisteredHasPriority() { var builder = new ContainerBuilder(); builder.RegisterType<Logger>().As<ILogger>(); builder.RegisterInstance<ILogger>(null!).As<ILogger>(); var container = builder.Build(); Assert.Null(container.Resolve<ILogger>()); } [Fact] public void CanPreserveExistingDefaults() { var builder = new ContainerBuilder(); builder.RegisterType<Logger>().As<ILogger>(); builder.RegisterInstance<ILogger>(default(ILogger)).As<ILogger>().PreserveExistingDefaults(); var container = builder.Build(); Assert.NotNull(container.Resolve<ILogger>()); } [Fact] public void BasicEnumerableResolve() { var builder = new ContainerBuilder(); builder.RegisterInstance("one").Keyed<string>(true); builder.RegisterInstance("bad").Keyed<string>(false); builder.RegisterInstance("two").Keyed<string>(true); var container = builder.Build(); var result = container.ResolveKeyed<IEnumerable<string>>(true); Assert.Equal(new[] { "one", "two" }, result.ToArray()); } [Fact] public void NullInstanceResovedAsConstructorParameter() { var builder = new ContainerBuilder(); builder.RegisterInstance<ILogger>(null); builder.RegisterType<ErrorHandler>().As<IErrorHandler>(); var container = builder.Build(); var obj = container.Resolve<IErrorHandler>(); Assert.Null(obj.Logger); } [Theory] [InlineData(false)] [InlineData(true)] public void FuncWithOneObjectParameter(bool overload) { var builder = new ContainerBuilder(); if (overload) builder.RegisterType<Logger>().As<ILogger>(); builder.RegisterType<ErrorHandler>().As<IErrorHandler>(); var container = builder.Build(); var factory = container.Resolve<Func<ILogger, IErrorHandler>>(); var logger = new Logger(); var obj = factory(logger); Assert.Equal(logger, obj.Logger); } [Fact] public void FuncWithTwoObjectParameters() { var builder = new ContainerBuilder(); builder.RegisterType<Database>().As<IDatabase>(); var container = builder.Build(); var factory = container.Resolve<Func<IErrorHandler, ILogger, IDatabase>>(); var obj = factory(null, null); Assert.NotNull(obj); } [Fact] public void FuncWithTwoObjectParametersWithProps() { var builder = new ContainerBuilder(); builder.RegisterType<DatabaseWithProps>().As<IDatabase>().PropertiesAutowired(); var container = builder.Build(); var factory = container.Resolve<Func<IErrorHandler, ILogger, IDatabase>>(); var logger = new Logger(); var obj = factory(null, logger); Assert.NotNull(obj); Assert.Same(logger, obj.Logger); } [Fact] public void AutowiredWithPropsRequired() { var builder = new ContainerBuilder(); builder.RegisterType<DatabaseWithProps>().As<IDatabase>().PropertiesAutowired(); var container = builder.Build(); Assert.Throws<ArgumentException>(() => container.Resolve<Func<IErrorHandler, IDatabase>>()); Assert.Throws<ArgumentException>(() => container.Resolve<Func<ILogger, IDatabase>>()); } public class DatabaseWithOptionalProps : IDatabase { public ILogger? Logger { get; private set; } public IErrorHandler? ErrorHandler { get; private set; } } [Fact] public void FuncWithOptionalProps() { var builder = new ContainerBuilder(); builder.RegisterType<DatabaseWithOptionalProps>().As<IDatabase>().PropertiesAutowired(); var container = builder.Build(); var factory = container.Resolve<Func<IDatabase>>(); var obj = factory(); Assert.NotNull(obj); } public class DatabaseWithDependencyProps : IDatabase { [Dependency] public ILogger Logger { get; private set; } [Dependency] public IErrorHandler? ErrorHandler { get; private set; } } [Fact] public void FuncWithDependencyProps() { var builder = new ContainerBuilder(); builder.RegisterType<DatabaseWithDependencyProps>().As<IDatabase>(); var container = builder.Build(); var factory = container.Resolve<Func<ILogger, IDatabase>>(); var logger = new Logger(); var obj = factory(logger); Assert.NotNull(obj); Assert.Same(logger, obj.Logger); } public class ClassWithRenamedDependencyProps { [Dependency] public ILogger Logger { get; set; } [Dependency("SuperLogger")] public ILogger Logger2 { get; set; } } [Fact] public void RenamingDependencies() { var builder = new ContainerBuilder(); builder.RegisterType<ClassWithRenamedDependencyProps>().AsSelf(); builder.RegisterType<Logger>().As<ILogger>().SingleInstance(); builder.RegisterType<Logger>().Named<ILogger>("SuperLogger").SingleInstance(); var container = builder.Build(); var obj = container.Resolve<ClassWithRenamedDependencyProps>(); Assert.NotNull(obj); Assert.Same(container.Resolve<ILogger>(), obj.Logger); Assert.Same(container.ResolveNamed<ILogger>("SuperLogger"), obj.Logger2); Assert.NotSame(obj.Logger, obj.Logger2); } public class KlassWith2IntParams { public int Param1 { get; private set; } public int Param2 { get; private set; } public KlassWith2IntParams(int param1, int param2) { Param1 = param1; Param2 = param2; } } delegate KlassWith2IntParams KlassWith2IntParamsFactory(int param2, int param1); [Fact] public void DelegateWithNamedParameters() { var builder = new ContainerBuilder(); builder.RegisterType<KlassWith2IntParams>(); var container = builder.Build(); var factory = container.Resolve<KlassWith2IntParamsFactory>(); var obj = factory(22, 11); Assert.Equal(11, obj.Param1); Assert.Equal(22, obj.Param2); } public class Logger1 : ILogger { } public class Logger2 : ILogger { } static IContainer BuildContainerWithTwoLoggers() { var builder = new ContainerBuilder(); builder.RegisterType<Logger1>().AsImplementedInterfaces(); builder.RegisterType<Logger2>().AsImplementedInterfaces(); return builder.Build(); } static void AssertTwoLoggers(IEnumerable<string> enumTypes) { Assert.Equal(new[] { "Logger1", "Logger2" }, enumTypes); } [Fact] public void AnythingCouldBeEnumerated() { var builder = new ContainerBuilder(); var container = builder.Build(); var allInstances = container.Resolve<IEnumerable<ILogger>>(); Assert.NotNull(allInstances); Assert.Empty(allInstances); } [Fact] public void EnumerateAllInstances() { var container = BuildContainerWithTwoLoggers(); var allInstances = container.Resolve<IEnumerable<ILogger>>(); var enumTypes = allInstances.Select(i => i.GetType().Name); AssertTwoLoggers(enumTypes); } [Fact] public void EnumerateAllInstanceFactories() { var container = BuildContainerWithTwoLoggers(); var allInstances = container.Resolve<IEnumerable<Func<ILogger>>>(); var enumTypes = allInstances.Select(i => i().GetType().Name); AssertTwoLoggers(enumTypes); } [Fact] public void EnumerateAllLazyInstances() { var container = BuildContainerWithTwoLoggers(); var allInstances = container.Resolve<IEnumerable<Lazy<ILogger>>>(); var enumTypes = allInstances.Select(i => i.Value.GetType().Name); AssertTwoLoggers(enumTypes); } [Fact] public void ArrayOfInstances() { var container = BuildContainerWithTwoLoggers(); var allInstances = container.Resolve<ILogger[]>(); var enumTypes = allInstances.Select(i => i.GetType().Name); AssertTwoLoggers(enumTypes); } [Fact] public void TupleResolvable() { var builder = new ContainerBuilder(); builder.RegisterType<Logger1>().AsImplementedInterfaces(); builder.RegisterInstance("hello"); var container = builder.Build(); var tuple = container.Resolve<Tuple<ILogger, string>>(); Assert.Equal("Logger1", tuple.Item1.GetType().Name); Assert.Equal("hello", tuple.Item2); } static IContainer BuildContainerWithTwoLoggersAndTwoStrings() { var builder = new ContainerBuilder(); builder.RegisterType<Logger1>().AsImplementedInterfaces(); builder.RegisterType<Logger2>().AsImplementedInterfaces(); builder.RegisterInstance("A"); builder.RegisterInstance("B"); return builder.Build(); } [Fact] public void EnumerateAllCombinations() { var container = BuildContainerWithTwoLoggersAndTwoStrings(); var tuples = container.Resolve<IEnumerable<Tuple<ILogger, string>>>(); var names = tuples.Select(t => t.Item1.GetType().Name + t.Item2); Assert.Equal(new[] { "Logger1A", "Logger1B", "Logger2A", "Logger2B" }, names); } [Fact] public void EnumerateAllCombinationsNested() { var container = BuildContainerWithTwoLoggersAndTwoStrings(); var tuples = container.Resolve<IEnumerable<Tuple<ILogger, IEnumerable<string>>>>().ToArray(); var enumTypes = tuples.Select(t => t.Item1.GetType().Name); AssertTwoLoggers(enumTypes); var names = tuples.SelectMany(t => t.Item2); Assert.Equal(new[] { "A", "B", "A", "B" }, names); } class PrivateLogger : ILogger { } [Fact] public void CanInstantiatePrivateClassAsSingleton() { var builder = new ContainerBuilder(); builder.RegisterType<PrivateLogger>().As<ILogger>().SingleInstance(); var container = builder.Build(); var log1 = container.Resolve<ILogger>(); Assert.NotNull(log1); } public class PublicClassWithPrivateConstructor : ILogger { PublicClassWithPrivateConstructor() { } } [Fact] public void BuildingContainerWithRegisteredTypeWithPrivateConstructorShouldThrow() { var builder = new ContainerBuilder(); builder.RegisterType<PublicClassWithPrivateConstructor>().As<ILogger>(); Assert.Throws<ArgumentException>(() => builder.Build()); } public class HardCycle1 : ICycle1 { readonly ICycle2 _cycle2; public HardCycle1(ICycle2 cycle2) { _cycle2 = cycle2; } public ICycle2 Cycle2Prop => _cycle2; } public class HardCycle2 : ICycle2 { readonly ICycle1 _cycle1; public HardCycle2(ICycle1 cycle1) { _cycle1 = cycle1; } public ICycle1 Cycle1Prop => _cycle1; } [Fact] public void ResolvingHardCycleShouldThrowException() { var builder = new ContainerBuilder(); builder.RegisterType<HardCycle1>().As<ICycle1>().SingleInstance(); builder.RegisterType<HardCycle2>().As<ICycle2>().SingleInstance(); var container = builder.Build(); Assert.Throws<InvalidOperationException>(() => container.Resolve<ICycle1>()); } [Fact] public void SingletonByTwoInterfacesIsStillSameInstance() { var builder = new ContainerBuilder(); builder.RegisterType<LoggerWithErrorHandler>().As<ILogger>().As<IErrorHandler>().SingleInstance(); var container = builder.Build(); var log1 = container.Resolve<IErrorHandler>(); Assert.NotNull(log1); var log2 = container.Resolve<ILogger>(); Assert.NotNull(log2); Assert.Same(log1, log2); } public class MultipleConstructors { public readonly String Desc; public MultipleConstructors() { Desc = ""; } public MultipleConstructors(int i) { Desc = "Int " + i.ToString(CultureInfo.InvariantCulture); } public MultipleConstructors(string s) { Desc = "String " + s; } public MultipleConstructors(int i, int j) { Desc = "Int " + i.ToString(CultureInfo.InvariantCulture) + ", Int " + j.ToString(CultureInfo.InvariantCulture); } } [Fact] public void UsingConstructorWorks() { var builder = new ContainerBuilder(); builder.RegisterInstance(7).Named<int>("i"); builder.RegisterInstance(3).Named<int>("j"); builder.RegisterInstance("A").Named<string>("s"); builder.RegisterType<MultipleConstructors>().Keyed<MultipleConstructors>(1); builder.RegisterType<MultipleConstructors>().UsingConstructor().Keyed<MultipleConstructors>(2); builder.RegisterType<MultipleConstructors>().UsingConstructor(typeof(int)).Keyed<MultipleConstructors>(3); builder.RegisterType<MultipleConstructors>().UsingConstructor(typeof(string)) .Keyed<MultipleConstructors>(4); builder.RegisterType<MultipleConstructors>().UsingConstructor(typeof(int), typeof(int)) .Keyed<MultipleConstructors>(5); var container = builder.Build(); Assert.Equal("Int 7, Int 3", container.ResolveKeyed<MultipleConstructors>(1).Desc); Assert.Equal("", container.ResolveKeyed<MultipleConstructors>(2).Desc); Assert.Equal("Int 7", container.ResolveKeyed<MultipleConstructors>(3).Desc); Assert.Equal("String A", container.ResolveKeyed<MultipleConstructors>(4).Desc); Assert.Equal("Int 7, Int 3", container.ResolveKeyed<MultipleConstructors>(5).Desc); } public interface ISupport { } public class Support : ISupport { } public interface INotify { } public class Notification : INotify { public Notification(ISupport support) { } } public class NotificationOverride : INotify { public NotificationOverride(ISupport support) { } } public interface IRefinable { } public class RefinePreview : IRefinable { public RefinePreview(Lazy<IWorld> world, INotify notify) { Assert.IsType<NotificationOverride>(notify); } } public interface IOwinServer { } public class WorldHttpHandler : IOwinServer { public WorldHttpHandler(Lazy<IWorld> world, IEnumerable<IRefinable> refinables) { Assert.Single(refinables); } } public interface IWorld { } public class World : IWorld { public World(IOwinServer server, ISupport support, INotify notifyChanges) { } } [Fact] public void DependenciesInEnumerablesWorks() { var builder = new ContainerBuilder(); builder.RegisterType<RefinePreview>().AsImplementedInterfaces().SingleInstance(); builder.RegisterType<WorldHttpHandler>().AsImplementedInterfaces().SingleInstance(); builder.RegisterType<World>().AsImplementedInterfaces().SingleInstance(); builder.RegisterType<Notification>().AsImplementedInterfaces().SingleInstance(); builder.RegisterType<NotificationOverride>().AsImplementedInterfaces().SingleInstance(); builder.RegisterType<Support>().AsImplementedInterfaces().SingleInstance(); var container = builder.Build(); var notificationOverride = container.Resolve<INotify>(); Assert.IsType<NotificationOverride>(notificationOverride); var world = container.Resolve<IWorld>(); } public interface IHandler { } public class Handler : IHandler { readonly ILogger _logger; public Handler(Func<ILogger> logger) { _logger = logger(); } } [Fact] public void FunctionDependencyWithSubdependency() { var containerBuilder = new ContainerBuilder(); containerBuilder.RegisterType<Logger>().AsImplementedInterfaces(); containerBuilder.RegisterType<Handler>().AsImplementedInterfaces().SingleInstance(); var container = containerBuilder.Build(); var handler = container.Resolve<IHandler>(); Assert.NotNull(handler); } public class EnhancedLogger : ILogger { readonly ILogger _parent; public EnhancedLogger(ILogger parent) { _parent = parent; } public ILogger Parent => _parent; } [Fact] public void EnhancingImplementationPossible() { var containerBuilder = new ContainerBuilder(); containerBuilder.RegisterType<Logger>().AsImplementedInterfaces().Named<ILogger>("parent"); containerBuilder.RegisterType<EnhancedLogger>().AsImplementedInterfaces(); var container = containerBuilder.Build(); var handler = container.Resolve<ILogger>(); Assert.IsType<EnhancedLogger>(handler); Assert.IsType<Logger>(((EnhancedLogger)handler).Parent); } class GreedyNonPublicClass { public GreedyNonPublicClass(ILogger a, ILogger b, ILogger c, ILogger d, ILogger e, ILogger f) { } } [Fact] public void ThrowsExceptionForTooManyArgumentsInNonPublicClass() { var containerBuilder = new ContainerBuilder(); containerBuilder.RegisterType<GreedyNonPublicClass>().AsImplementedInterfaces(); foreach (var name in new[] { "a", "b", "c", "d", "e", "f" }) containerBuilder.RegisterType<Logger>().AsImplementedInterfaces().Named<ILogger>(name); var container = containerBuilder.Build(); if (Debugger.IsAttached) { var ex = Assert.Throws<BTDBException>(() => container.Resolve<GreedyNonPublicClass>()); Assert.Contains("Greedy", ex.Message); Assert.Contains("Unsupported", ex.Message); } else { Assert.NotNull(container.Resolve<GreedyNonPublicClass>()); } } [Fact] public void RegisterInstanceUsesGenericParameterForRegistration() { var containerBuilder = new ContainerBuilder(); containerBuilder.RegisterInstance<ILogger>(new Logger()); var container = containerBuilder.Build(); Assert.NotNull(container.Resolve<ILogger>()); } [Fact] public void RegisterInstanceWithObjectParamUsesRealObjectType() { var containerBuilder = new ContainerBuilder(); containerBuilder.RegisterInstance((object)new Logger()); var container = containerBuilder.Build(); Assert.NotNull(container.Resolve<Logger>()); } class ClassDependency { } struct StructDependency { } enum EnumDependency { Foo, Bar, FooBar = Foo | Bar } abstract class OptionalClass<T> { public T Value { get; } public OptionalClass(T t) => Value = t; public override bool Equals(object obj) { var @class = obj as OptionalClass<T>; return @class != null && EqualityComparer<T>.Default.Equals(Value, @class.Value); } public override int GetHashCode() { return -1937169414 + EqualityComparer<T>.Default.GetHashCode(Value); } public override string ToString() => $"{Value}"; } class ClassWithTrueBool : OptionalClass<bool> { public ClassWithTrueBool(bool foo = true) : base(foo) { } } class ClassWithFalseBool : OptionalClass<bool> { public ClassWithFalseBool(bool foo = false) : base(foo) { } } class ClassWithInt16 : OptionalClass<Int16> { public ClassWithInt16(Int16 foo = 11111) : base(foo) { } } class ClassWithInt32 : OptionalClass<Int32> { public ClassWithInt32(Int32 foo = Int32.MaxValue) : base(foo) { } } class ClassWithInt64 : OptionalClass<Int64> { public ClassWithInt64(Int64 foo = Int64.MaxValue) : base(foo) { } } class ClassWithFloat : OptionalClass<float> { public ClassWithFloat(float foo = 1.1f) : base(foo) { } } class ClassWithDouble : OptionalClass<double> { public ClassWithDouble(double foo = 2.2d) : base(foo) { } } class ClassWithDoubleCastedFromFloat : OptionalClass<double> { public ClassWithDoubleCastedFromFloat(double foo = 2.2f) : base(foo) { } } class ClassWithDecimal : OptionalClass<decimal> { public ClassWithDecimal(decimal foo = 3.3m) : base(foo) { } } class ClassWithString : OptionalClass<string> { public ClassWithString(string foo = "str") : base(foo) { } } class ClassWithClass : OptionalClass<ClassDependency> { public ClassWithClass(ClassDependency foo = default) : base(foo) { } } class ClassWithStruct : OptionalClass<StructDependency> { public ClassWithStruct(StructDependency foo = default) : base(foo) { } } class ClassWithEnum : OptionalClass<EnumDependency> { public ClassWithEnum(EnumDependency foo = EnumDependency.Foo) : base(foo) { } } class ClassWithEnum2 : OptionalClass<EnumDependency> { public ClassWithEnum2(EnumDependency foo = EnumDependency.FooBar) : base(foo) { } } class ClassWithNullable : OptionalClass<int?> { public ClassWithNullable(int? foo = default) : base(foo) { } } class ClassWithNullable2 : OptionalClass<int?> { public ClassWithNullable2(int? foo = 10) : base(foo) { } } class ClassWithNullableStruct : OptionalClass<StructDependency?> { public ClassWithNullableStruct(StructDependency? foo = default) : base(foo) { } } class ClassWithDateTime : OptionalClass<DateTime> { public ClassWithDateTime(DateTime foo = default) : base(foo) { } } class ClassWithNullableDateTime : OptionalClass<DateTime?> { public ClassWithNullableDateTime(DateTime? foo = default) : base(foo) { } } [Theory] [InlineData(typeof(ClassWithTrueBool))] [InlineData(typeof(ClassWithFalseBool))] [InlineData(typeof(ClassWithInt16))] [InlineData(typeof(ClassWithInt32))] [InlineData(typeof(ClassWithInt64))] [InlineData(typeof(ClassWithFloat))] [InlineData(typeof(ClassWithDouble))] [InlineData(typeof(ClassWithDoubleCastedFromFloat))] //[InlineData(typeof(ClassWithDecimal), Skip = "Not supported yet")] [InlineData(typeof(ClassWithString))] [InlineData(typeof(ClassWithClass))] [InlineData(typeof(ClassWithStruct))] [InlineData(typeof(ClassWithEnum))] [InlineData(typeof(ClassWithEnum2))] [InlineData(typeof(ClassWithNullable))] [InlineData(typeof(ClassWithNullable2))] [InlineData(typeof(ClassWithNullableStruct))] //[InlineData(typeof(ClassWithDateTime), Skip = "Not supported yet")] [InlineData(typeof(ClassWithNullableDateTime))] public void ResolveWithOptionalParameterWithoutRegister(Type type) { object Create(Type t) => Activator.CreateInstance(t, BindingFlags.CreateInstance | BindingFlags.Public | BindingFlags.Instance | BindingFlags.OptionalParamBinding, null, new object[] { Type.Missing }, CultureInfo.CurrentCulture); var expected = Create(type); var containerBuilder = new ContainerBuilder(); containerBuilder.RegisterType(type); var container = containerBuilder.Build(); var actual = container.Resolve(type); Assert.Equal(expected, actual); } class ClassWithRegisteredOptionalParam : OptionalClass<ClassWithInt32> { public ClassWithRegisteredOptionalParam(ClassWithInt32 t = null) : base(t) { } } [Fact] public void ResolveWithOptionalParameterWithRegister() { var expected = new ClassWithRegisteredOptionalParam(new ClassWithInt32(42)); var containerBuilder = new ContainerBuilder(); containerBuilder.RegisterType<ClassWithRegisteredOptionalParam>(); containerBuilder.RegisterInstance(expected.Value); var container = containerBuilder.Build(); var actual = container.Resolve<ClassWithRegisteredOptionalParam>(); Assert.Equal(expected, actual); } [Fact] public void CanObtainRawDefaultValueOfDateTime() { var ctor = typeof(ClassWithDateTime).GetConstructors()[0]; var dateTimeParameter = ctor.GetParameters()[0]; Assert.True(dateTimeParameter.HasDefaultValue); Assert.Null(dateTimeParameter.RawDefaultValue); } class ClassWithDispose : ILogger, IAsyncDisposable, IDisposable { public async ValueTask DisposeAsync() { await Task.Delay(0); } public void Dispose() { } } [Fact] public void DisposableInterfacesAreNotRegisteredAutomatically() { var containerBuilder = new ContainerBuilder(); containerBuilder.RegisterInstance(new ClassWithDispose()).AsImplementedInterfaces(); var container = containerBuilder.Build(); Assert.NotNull(container.Resolve<ILogger>()); Assert.Throws<ArgumentException>(() => container.Resolve<IDisposable>()); Assert.Throws<ArgumentException>(() => container.Resolve<IAsyncDisposable>()); } [Fact] public void DisposableInterfacesCanBeRegisteredManually() { var containerBuilder = new ContainerBuilder(); containerBuilder.RegisterInstance(new ClassWithDispose()).AsImplementedInterfaces().As<IDisposable>() .As<IAsyncDisposable>(); var container = containerBuilder.Build(); Assert.NotNull(container.Resolve<IDisposable>()); Assert.NotNull(container.Resolve<IAsyncDisposable>()); } [Fact] public void ResolveOptionalWorks() { var containerBuilder = new ContainerBuilder(); containerBuilder.RegisterInstance(new ClassWithDispose()).AsImplementedInterfaces(); var container = containerBuilder.Build(); Assert.NotNull(container.ResolveOptional<ILogger>()); Assert.Null(container.ResolveOptional<IDatabase>()); Assert.Null(container.ResolveOptional<Func<IDatabase>>()); } [Fact] public void ResolveOptionalKeyedWorks() { var builder = new ContainerBuilder(); builder.RegisterType<Logger>().Keyed<ILogger>(true); var container = builder.Build(); Assert.NotNull(container.ResolveOptionalKeyed<ILogger>(true)); Assert.Null(container.ResolveOptionalKeyed<ILogger>(false)); } [Fact] public void ResolveOptionalNamedWorks() { var builder = new ContainerBuilder(); builder.RegisterType<Logger>().Named<ILogger>("A"); var container = builder.Build(); Assert.NotNull(container.ResolveOptionalNamed<ILogger>("A")); Assert.Null(container.ResolveOptionalNamed<ILogger>("B")); } [Fact] public void VerificationFailsWhenSingletonUsesTransient() { var builder = new ContainerBuilder(); builder.RegisterType<Logger>().As<ILogger>(); builder.RegisterType<ErrorHandler>().As<IErrorHandler>().SingleInstance(); Assert.Throws<BTDBException>(() => builder.BuildAndVerify()); } class Foo { internal TimeSpan? Bar; public Foo(TimeSpan? param) { Bar = param; } } [Fact] public void InjectNullableStructDoesNotCrash() { var builder = new ContainerBuilder(); TimeSpan? timeSpan = TimeSpan.FromHours(1); builder.RegisterInstance<TimeSpan?>(timeSpan); builder.RegisterType<Foo>(); var container = builder.Build(); Assert.Equal(TimeSpan.FromHours(1), container.Resolve<Foo>().Bar); } [Fact] public void InjectNullableStructWithoutValueDoesNotCrash() { var builder = new ContainerBuilder(); builder.RegisterInstance<TimeSpan?>(null!); builder.RegisterType<Foo>(); var container = builder.Build(); Assert.False(container.Resolve<Foo>().Bar.HasValue); } [Fact] public void InjectStructByFactory() { var builder = new ContainerBuilder(); builder.RegisterFactory(c => new Foo(TimeSpan.FromHours(1))); var container = builder.Build(); var foo = container.Resolve<Foo>(); Assert.Equal(TimeSpan.FromHours(1), foo.Bar); } [Fact] public void UniquenessOfRegistrationsCouldBeEnforced() { var builder = new ContainerBuilder(ContainerBuilderBehaviour.UniqueRegistrations); builder.RegisterType<Logger>().As<ILogger>(); builder.RegisterType<Logger>().As<ILogger>(); Assert.Throws<BTDBException>(() => builder.Build()); } [Fact] public void UniquenessOfRegistrationsCouldBeEnforcedConfiguredForEveryRegistration() { var builder = new ContainerBuilder(); builder.RegisterType<Logger>().As<ILogger>().UniqueRegistration(true); builder.RegisterType<Logger>().As<ILogger>().UniqueRegistration(true); Assert.Throws<BTDBException>(() => builder.Build()); } [Fact] public void UniquenessOfRegistrationsCouldBeOverriden() { var builder = new ContainerBuilder(ContainerBuilderBehaviour.UniqueRegistrations); builder.RegisterType<Logger>().As<ILogger>().UniqueRegistration(false); builder.RegisterType<Logger>().As<ILogger>().UniqueRegistration(false); builder.Build(); } }
#region Using Statements using System; using System.Collections.Generic; using System.Text; #endregion namespace JigLibX.Collision { #region public struct MaterialPairProperties /// <summary> /// Struct MaterialPairProperties /// </summary> public struct MaterialPairProperties { /// <summary> /// Restitution /// </summary> public float Restitution; /// <summary> /// Static Friction /// </summary> public float StaticFriction; /// <summary> /// Dynamic Friction /// </summary> public float DynamicFriction; /// <summary> /// Constructor /// </summary> /// <param name="r"></param> /// <param name="sf"></param> /// <param name="df"></param> public MaterialPairProperties(float r, float sf, float df) { this.Restitution = r; this.DynamicFriction = df; this.StaticFriction = sf; } } #endregion #region public struct MaterialProperties /// <summary> /// Struct MaterialProperties /// </summary> public struct MaterialProperties { /// <summary> /// Elasticity /// </summary> public float Elasticity; /// <summary> /// Static Roughness /// </summary> public float StaticRoughness; /// <summary> /// Dynamic Roughness /// </summary> public float DynamicRoughness; /// <summary> /// Constructor /// </summary> /// <param name="e"></param> /// <param name="sr"></param> /// <param name="dr"></param> public MaterialProperties(float e, float sr, float dr) { this.Elasticity = e; this.StaticRoughness = sr; this.DynamicRoughness = dr; } /// <summary> /// Gets new empty MaterialProperties /// </summary> public static MaterialProperties Unset { get { return new MaterialProperties(); } } } #endregion /// <summary> /// This handles the properties of interactions between different /// materials. /// </summary> public class MaterialTable { /// <summary> /// Some default materials that get added automatically User /// materials should start at NumMaterialTypes, or else /// ignore this and over-ride everything. User-refined values can /// get used so should not assume the values come form this enum - /// use MaterialID /// </summary> public enum MaterialID { /// <summary> /// Unset /// </summary> Unset, /// <summary> /// Individual values should be used/calculated at runtime /// </summary> UserDefined, /// <summary> /// NotBouncySmooth /// </summary> NotBouncySmooth, /// <summary> /// NotBouncyNormal /// </summary> NotBouncyNormal, /// <summary> /// NotBouncyRough /// </summary> NotBouncyRough, /// <summary> /// NormalSmooth /// </summary> NormalSmooth, /// <summary> /// NormalNormal /// </summary> NormalNormal, /// <summary> /// NormalRough /// </summary> NormalRough, /// <summary> /// BouncySmooth /// </summary> BouncySmooth, /// <summary> /// BouncyNormal /// </summary> BouncyNormal, /// <summary> /// BouncyRough /// </summary> BouncyRough, /// <summary> /// NumMaterialTypes /// </summary> NumMaterialTypes } private Dictionary<int, MaterialProperties> materials = new Dictionary<int, MaterialProperties>(); private Dictionary<int, MaterialPairProperties> materialPairs = new Dictionary<int, MaterialPairProperties>(); /// <summary> /// On construction all the default Materials get added /// </summary> public MaterialTable() { Reset(); } /// <summary> /// Clear everything except the default Materials /// </summary> public void Reset() { Clear(); float normalBouncy = 0.3f; float normalRoughS = 0.5f; float normalRoughD = 0.3f; float roughRoughS = 0.5f; float roughRoughD = 0.3f; SetMaterialProperties((int)MaterialID.Unset, new MaterialProperties(0.0f, 0.0f, 0.0f)); SetMaterialProperties((int)MaterialID.NotBouncySmooth, new MaterialProperties(0.0f, 0.0f, 0.0f)); SetMaterialProperties((int)MaterialID.NotBouncyNormal, new MaterialProperties(0.0f, normalRoughS, normalRoughD)); SetMaterialProperties((int)MaterialID.NotBouncyRough, new MaterialProperties(0.0f, roughRoughD, roughRoughD)); SetMaterialProperties((int)MaterialID.NormalSmooth, new MaterialProperties(normalBouncy, 0.0f, 1.0f)); SetMaterialProperties((int)MaterialID.NormalNormal, new MaterialProperties(normalBouncy, normalRoughS, normalRoughD)); SetMaterialProperties((int)MaterialID.NormalRough, new MaterialProperties(normalBouncy, roughRoughS, roughRoughD)); SetMaterialProperties((int)MaterialID.BouncySmooth, new MaterialProperties(1.0f, 0.0f, 0.0f)); SetMaterialProperties((int)MaterialID.BouncyNormal, new MaterialProperties(1.0f, normalRoughS, normalRoughD)); SetMaterialProperties((int)MaterialID.BouncyRough, new MaterialProperties(1.0f, roughRoughS, roughRoughD)); } /// <summary> /// Clear everything /// </summary> public void Clear() { materials.Clear(); materialPairs.Clear(); } /// <summary> /// This adds/overrides a material, and sets all the pairs for /// existing materials using some sensible heuristic /// </summary> /// <param name="id"></param> /// <param name="properties"></param> public void SetMaterialProperties(int id, MaterialProperties properties) { materials[id] = properties; foreach (KeyValuePair<int, MaterialProperties> it in materials) { int otherID = it.Key; MaterialProperties mat = it.Value; int key01 = otherID << 16 | id; int key10 = id << 16 | otherID; materialPairs[key01] = materialPairs[key10] = new MaterialPairProperties(properties.Elasticity * mat.Elasticity, properties.StaticRoughness * mat.StaticRoughness, properties.DynamicRoughness * mat.DynamicRoughness); } } /// <summary> /// Returns properties of a material - defaults on inelastic /// frictionless. /// </summary> /// <param name="id"></param> /// <returns>MaterialProperties</returns> public MaterialProperties GetMaterialProperties(int id) { return materials[id]; } /// <summary> /// Gets the properties for a pair of materials. Same result even /// if the two ids are swapped /// </summary> /// <param name="id1"></param> /// <param name="id2"></param> /// <returns>MaterialProperties</returns> public MaterialPairProperties GetPairProperties(int id1, int id2) { int key = id1 << 16 | id2; return materialPairs[key]; } /// <summary> /// This overrides the result for a single pair of materials. It's /// recommended that you add all materials first. Order of ids /// doesn't matter /// </summary> /// <param name="id1"></param> /// <param name="id2"></param> /// <param name="pairProperties"></param> public void SetMaterialPairProperties(int id1, int id2, MaterialPairProperties pairProperties) { int key01 = id1 << 16 | id2; int key10 = id2 << 16 | id1; materialPairs[key01] = materialPairs[key10] = pairProperties; } } }
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Reflection; using Newtonsoft.Json; using Signum.Engine.Basics; using Signum.Engine.Maps; using Signum.Entities; using Signum.Entities.Reflection; using Signum.Utilities; using Signum.Entities.DynamicQuery; using Signum.Utilities.ExpressionTrees; using Signum.Utilities.Reflection; using Signum.Engine.Operations; using Signum.Engine; using Signum.Entities.Basics; namespace Signum.React.Facades { public static class ReflectionServer { public static Func<object> GetContext = GetCurrentValidCulture; public static object GetCurrentValidCulture() { var ci = CultureInfo.CurrentCulture; while (ci != CultureInfo.InvariantCulture && !EntityAssemblies.Keys.Any(a => DescriptionManager.GetLocalizedAssembly(a, ci) != null)) ci = ci.Parent; return ci != CultureInfo.InvariantCulture ? ci : CultureInfo.GetCultureInfo("en"); } public static ConcurrentDictionary<object, Dictionary<string, TypeInfoTS>> cache = new ConcurrentDictionary<object, Dictionary<string, TypeInfoTS>>(); public static Dictionary<Assembly, HashSet<string>> EntityAssemblies = null!; public static ResetLazy<Dictionary<string, Type>> TypesByName = new ResetLazy<Dictionary<string, Type>>( () => GetTypes().Where(t => typeof(ModifiableEntity).IsAssignableFrom(t) || t.IsEnum && !t.Name.EndsWith("Query") && !t.Name.EndsWith("Message")) .ToDictionaryEx(GetTypeName, "Types")); public static Dictionary<string, Func<bool>> OverrideIsNamespaceAllowed = new Dictionary<string, Func<bool>>(); public static void RegisterLike(Type type, Func<bool> allowed) { TypesByName.Reset(); EntityAssemblies.GetOrCreate(type.Assembly).Add(type.Namespace!); OverrideIsNamespaceAllowed[type.Namespace!] = allowed; } internal static void Start() { DescriptionManager.Invalidated += () => cache.Clear(); Schema.Current.OnMetadataInvalidated += () => cache.Clear(); var mainTypes = Schema.Current.Tables.Keys; var mixins = mainTypes.SelectMany(t => MixinDeclarations.GetMixinDeclarations(t)); var operations = OperationLogic.RegisteredOperations.Select(o => o.FieldInfo.DeclaringType!); EntityAssemblies = mainTypes.Concat(mixins).Concat(operations).AgGroupToDictionary(t => t.Assembly, gr => gr.Select(a => a.Namespace!).ToHashSet()); EntityAssemblies[typeof(PaginationMode).Assembly].Add(typeof(PaginationMode).Namespace!); } const BindingFlags instanceFlags = BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly; const BindingFlags staticFlags = BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly; public static event Func<TypeInfoTS, Type, TypeInfoTS?>? TypeExtension; static TypeInfoTS? OnTypeExtension(TypeInfoTS ti, Type t) { foreach (var a in TypeExtension.GetInvocationListTyped()) { ti = a(ti, t)!; if (ti == null) return null; } return ti; } public static event Func<MemberInfoTS, PropertyRoute, MemberInfoTS?>? PropertyRouteExtension; static MemberInfoTS? OnPropertyRouteExtension(MemberInfoTS mi, PropertyRoute m) { if (PropertyRouteExtension == null) return mi; foreach (var a in PropertyRouteExtension.GetInvocationListTyped()) { mi = a(mi, m)!; if (mi == null) return null; } return mi; } public static event Func<MemberInfoTS, FieldInfo, MemberInfoTS?>? FieldInfoExtension; static MemberInfoTS? OnFieldInfoExtension(MemberInfoTS mi, FieldInfo m) { if (FieldInfoExtension == null) return mi; foreach (var a in FieldInfoExtension.GetInvocationListTyped()) { mi = a(mi, m)!; if (mi == null) return null; } return mi; } public static event Func<OperationInfoTS, OperationInfo, Type, OperationInfoTS?>? OperationExtension; static OperationInfoTS? OnOperationExtension(OperationInfoTS oi, OperationInfo o, Type type) { if (OperationExtension == null) return oi; foreach (var a in OperationExtension.GetInvocationListTyped()) { oi = a(oi, o, type)!; if (oi == null) return null; } return oi; } public static HashSet<Type> ExcludeTypes = new HashSet<Type>(); internal static Dictionary<string, TypeInfoTS> GetTypeInfoTS() { return cache.GetOrAdd(GetContext(), ci => { var result = new Dictionary<string, TypeInfoTS>(); var allTypes = GetTypes(); allTypes = allTypes.Except(ExcludeTypes).ToList(); result.AddRange(GetEntities(allTypes), "typeInfo"); result.AddRange(GetSymbolContainers(allTypes), "typeInfo"); result.AddRange(GetEnums(allTypes), "typeInfo"); return result; }); } public static List<Type> GetTypes() { return EntityAssemblies.SelectMany(kvp => { var normalTypes = kvp.Key.GetTypes().Where(t => kvp.Value.Contains(t.Namespace!)); var usedEnums = (from type in normalTypes where typeof(ModifiableEntity).IsAssignableFrom(type) from p in type.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly) let pt = (p.PropertyType.ElementType() ?? p.PropertyType).UnNullify() where pt.IsEnum && !EntityAssemblies.ContainsKey(pt.Assembly) select pt).ToList(); var importedTypes = kvp.Key.GetCustomAttributes<ImportInTypeScriptAttribute>().Where(a => kvp.Value.Contains(a.ForNamesace)).Select(a => a.Type); return normalTypes.Concat(importedTypes).Concat(usedEnums); }).Distinct().ToList(); } static MethodInfo miToString = ReflectionTools.GetMethodInfo((object o) => o.ToString()); public static Dictionary<string, TypeInfoTS> GetEntities(IEnumerable<Type> allTypes) { var models = (from type in allTypes where typeof(ModelEntity).IsAssignableFrom(type) && !type.IsAbstract select type).ToList(); var queries = QueryLogic.Queries; var schema = Schema.Current; var settings = Schema.Current.Settings; var result = (from type in TypeLogic.TypeToEntity.Keys.Concat(models) where !type.IsEnumEntity() && !ReflectionServer.ExcludeTypes.Contains(type) let descOptions = LocalizedAssembly.GetDescriptionOptions(type) let allOperations = !type.IsEntity() ? null : OperationLogic.GetAllOperationInfos(type) select KeyValuePair.Create(GetTypeName(type), OnTypeExtension(new TypeInfoTS { Kind = KindOfType.Entity, FullName = type.FullName!, NiceName = descOptions.HasFlag(DescriptionOptions.Description) ? type.NiceName() : null, NicePluralName = descOptions.HasFlag(DescriptionOptions.PluralDescription) ? type.NicePluralName() : null, Gender = descOptions.HasFlag(DescriptionOptions.Gender) ? type.GetGender().ToString() : null, EntityKind = type.IsIEntity() ? EntityKindCache.GetEntityKind(type) : (EntityKind?)null, EntityData = type.IsIEntity() ? EntityKindCache.GetEntityData(type) : (EntityData?)null, IsLowPopulation = type.IsIEntity() ? EntityKindCache.IsLowPopulation(type) : false, IsSystemVersioned = type.IsIEntity() ? schema.Table(type).SystemVersioned != null : false, ToStringFunction = typeof(Symbol).IsAssignableFrom(type) ? null : LambdaToJavascriptConverter.ToJavascript(ExpressionCleaner.GetFieldExpansion(type, miToString)!), QueryDefined = queries.QueryDefined(type), Members = PropertyRoute.GenerateRoutes(type) .Where(pr => InTypeScript(pr)) .Select(p => { var validators = Validator.TryGetPropertyValidator(p)?.Validators; var mi = new MemberInfoTS { NiceName = p.PropertyInfo!.NiceName(), TypeNiceName = GetTypeNiceName(p.PropertyInfo!.PropertyType), Format = p.PropertyRouteType == PropertyRouteType.FieldOrProperty ? Reflector.FormatString(p) : null, IsReadOnly = !IsId(p) && (p.PropertyInfo?.IsReadOnly() ?? false), Required = !IsId(p) && ((p.Type.IsValueType && !p.Type.IsNullable()) || (validators?.Any(v => !v.DisabledInModelBinder && (!p.Type.IsMList() ? (v is NotNullValidatorAttribute) : (v is CountIsValidatorAttribute c && c.IsGreaterThanZero))) ?? false)), Unit = UnitAttribute.GetTranslation(p.PropertyInfo?.GetCustomAttribute<UnitAttribute>()?.UnitName), Type = new TypeReferenceTS(IsId(p) ? PrimaryKey.Type(type).Nullify() : p.PropertyInfo!.PropertyType, p.Type.IsMList() ? p.Add("Item").TryGetImplementations() : p.TryGetImplementations()), IsMultiline = validators?.OfType<StringLengthValidatorAttribute>().FirstOrDefault()?.MultiLine ?? false, IsVirtualMList = p.IsVirtualMList(), MaxLength = validators?.OfType<StringLengthValidatorAttribute>().FirstOrDefault()?.Max.DefaultToNull(-1), PreserveOrder = settings.FieldAttributes(p)?.OfType<PreserveOrderAttribute>().Any() ?? false, }; return KeyValuePair.Create(p.PropertyString(), OnPropertyRouteExtension(mi, p)!); }) .Where(kvp => kvp.Value != null) .ToDictionaryEx("properties"), HasConstructorOperation = allOperations != null && allOperations.Any(oi => oi.OperationType == OperationType.Constructor), Operations = allOperations == null ? null : allOperations.Select(oi => KeyValuePair.Create(oi.OperationSymbol.Key, OnOperationExtension(new OperationInfoTS(oi), oi, type)!)).Where(kvp => kvp.Value != null).ToDictionaryEx("operations"), RequiresEntityPack = allOperations != null && allOperations.Any(oi => oi.HasCanExecute != null), }, type))) .Where(kvp => kvp.Value != null) .ToDictionaryEx("entities"); return result; } public static bool InTypeScript(PropertyRoute pr) { return (pr.Parent == null || InTypeScript(pr.Parent)) && (pr.PropertyInfo == null || (pr.PropertyInfo.GetCustomAttribute<InTypeScriptAttribute>()?.GetInTypeScript() ?? !IsExpression(pr.Parent!.Type, pr.PropertyInfo))); } private static bool IsExpression(Type type, PropertyInfo propertyInfo) { return propertyInfo.SetMethod == null && ExpressionCleaner.HasExpansions(type, propertyInfo); } static string? GetTypeNiceName(Type type) { if (type.IsModifiableEntity() && !type.IsEntity()) return type.NiceName(); return null; } public static bool IsId(PropertyRoute p) { return p.PropertyRouteType == PropertyRouteType.FieldOrProperty && p.PropertyInfo!.Name == nameof(Entity.Id) && p.Parent!.PropertyRouteType == PropertyRouteType.Root; } public static Dictionary<string, TypeInfoTS> GetEnums(IEnumerable<Type> allTypes) { var queries = QueryLogic.Queries; var result = (from type in allTypes where type.IsEnum let descOptions = LocalizedAssembly.GetDescriptionOptions(type) where descOptions != DescriptionOptions.None let kind = type.Name.EndsWith("Query") ? KindOfType.Query : type.Name.EndsWith("Message") ? KindOfType.Message : KindOfType.Enum select KeyValuePair.Create(GetTypeName(type), OnTypeExtension(new TypeInfoTS { Kind = kind, FullName = type.FullName!, NiceName = descOptions.HasFlag(DescriptionOptions.Description) ? type.NiceName() : null, Members = type.GetFields(staticFlags) .Where(fi => kind != KindOfType.Query || queries.QueryDefined(fi.GetValue(null)!)) .Select(fi => KeyValuePair.Create(fi.Name, OnFieldInfoExtension(new MemberInfoTS { NiceName = fi.NiceName(), IsIgnoredEnum = kind == KindOfType.Enum && fi.HasAttribute<IgnoreAttribute>() }, fi)!)) .Where(a=>a.Value != null) .ToDictionaryEx("query"), }, type))) .Where(a => a.Value != null) .ToDictionaryEx("enums"); return result; } public static Dictionary<string, TypeInfoTS> GetSymbolContainers(IEnumerable<Type> allTypes) { SymbolLogic.LoadAll(); var result = (from type in allTypes where type.IsStaticClass() && type.HasAttribute<AutoInitAttribute>() select KeyValuePair.Create(GetTypeName(type), OnTypeExtension(new TypeInfoTS { Kind = KindOfType.SymbolContainer, FullName = type.FullName!, Members = type.GetFields(staticFlags) .Select(f => GetSymbolInfo(f)) .Where(s => s.FieldInfo != null && /*Duplicated like in Dynamic*/ s.IdOrNull.HasValue /*Not registered*/) .Select(s => KeyValuePair.Create(s.FieldInfo.Name, OnFieldInfoExtension(new MemberInfoTS { NiceName = s.FieldInfo.NiceName(), Id = s.IdOrNull!.Value.Object }, s.FieldInfo)!)) .Where(a => a.Value != null) .ToDictionaryEx("fields"), }, type))) .Where(a => a.Value != null && a.Value.Members.Any()) .ToDictionaryEx("symbols"); return result; } private static (FieldInfo FieldInfo, PrimaryKey? IdOrNull) GetSymbolInfo(FieldInfo m) { object? v = m.GetValue(null); if (v is IOperationSymbolContainer osc) v = osc.Symbol; if (v is Symbol s) return (s.FieldInfo, s.IdOrNull); if(v is SemiSymbol semiS) return (semiS.FieldInfo!, semiS.IdOrNull); throw new InvalidOperationException(); } public static string GetTypeName(Type t) { if (typeof(ModifiableEntity).IsAssignableFrom(t)) return TypeLogic.TryGetCleanName(t) ?? t.Name; return t.Name; } } public class TypeInfoTS { [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "kind")] public KindOfType Kind { get; set; } [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "fullName")] public string FullName { get; set; } = null!; [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "niceName")] public string? NiceName { get; set; } [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "nicePluralName")] public string? NicePluralName { get; set; } [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "gender")] public string? Gender { get; set; } [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "entityKind")] public EntityKind? EntityKind { get; set; } [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "entityData")] public EntityData? EntityData { get; set; } [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore, PropertyName = "isLowPopulation")] public bool IsLowPopulation { get; set; } [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore, PropertyName = "isSystemVersioned")] public bool IsSystemVersioned { get; set; } [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "toStringFunction")] public string? ToStringFunction { get; set; } [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore, PropertyName = "queryDefined")] public bool QueryDefined { get; set; } [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "members")] public Dictionary<string, MemberInfoTS> Members { get; set; } = null!; [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore, PropertyName = "hasConstructorOperation")] public bool HasConstructorOperation { get; set; } [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "operations")] public Dictionary<string, OperationInfoTS>? Operations { get; set; } [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore, PropertyName = "requiresEntityPack")] public bool RequiresEntityPack { get; set; } [JsonExtensionData] public Dictionary<string, object> Extension { get; set; } = new Dictionary<string, object>(); public override string ToString() => $"{Kind} {NiceName} {EntityKind} {EntityData}"; } public class MemberInfoTS { [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "type")] public TypeReferenceTS? Type { get; set; } [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "niceName")] public string? NiceName { get; set; } [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "typeNiceName")] public string? TypeNiceName { get; set; } [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore, PropertyName = "isReadOnly")] public bool IsReadOnly { get; set; } [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore, PropertyName = "required")] public bool Required { get; set; } [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "unit")] public string? Unit { get; set; } [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "format")] public string? Format { get; set; } [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore, PropertyName = "isIgnoredEnum")] public bool IsIgnoredEnum { get; set; } [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore, PropertyName = "isVirtualMList")] public bool IsVirtualMList { get; set; } [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "maxLength")] public int? MaxLength { get; set; } [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore, PropertyName = "isMultiline")] public bool IsMultiline { get; set; } [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore, PropertyName = "preserveOrder")] public bool PreserveOrder { get; internal set; } [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "id")] public object? Id { get; set; } [JsonExtensionData] public Dictionary<string, object> Extension { get; set; } = new Dictionary<string, object>(); } public class OperationInfoTS { [JsonProperty(PropertyName = "operationType")] private OperationType OperationType; [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore, NullValueHandling = NullValueHandling.Ignore, PropertyName = "canBeNew")] private bool? CanBeNew; [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore, NullValueHandling = NullValueHandling.Ignore, PropertyName = "hasCanExecute")] private bool? HasCanExecute; [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore, NullValueHandling = NullValueHandling.Ignore, PropertyName = "hasStates")] private bool? HasStates; [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore, NullValueHandling = NullValueHandling.Ignore, PropertyName = "canBeModified")] private bool? CanBeModified; [JsonExtensionData] public Dictionary<string, object> Extension { get; set; } = new Dictionary<string, object>(); public OperationInfoTS(OperationInfo oper) { this.CanBeNew = oper.CanBeNew; this.HasCanExecute = oper.HasCanExecute; this.HasStates = oper.HasStates; this.OperationType = oper.OperationType; this.CanBeModified = oper.CanBeModified; } } public class TypeReferenceTS { [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore, PropertyName = "isCollection")] public bool IsCollection { get; set; } [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore, PropertyName = "isLite")] public bool IsLite { get; set; } [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore, PropertyName = "isNotNullable")] public bool IsNotNullable { get; set; } [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore, PropertyName = "isEmbedded")] public bool IsEmbedded { get; set; } [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "name")] public string Name { get; set; } [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "typeNiceName")] public string? TypeNiceName { get; set; } #pragma warning disable CS8618 // Non-nullable field is uninitialized. public TypeReferenceTS() { } #pragma warning restore CS8618 // Non-nullable field is uninitialized. public TypeReferenceTS(Type type, Implementations? implementations) { this.IsCollection = type != typeof(string) && type != typeof(byte[]) && type.ElementType() != null; var clean = type == typeof(string) ? type : (type.ElementType() ?? type); this.IsLite = clean.IsLite(); this.IsNotNullable = clean.IsValueType && !clean.IsNullable(); this.IsEmbedded = clean.IsEmbeddedEntity(); if (this.IsEmbedded && !this.IsCollection) this.TypeNiceName = type.NiceName(); if(implementations != null) { try { this.Name = implementations.Value.Key(); } catch (Exception) when (StartParameters.IgnoredCodeErrors != null) { this.Name = "ERROR"; } }else { this.Name = TypeScriptType(type); } } private static string TypeScriptType(Type type) { type = CleanMList(type); type = type.UnNullify().CleanType(); return BasicType(type) ?? ReflectionServer.GetTypeName(type) ?? "any"; } private static Type CleanMList(Type type) { if (type.IsMList()) type = type.ElementType()!; return type; } public static string? BasicType(Type type) { if (type.IsEnum) return null; switch (Type.GetTypeCode(type)) { case TypeCode.Boolean: return "boolean"; case TypeCode.Char: return "string"; case TypeCode.SByte: case TypeCode.Byte: case TypeCode.Int16: case TypeCode.UInt16: case TypeCode.Int32: case TypeCode.UInt32: case TypeCode.Int64: case TypeCode.UInt64: return "number"; case TypeCode.Single: case TypeCode.Double: case TypeCode.Decimal: return "decimal"; case TypeCode.DateTime: return "datetime"; case TypeCode.String: return "string"; } return null; } } public enum KindOfType { Entity, Enum, Message, Query, SymbolContainer, } }
using System; using System.CodeDom.Compiler; using System.Collections.Generic; using System.ComponentModel; using System.Runtime.Serialization; using Microsoft.Xrm.Sdk; namespace PowerShellLibrary.Crm.CmdletProviders { [DataContract] [Microsoft.Xrm.Sdk.Client.EntityLogicalName("incidentresolution")] [GeneratedCode("CrmSvcUtil", "7.1.0001.3108")] public class IncidentResolution : Entity, INotifyPropertyChanging, INotifyPropertyChanged { public const string EntityLogicalName = "incidentresolution"; public const int EntityTypeCode = 4206; [AttributeLogicalName("activityid")] public Guid? ActivityId { get { return this.GetAttributeValue<Guid?>("activityid"); } set { this.OnPropertyChanging("ActivityId"); this.SetAttributeValue("activityid", (object) value); if (value.HasValue) base.Id = value.Value; else base.Id = Guid.Empty; this.OnPropertyChanged("ActivityId"); } } [AttributeLogicalName("activityid")] public override Guid Id { get { return base.Id; } set { this.ActivityId = new Guid?(value); } } [AttributeLogicalName("activitytypecode")] public string ActivityTypeCode { get { return this.GetAttributeValue<string>("activitytypecode"); } } [AttributeLogicalName("actualdurationminutes")] public int? ActualDurationMinutes { get { return this.GetAttributeValue<int?>("actualdurationminutes"); } set { this.OnPropertyChanging("ActualDurationMinutes"); this.SetAttributeValue("actualdurationminutes", (object) value); this.OnPropertyChanged("ActualDurationMinutes"); } } [AttributeLogicalName("actualend")] public DateTime? ActualEnd { get { return this.GetAttributeValue<DateTime?>("actualend"); } set { this.OnPropertyChanging("ActualEnd"); this.SetAttributeValue("actualend", (object) value); this.OnPropertyChanged("ActualEnd"); } } [AttributeLogicalName("actualstart")] public DateTime? ActualStart { get { return this.GetAttributeValue<DateTime?>("actualstart"); } set { this.OnPropertyChanging("ActualStart"); this.SetAttributeValue("actualstart", (object) value); this.OnPropertyChanged("ActualStart"); } } [AttributeLogicalName("category")] public string Category { get { return this.GetAttributeValue<string>("category"); } set { this.OnPropertyChanging("Category"); this.SetAttributeValue("category", (object) value); this.OnPropertyChanged("Category"); } } [AttributeLogicalName("createdby")] public EntityReference CreatedBy { get { return this.GetAttributeValue<EntityReference>("createdby"); } } [AttributeLogicalName("createdbyexternalparty")] public EntityReference CreatedByExternalParty { get { return this.GetAttributeValue<EntityReference>("createdbyexternalparty"); } } [AttributeLogicalName("createdon")] public DateTime? CreatedOn { get { return this.GetAttributeValue<DateTime?>("createdon"); } } [AttributeLogicalName("createdonbehalfby")] public EntityReference CreatedOnBehalfBy { get { return this.GetAttributeValue<EntityReference>("createdonbehalfby"); } } [AttributeLogicalName("description")] public string Description { get { return this.GetAttributeValue<string>("description"); } set { this.OnPropertyChanging("Description"); this.SetAttributeValue("description", (object) value); this.OnPropertyChanged("Description"); } } [AttributeLogicalName("importsequencenumber")] public int? ImportSequenceNumber { get { return this.GetAttributeValue<int?>("importsequencenumber"); } set { this.OnPropertyChanging("ImportSequenceNumber"); this.SetAttributeValue("importsequencenumber", (object) value); this.OnPropertyChanged("ImportSequenceNumber"); } } [AttributeLogicalName("incidentid")] public EntityReference IncidentId { get { return this.GetAttributeValue<EntityReference>("incidentid"); } set { this.OnPropertyChanging("IncidentId"); this.SetAttributeValue("incidentid", (object) value); this.OnPropertyChanged("IncidentId"); } } [AttributeLogicalName("isbilled")] public bool? IsBilled { get { return this.GetAttributeValue<bool?>("isbilled"); } set { this.OnPropertyChanging("IsBilled"); this.SetAttributeValue("isbilled", (object) value); this.OnPropertyChanged("IsBilled"); } } [AttributeLogicalName("isregularactivity")] public bool? IsRegularActivity { get { return this.GetAttributeValue<bool?>("isregularactivity"); } } [AttributeLogicalName("isworkflowcreated")] public bool? IsWorkflowCreated { get { return this.GetAttributeValue<bool?>("isworkflowcreated"); } set { this.OnPropertyChanging("IsWorkflowCreated"); this.SetAttributeValue("isworkflowcreated", (object) value); this.OnPropertyChanged("IsWorkflowCreated"); } } [AttributeLogicalName("modifiedby")] public EntityReference ModifiedBy { get { return this.GetAttributeValue<EntityReference>("modifiedby"); } } [AttributeLogicalName("modifiedbyexternalparty")] public EntityReference ModifiedByExternalParty { get { return this.GetAttributeValue<EntityReference>("modifiedbyexternalparty"); } } [AttributeLogicalName("modifiedon")] public DateTime? ModifiedOn { get { return this.GetAttributeValue<DateTime?>("modifiedon"); } } [AttributeLogicalName("modifiedonbehalfby")] public EntityReference ModifiedOnBehalfBy { get { return this.GetAttributeValue<EntityReference>("modifiedonbehalfby"); } } [AttributeLogicalName("overriddencreatedon")] public DateTime? OverriddenCreatedOn { get { return this.GetAttributeValue<DateTime?>("overriddencreatedon"); } set { this.OnPropertyChanging("OverriddenCreatedOn"); this.SetAttributeValue("overriddencreatedon", (object) value); this.OnPropertyChanged("OverriddenCreatedOn"); } } [AttributeLogicalName("ownerid")] public EntityReference OwnerId { get { return this.GetAttributeValue<EntityReference>("ownerid"); } set { this.OnPropertyChanging("OwnerId"); this.SetAttributeValue("ownerid", (object) value); this.OnPropertyChanged("OwnerId"); } } [AttributeLogicalName("owningbusinessunit")] public EntityReference OwningBusinessUnit { get { return this.GetAttributeValue<EntityReference>("owningbusinessunit"); } } [AttributeLogicalName("owningteam")] public EntityReference OwningTeam { get { return this.GetAttributeValue<EntityReference>("owningteam"); } } [AttributeLogicalName("owninguser")] public EntityReference OwningUser { get { return this.GetAttributeValue<EntityReference>("owninguser"); } } [AttributeLogicalName("scheduleddurationminutes")] public int? ScheduledDurationMinutes { get { return this.GetAttributeValue<int?>("scheduleddurationminutes"); } } [AttributeLogicalName("scheduledend")] public DateTime? ScheduledEnd { get { return this.GetAttributeValue<DateTime?>("scheduledend"); } set { this.OnPropertyChanging("ScheduledEnd"); this.SetAttributeValue("scheduledend", (object) value); this.OnPropertyChanged("ScheduledEnd"); } } [AttributeLogicalName("scheduledstart")] public DateTime? ScheduledStart { get { return this.GetAttributeValue<DateTime?>("scheduledstart"); } set { this.OnPropertyChanging("ScheduledStart"); this.SetAttributeValue("scheduledstart", (object) value); this.OnPropertyChanged("ScheduledStart"); } } [AttributeLogicalName("serviceid")] public EntityReference ServiceId { get { return this.GetAttributeValue<EntityReference>("serviceid"); } set { this.OnPropertyChanging("ServiceId"); this.SetAttributeValue("serviceid", (object) value); this.OnPropertyChanged("ServiceId"); } } [AttributeLogicalName("statecode")] public IncidentResolutionState? StateCode { get { OptionSetValue attributeValue = this.GetAttributeValue<OptionSetValue>("statecode"); if (attributeValue != null) return new IncidentResolutionState?((IncidentResolutionState) Enum.ToObject(typeof (IncidentResolutionState), attributeValue.Value)); return new IncidentResolutionState?(); } set { this.OnPropertyChanging("StateCode"); if (!value.HasValue) this.SetAttributeValue("statecode", (object) null); else this.SetAttributeValue("statecode", (object) new OptionSetValue((int) value.Value)); this.OnPropertyChanged("StateCode"); } } [AttributeLogicalName("statuscode")] public OptionSetValue StatusCode { get { return this.GetAttributeValue<OptionSetValue>("statuscode"); } set { this.OnPropertyChanging("StatusCode"); this.SetAttributeValue("statuscode", (object) value); this.OnPropertyChanged("StatusCode"); } } [AttributeLogicalName("subcategory")] public string Subcategory { get { return this.GetAttributeValue<string>("subcategory"); } set { this.OnPropertyChanging("Subcategory"); this.SetAttributeValue("subcategory", (object) value); this.OnPropertyChanged("Subcategory"); } } [AttributeLogicalName("subject")] public string Subject { get { return this.GetAttributeValue<string>("subject"); } set { this.OnPropertyChanging("Subject"); this.SetAttributeValue("subject", (object) value); this.OnPropertyChanged("Subject"); } } [AttributeLogicalName("timespent")] public int? TimeSpent { get { return this.GetAttributeValue<int?>("timespent"); } set { this.OnPropertyChanging("TimeSpent"); this.SetAttributeValue("timespent", (object) value); this.OnPropertyChanged("TimeSpent"); } } [AttributeLogicalName("timezoneruleversionnumber")] public int? TimeZoneRuleVersionNumber { get { return this.GetAttributeValue<int?>("timezoneruleversionnumber"); } set { this.OnPropertyChanging("TimeZoneRuleVersionNumber"); this.SetAttributeValue("timezoneruleversionnumber", (object) value); this.OnPropertyChanged("TimeZoneRuleVersionNumber"); } } [AttributeLogicalName("utcconversiontimezonecode")] public int? UTCConversionTimeZoneCode { get { return this.GetAttributeValue<int?>("utcconversiontimezonecode"); } set { this.OnPropertyChanging("UTCConversionTimeZoneCode"); this.SetAttributeValue("utcconversiontimezonecode", (object) value); this.OnPropertyChanged("UTCConversionTimeZoneCode"); } } [AttributeLogicalName("versionnumber")] public long? VersionNumber { get { return this.GetAttributeValue<long?>("versionnumber"); } } [RelationshipSchemaName("IncidentResolution_AsyncOperations")] public IEnumerable<AsyncOperation> IncidentResolution_AsyncOperations { get { return this.GetRelatedEntities<AsyncOperation>("IncidentResolution_AsyncOperations", new EntityRole?()); } set { this.OnPropertyChanging("IncidentResolution_AsyncOperations"); this.SetRelatedEntities<AsyncOperation>("IncidentResolution_AsyncOperations", new EntityRole?(), value); this.OnPropertyChanged("IncidentResolution_AsyncOperations"); } } [RelationshipSchemaName("business_unit_incident_resolution_activities")] [AttributeLogicalName("owningbusinessunit")] public BusinessUnit business_unit_incident_resolution_activities { get { return this.GetRelatedEntity<BusinessUnit>("business_unit_incident_resolution_activities", new EntityRole?()); } } [RelationshipSchemaName("lk_incidentresolution_createdby")] [AttributeLogicalName("createdby")] public SystemUser lk_incidentresolution_createdby { get { return this.GetRelatedEntity<SystemUser>("lk_incidentresolution_createdby", new EntityRole?()); } } [RelationshipSchemaName("lk_incidentresolution_createdonbehalfby")] [AttributeLogicalName("createdonbehalfby")] public SystemUser lk_incidentresolution_createdonbehalfby { get { return this.GetRelatedEntity<SystemUser>("lk_incidentresolution_createdonbehalfby", new EntityRole?()); } } [AttributeLogicalName("modifiedby")] [RelationshipSchemaName("lk_incidentresolution_modifiedby")] public SystemUser lk_incidentresolution_modifiedby { get { return this.GetRelatedEntity<SystemUser>("lk_incidentresolution_modifiedby", new EntityRole?()); } } [AttributeLogicalName("modifiedonbehalfby")] [RelationshipSchemaName("lk_incidentresolution_modifiedonbehalfby")] public SystemUser lk_incidentresolution_modifiedonbehalfby { get { return this.GetRelatedEntity<SystemUser>("lk_incidentresolution_modifiedonbehalfby", new EntityRole?()); } } [RelationshipSchemaName("user_incidentresolution")] [AttributeLogicalName("owninguser")] public SystemUser user_incidentresolution { get { return this.GetRelatedEntity<SystemUser>("user_incidentresolution", new EntityRole?()); } } public event PropertyChangedEventHandler PropertyChanged; public event PropertyChangingEventHandler PropertyChanging; public IncidentResolution() : base("incidentresolution") { } private void OnPropertyChanged(string propertyName) { if (this.PropertyChanged == null) return; this.PropertyChanged((object) this, new PropertyChangedEventArgs(propertyName)); } private void OnPropertyChanging(string propertyName) { if (this.PropertyChanging == null) return; this.PropertyChanging((object) this, new PropertyChangingEventArgs(propertyName)); } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the MIT license. See License.txt in the project root for license information. using System; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Testing; using Test.Utilities; using Xunit; using VerifyCS = Test.Utilities.CSharpCodeFixVerifier< Microsoft.CodeQuality.Analyzers.QualityGuidelines.RethrowToPreserveStackDetailsAnalyzer, Microsoft.CodeAnalysis.Testing.EmptyCodeFixProvider>; using VerifyVB = Test.Utilities.VisualBasicCodeFixVerifier< Microsoft.CodeQuality.Analyzers.QualityGuidelines.RethrowToPreserveStackDetailsAnalyzer, Microsoft.CodeAnalysis.Testing.EmptyCodeFixProvider>; namespace Microsoft.CodeQuality.Analyzers.QualityGuidelines.UnitTests { public class RethrowToPreserveStackDetailsTests { [Fact] public async Task CA2200_NoDiagnosticsForRethrowAsync() { await VerifyCS.VerifyAnalyzerAsync(@" using System; class Program { void CatchAndRethrowImplicitly() { try { throw new ArithmeticException(); } catch (ArithmeticException e) { throw; } } } "); await VerifyVB.VerifyAnalyzerAsync(@" Imports System Class Program Sub CatchAndRethrowExplicitly() Try Throw New ArithmeticException() Catch ex As Exception Throw End Try End Sub End Class "); } [Fact] public async Task CA2200_NoDiagnosticsForThrowAnotherExceptionAsync() { await VerifyCS.VerifyAnalyzerAsync(@" using System; class Program { void CatchAndRethrowExplicitly() { try { throw new ArithmeticException(); throw new Exception(); } catch (ArithmeticException e) { var i = new Exception(); throw i; } } } "); await VerifyVB.VerifyAnalyzerAsync(@" Imports System Class Program Sub CatchAndRethrowExplicitly() Try Throw New ArithmeticException() Throw New Exception() Catch ex As Exception Dim i As New Exception() Throw i End Try End Sub End Class "); } [Fact] [WorkItem(4280, "https://github.com/dotnet/roslyn-analyzers/issues/4280")] public async Task CA2200_NoDiagnosticsForThrowAnotherExceptionInWhenClauseAsync() { await VerifyCS.VerifyAnalyzerAsync(@" using System; public abstract class C { public void M() { try { } catch (Exception ex) when (Map(ex, out Exception mappedEx)) { throw mappedEx; } } protected abstract bool Map(Exception ex, out Exception ex2); } "); } [Fact] [WorkItem(4280, "https://github.com/dotnet/roslyn-analyzers/issues/4280")] public async Task CA2200_NoDiagnosticsForThrowAnotherExceptionInWhenClauseWithoutVariableDeclaratorAsync() { await VerifyCS.VerifyAnalyzerAsync(@" using System; public abstract class C { public void M() { try { } catch (Exception) when (Map(out Exception ex)) { throw ex; } } protected abstract bool Map(out Exception ex); } "); } [Fact] public async Task CA2200_DiagnosticForThrowCaughtExceptionAsync() { await VerifyCS.VerifyAnalyzerAsync(@" using System; class Program { void CatchAndRethrowExplicitly() { try { ThrowException(); } catch (ArithmeticException e) { [|throw e;|] } } void ThrowException() { throw new ArithmeticException(); } } "); await VerifyVB.VerifyAnalyzerAsync(@" Imports System Class Program Sub CatchAndRethrowExplicitly() Try Throw New ArithmeticException() Catch e As ArithmeticException [|Throw e|] End Try End Sub End Class "); } [Fact] public async Task CA2200_NoDiagnosticsForThrowCaughtReassignedExceptionAsync() { await VerifyCS.VerifyAnalyzerAsync(@" using System; class Program { void CatchAndRethrowExplicitlyReassigned() { try { ThrowException(); } catch (SystemException e) { e = new ArithmeticException(); throw e; } } void ThrowException() { throw new SystemException(); } } "); await VerifyVB.VerifyAnalyzerAsync(@" Imports System Class Program Sub CatchAndRethrowExplicitly() Try Throw New Exception() Catch e As Exception e = New ArithmeticException() Throw e End Try End Sub End Class "); } [Fact] public async Task CA2200_NoDiagnosticsForEmptyBlockAsync() { await VerifyCS.VerifyAnalyzerAsync(@" using System; class Program { void CatchAndRethrowExplicitlyReassigned() { try { ThrowException(); } catch (SystemException e) { } } void ThrowException() { throw new SystemException(); } } "); await VerifyVB.VerifyAnalyzerAsync(@" Imports System Class Program Sub CatchAndRethrowExplicitly() Try Throw New Exception() Catch e As Exception End Try End Sub End Class "); } [Fact] public async Task CA2200_NoDiagnosticsForThrowCaughtExceptionInAnotherScopeAsync() { await VerifyCS.VerifyAnalyzerAsync(@" using System; class Program { void CatchAndRethrowExplicitly() { try { ThrowException(); } catch (ArithmeticException e) { [|throw e;|] } } void ThrowException() { throw new ArithmeticException(); } } "); } [Fact] public async Task CA2200_SingleDiagnosticForThrowCaughtExceptionInSpecificScopeAsync() { await VerifyVB.VerifyAnalyzerAsync(@" Imports System Class Program Sub CatchAndRethrowExplicitly() Try Throw New ArithmeticException() Catch e As ArithmeticException [|Throw e|] Catch e As Exception [|Throw e|] End Try End Sub End Class "); } [Fact] public async Task CA2200_MultipleDiagnosticsForThrowCaughtExceptionAtMultiplePlacesAsync() { await VerifyCS.VerifyAnalyzerAsync(@" using System; class Program { void CatchAndRethrowExplicitly() { try { ThrowException(); } catch (ArithmeticException e) { [|throw e;|] } catch (Exception e) { [|throw e;|] } } void ThrowException() { throw new ArithmeticException(); } } "); await VerifyVB.VerifyAnalyzerAsync(@" Imports System Class Program Sub CatchAndRethrowExplicitly() Try Throw New ArithmeticException() Catch e As ArithmeticException [|Throw e|] Catch e As Exception [|Throw e|] End Try End Sub End Class "); } [Fact] public async Task CA2200_NoDiagnosticForThrowOuterCaughtExceptionAsync() { await VerifyCS.VerifyAnalyzerAsync(@" using System; class Program { void CatchAndRethrowExplicitly() { try { throw new ArithmeticException(); } catch (ArithmeticException e) { try { throw new ArithmeticException(); } catch (ArithmeticException i) { throw e; } } } } "); await VerifyVB.VerifyAnalyzerAsync(@" Imports System Class Program Sub CatchAndRethrowExplicitly() Try Throw New ArithmeticException() Catch e As ArithmeticException Try Throw New ArithmeticException() Catch ex As Exception Throw e End Try End Try End Sub End Class "); } [Fact] public async Task CA2200_NoDiagnosticsForNestingWithCompileErrorsAsync() { await VerifyCS.VerifyAnalyzerAsync(@" using System; class Program { void CatchAndRethrowExplicitly() { try { try { throw new ArithmeticException(); } catch (ArithmeticException e) { throw; } catch ({|CS0160:ArithmeticException|}) { try { throw new ArithmeticException(); } catch (ArithmeticException i) { throw {|CS0103:e|}; } } } catch (Exception e) { throw; } } } "); await VerifyVB.VerifyAnalyzerAsync(@" Imports System Class Program Sub CatchAndRethrowExplicitly() Try Try Throw New ArithmeticException() Catch ex As ArithmeticException Throw Catch i As ArithmeticException Try Throw New ArithmeticException() Catch e As Exception Throw {|BC30451:ex|} End Try End Try Catch ex As Exception Throw End Try End Sub End Class "); } [Fact] public async Task CA2200_NoDiagnosticsForCatchWithoutIdentifierAsync() { await VerifyCS.VerifyAnalyzerAsync(@" using System; class Program { void CatchAndRethrow(Exception exception) { try { } catch (Exception) { var finalException = new InvalidOperationException(""aaa"", exception); throw finalException; } } } "); } [Fact] [WorkItem(2167, "https://github.com/dotnet/roslyn-analyzers/issues/2167")] public async Task CA2200_NoDiagnosticsForCatchWithoutArgumentAsync() { await VerifyCS.VerifyAnalyzerAsync(@" using System; class Program { void CatchAndRethrow(Exception exception) { try { } catch { var finalException = new InvalidOperationException(""aaa"", exception); throw finalException; } } } "); await VerifyVB.VerifyAnalyzerAsync(@" Imports System Class Program Sub CatchAndRethrow(exception As Exception) Try Catch Dim finalException = new InvalidOperationException(""aaa"", exception) Throw finalException End Try End Sub End Class "); } [Fact] public async Task CA2200_DiagnosticsForThrowCaughtExceptionInLocalMethodAsync() { await VerifyCS.VerifyAnalyzerAsync(@" using System; class Program { void CatchAndRethrowExplicitly() { try { } catch (Exception e) { DoThrow(); void DoThrow() { throw e; } } } } "); } [Fact] public async Task CA2200_NoDiagnosticsForThrowCaughtExceptionInLocalMethodAfterReassignmentAsync() { await VerifyCS.VerifyAnalyzerAsync(@" using System; class Program { void CatchAndRethrowExplicitly() { try { } catch (Exception e) { e = new ArgumentException(); DoThrow(); void DoThrow() { throw e; // This should not fire. } } } } "); } [Fact] public async Task CA2200_NoDiagnosticsForThrowCaughtExceptionInActionOrFuncAsync() { await VerifyCS.VerifyAnalyzerAsync(@" using System; class Program { void CatchAndRethrowExplicitly() { try { } catch (Exception e) { Action DoThrowAction = () => { throw e; }; Func<int> DoThrowFunc = () => { throw e; }; DoThrowAction(); var result = DoThrowFunc(); } } } "); } [Fact] public async Task CA2200_NoDiagnosticsForThrowVariableAsync() { await VerifyCS.VerifyAnalyzerAsync(@" using System; class Program { void M() { var e = new ArithmeticException(); throw e; } } "); await VerifyVB.VerifyAnalyzerAsync(@" Imports System Class Program Sub M() Dim e = New ArithmeticException() Throw e End Sub End Class "); } } }
#pragma warning disable 1591 using System; namespace Braintree { public enum ValidationErrorCode { GOOGLE_WALLET_CARD_EXPIRATION_MONTH_IS_REQUIRED = 83701, GOOGLE_WALLET_CARD_EXPIRATION_YEAR_IS_REQUIRED = 83702, GOOGLE_WALLET_CARD_NUMBER_IS_REQUIRED = 83703, GOOGLE_WALLET_CARD_NUMBER_IS_INVALID = 83704, GOOGLE_WALLET_CARD_GOOGLE_TRANSACTION_ID_IS_REQUIRED = 83705, GOOGLE_WALLET_CARD_SOURCE_CARD_TYPE_IS_REQUIRED = 83706, GOOGLE_WALLET_CARD_SOURCE_CARD_LAST_FOUR_IS_REQUIRED = 83707, ADDRESS_CANNOT_BE_BLANK = 81801, ADDRESS_COMPANY_IS_INVALID = 91821, ADDRESS_COMPANY_IS_TOO_LONG = 81802, ADDRESS_COUNTRY_CODE_ALPHA2_IS_NOT_ACCEPTED = 91814, ADDRESS_COUNTRY_CODE_ALPHA3_IS_NOT_ACCEPTED = 91816, ADDRESS_COUNTRY_CODE_NUMERIC_IS_NOT_ACCEPTED = 91817, ADDRESS_COUNTRY_NAME_IS_NOT_ACCEPTED = 91803, ADDRESS_EXTENDED_ADDRESS_IS_INVALID = 91823, ADDRESS_EXTENDED_ADDRESS_IS_TOO_LONG = 81804, ADDRESS_FIRST_NAME_IS_INVALID = 91819, ADDRESS_FIRST_NAME_IS_TOO_LONG = 81805, ADDRESS_INCONSISTENT_COUNTRY = 91815, ADDRESS_IS_INVALID = 91828, ADDRESS_LAST_NAME_IS_INVALID = 91820, ADDRESS_LAST_NAME_IS_TOO_LONG = 81806, ADDRESS_LOCALITY_IS_INVALID = 91824, ADDRESS_LOCALITY_IS_TOO_LONG = 81807, ADDRESS_POSTAL_CODE_INVALID_CHARACTERS = 81813, ADDRESS_POSTAL_CODE_IS_INVALID = 91826, ADDRESS_POSTAL_CODE_IS_REQUIRED = 81808, ADDRESS_POSTAL_CODE_IS_TOO_LONG = 81809, ADDRESS_REGION_IS_INVALID = 91825, ADDRESS_REGION_IS_TOO_LONG = 81810, ADDRESS_STATE_IS_INVALID_FOR_SELLER_PROTECTION = 81827, ADDRESS_STREET_ADDRESS_IS_INVALID = 91822, ADDRESS_STREET_ADDRESS_IS_REQUIRED = 81811, ADDRESS_STREET_ADDRESS_IS_TOO_LONG = 81812, ADDRESS_TOO_MANY_ADDRESSES_PER_CUSTOMER = 91818, APPLE_PAY_CARDS_ARE_NOT_ACCEPTED = 83501, APPLE_PAY_CUSTOMER_ID_IS_REQUIRED_FOR_VAULTING = 83502, APPLE_PAY_TOKEN_IS_IN_USE = 93503, APPLE_PAY_PAYMENT_METHOD_NONCE_CONSUMED = 93504, APPLE_PAY_PAYMENT_METHOD_NONCE_UNKNOWN = 93505, APPLE_PAY_PAYMENT_METHOD_NONCE_LOCKED = 93506, APPLE_PAY_PAYMENT_METHOD_NONCE_CARD_TYPE_IS_NOT_ACCEPTED = 83518, APPLE_PAY_CANNOT_UPDATE_APPLE_PAY_CARD_USING_PAYMENT_METHOD_NONCE = 93507, APPLE_PAY_NUMBER_IS_REQUIRED = 93508, APPLE_PAY_EXPIRATION_MONTH_IS_REQUIRED = 93509, APPLE_PAY_EXPIRATION_YEAR_IS_REQUIRED = 93510, APPLE_PAY_CRYPTOGRAM_IS_REQUIRED = 93511, APPLE_PAY_DECRYPTION_FAILED = 83512, APPLE_PAY_DISABLED = 93513, APPLE_PAY_MERCHANT_NOT_CONFIGURED = 93514, APPLE_PAY_MERCHANT_KEYS_ALREADY_CONFIGURED = 93515, APPLE_PAY_MERCHANT_KEYS_NOT_CONFIGURED = 93516, APPLE_PAY_CERTIFICATE_INVALID = 93517, APPLE_PAY_CERTIFICATE_MISMATCH = 93519, APPLE_PAY_INVALID_TOKEN = 83520, APPLE_PAY_PRIVATE_KEY_MISMATCH = 93521, APPLE_PAY_KEY_MISMATCH_STORING_CERTIFICATE = 93522, AUTHORIZATION_FINGERPRINT_INVALID_CREATED_AT = 93204, AUTHORIZATION_FINGERPRINT_INVALID_FORMAT = 93202, AUTHORIZATION_FINGERPRINT_INVALID_PUBLIC_KEY = 93205, AUTHORIZATION_FINGERPRINT_INVALID_SIGNATURE = 93206, AUTHORIZATION_FINGERPRINT_MISSING_FINGERPRINT = 93201, AUTHORIZATION_FINGERPRINT_OPTIONS_NOT_ALLOWED_WITHOUT_CUSTOMER = 93207, AUTHORIZATION_FINGERPRINT_SIGNATURE_REVOKED = 93203, CLIENT_TOKEN_CUSTOMER_DOES_NOT_EXIST = 92804, CLIENT_TOKEN_FAIL_ON_DUPLICATE_PAYMENT_METHOD_REQUIRES_CUSTOMER_ID = 92803, CLIENT_TOKEN_MAKE_DEFAULT_REQUIRES_CUSTOMER_ID = 92801, CLIENT_TOKEN_MERCHANT_ACCOUNT_DOES_NOT_EXIST = 92807, CLIENT_TOKEN_PROXY_MERCHANT_DOES_NOT_EXIST = 92805, CLIENT_TOKEN_UNSUPPORTED_VERSION = 92806, CLIENT_TOKEN_VERIFY_CARD_REQUIRES_CUSTOMER_ID = 92802, CREDIT_CARD_BILLING_ADDRESS_CONFLICT = 91701, CREDIT_CARD_BILLING_ADDRESS_FORMAT_IS_INVALID = 91744, CREDIT_CARD_BILLING_ADDRESS_ID_IS_INVALID = 91702, CREDIT_CARD_CANNOT_UPDATE_CARD_USING_PAYMENT_METHOD_NONCE = 91735, CREDIT_CARD_CARDHOLDER_NAME_IS_TOO_LONG = 81723, CREDIT_CARD_CREDIT_CARD_TYPE_IS_NOT_ACCEPTED = 81703, CREDIT_CARD_CREDIT_CARD_TYPE_IS_NOT_ACCEPTED_BY_SUBSCRIPTION_MERCHANT_ACCOUNT = 81718, CREDIT_CARD_CUSTOMER_ID_IS_INVALID = 91705, CREDIT_CARD_CUSTOMER_ID_IS_REQUIRED = 91704, CREDIT_CARD_CVV_IS_INVALID = 81707, CREDIT_CARD_CVV_IS_REQUIRED = 81706, CREDIT_CARD_CVV_VERIFICATION_FAILED = 81736, CREDIT_CARD_DUPLICATE_CARD_EXISTS = 81724, CREDIT_CARD_EXPIRATION_DATE_CONFLICT = 91708, CREDIT_CARD_EXPIRATION_DATE_IS_INVALID = 81710, CREDIT_CARD_EXPIRATION_DATE_IS_REQUIRED = 81709, CREDIT_CARD_EXPIRATION_DATE_YEAR_IS_INVALID = 81711, CREDIT_CARD_EXPIRATION_MONTH_IS_INVALID = 81712, CREDIT_CARD_EXPIRATION_YEAR_IS_INVALID = 81713, CREDIT_CARD_INVALID_PARAMS_FOR_CREDIT_CARD_UPDATE = 91745, CREDIT_CARD_INVALID_VENMO_SDK_PAYMENT_METHOD_CODE = 91727, CREDIT_CARD_NUMBER_HAS_INVALID_LENGTH = 81716, CREDIT_CARD_NUMBER_IS_INVALID = 81715, CREDIT_CARD_NUMBER_IS_PROHIBITED = 81750, CREDIT_CARD_NUMBER_IS_REQUIRED = 81714, CREDIT_CARD_NUMBER_LENGTH_IS_INVALID = 81716, CREDIT_CARD_NUMBER_MUST_BE_TEST_NUMBER = 81717, CREDIT_CARD_OPTIONS_UPDATE_EXISTING_TOKEN_IS_INVALID = 91723, CREDIT_CARD_OPTIONS_UPDATE_EXISTING_TOKEN_NOT_ALLOWED = 91729, CREDIT_CARD_OPTIONS_VERIFICATION_AMOUNT_CANNOT_BE_NEGATIVE = 91739, CREDIT_CARD_OPTIONS_VERIFICATION_AMOUNT_FORMAT_IS_INVALID = 91740, CREDIT_CARD_OPTIONS_VERIFICATION_AMOUNT_IS_TOO_LARGE = 91752, CREDIT_CARD_OPTIONS_VERIFICATION_AMOUNT_NOT_SUPPORTED_BY_PROCESSOR = 91741, CREDIT_CARD_OPTIONS_VERIFICATION_MERCHANT_ACCOUNT_ID_IS_INVALID = 91728, CREDIT_CARD_OPTIONS_VERIFICATION_MERCHANT_ACCOUNT_IS_FORBIDDEN = 91743, CREDIT_CARD_OPTIONS_VERIFICATION_MERCHANT_ACCOUNT_IS_SUSPENDED = 91742, CREDIT_CARD_PAYMENT_METHOD_CONFLICT = 81725, CREDIT_CARD_PAYMENT_METHOD_IS_NOT_A_CREDIT_CARD = 91738, CREDIT_CARD_PAYMENT_METHOD_NONCE_CARD_TYPE_IS_NOT_ACCEPTED = 91734, CREDIT_CARD_PAYMENT_METHOD_NONCE_CONSUMED = 91731, CREDIT_CARD_PAYMENT_METHOD_NONCE_LOCKED = 91733, CREDIT_CARD_PAYMENT_METHOD_NONCE_UNKNOWN = 91732, CREDIT_CARD_POSTAL_CODE_VERIFICATION_FAILED = 81737, CREDIT_CARD_TOKEN_FORMAT_IS_INVALID = 91718, CREDIT_CARD_TOKEN_INVALID = 91718, CREDIT_CARD_TOKEN_IS_IN_USE = 91719, CREDIT_CARD_TOKEN_IS_NOT_ALLOWED = 91721, CREDIT_CARD_TOKEN_IS_REQUIRED = 91722, CREDIT_CARD_TOKEN_IS_TOO_LONG = 91720, CREDIT_CARD_VENMO_SDK_PAYMENT_METHOD_CODE_CARD_TYPE_IS_NOT_ACCEPTED = 91726, CREDIT_CARD_VERIFICATION_NOT_SUPPORTED_ON_THIS_MERCHANT_ACCOUNT = 91730, CUSTOMER_COMPANY_IS_TOO_LONG = 81601, CUSTOMER_CUSTOM_FIELD_IS_INVALID = 91602, CUSTOMER_CUSTOM_FIELD_IS_TOO_LONG = 81603, CUSTOMER_EMAIL_FORMAT_IS_INVALID = 81604, CUSTOMER_EMAIL_IS_INVALID = 81604, CUSTOMER_EMAIL_IS_REQUIRED = 81606, CUSTOMER_EMAIL_IS_TOO_LONG = 81605, CUSTOMER_FAX_IS_TOO_LONG = 81607, CUSTOMER_FIRST_NAME_IS_TOO_LONG = 81608, CUSTOMER_ID_IS_INVAILD = 91610, //Deprecated CUSTOMER_ID_IS_INVALID = 91610, CUSTOMER_ID_IS_IN_USE = 91609, CUSTOMER_ID_IS_NOT_ALLOWED = 91611, CUSTOMER_ID_IS_REQUIRED = 91613, CUSTOMER_ID_IS_TOO_LONG = 91612, CUSTOMER_LAST_NAME_IS_TOO_LONG = 81613, CUSTOMER_PHONE_IS_TOO_LONG = 81614, CUSTOMER_VAULTED_PAYMENT_INSTRUMENT_NONCE_BELONGS_TO_DIFFERENT_CUSTOMER = 91617, CUSTOMER_WEBSITE_FORMAT_IS_INVALID = 81616, CUSTOMER_WEBSITE_IS_INVALID = 81616, CUSTOMER_WEBSITE_IS_TOO_LONG = 81615, DESCRIPTOR_DYNAMIC_DESCRIPTORS_DISABLED = 92203, DESCRIPTOR_INTERNATIONAL_NAME_FORMAT_IS_INVALID = 92204, DESCRIPTOR_INTERNATIONAL_PHONE_FORMAT_IS_INVALID = 92205, DESCRIPTOR_NAME_FORMAT_IS_INVALID = 92201, DESCRIPTOR_PHONE_FORMAT_IS_INVALID = 92202, DESCRIPTOR_URL_FORMAT_IS_INVALID = 92206, INDUSTRY_DATA_INDUSTRY_TYPE_IS_INVALID = 93401, INDUSTRY_DATA_LODGING_EMPTY_DATA = 93402, INDUSTRY_DATA_LODGING_FOLIO_NUMBER_IS_INVALID = 93403, INDUSTRY_DATA_LODGING_CHECK_IN_DATE_IS_INVALID = 93404, INDUSTRY_DATA_LODGING_CHECK_OUT_DATE_IS_INVALID = 93405, INDUSTRY_DATA_LODGING_CHECK_OUT_DATE_MUST_FOLLOW_CHECK_IN_DATE = 93406, INDUSTRY_DATA_LODGING_UNKNOWN_DATA_FIELD = 93407, INDUSTRY_DATA_TRAVEL_CRUISE_EMPTY_DATA = 93408, INDUSTRY_DATA_TRAVEL_CRUISE_UNKNOWN_DATA_FIELD = 93409, INDUSTRY_DATA_TRAVEL_CRUISE_TRAVEL_PACKAGE_IS_INVALID = 93410, INDUSTRY_DATA_TRAVEL_CRUISE_DEPARTURE_DATE_IS_INVALID = 93411, INDUSTRY_DATA_TRAVEL_CRUISE_LODGING_CHECK_IN_DATE_IS_INVALID = 93412, INDUSTRY_DATA_TRAVEL_CRUISE_LODGING_CHECK_OUT_DATE_IS_INVALID = 93413, MERCHANT_COUNTRY_CANNOT_BE_BLANK = 83603, MERCHANT_COUNTRY_CODE_ALPHA2_IS_INVALID = 93607, MERCHANT_COUNTRY_CODE_ALPHA2_IS_NOT_ACCEPTED = 93606, MERCHANT_COUNTRY_CODE_ALPHA3_IS_INVALID = 93605, MERCHANT_COUNTRY_CODE_ALPHA3_IS_NOT_ACCEPTED = 93604, MERCHANT_COUNTRY_CODE_NUMERIC_IS_INVALID = 93609, MERCHANT_COUNTRY_CODE_NUMERIC_IS_NOT_ACCEPTED = 93608, MERCHANT_COUNTRY_NAME_IS_INVALID = 93611, MERCHANT_COUNTRY_NAME_IS_NOT_ACCEPTED = 93610, MERCHANT_CURRENCIES_ARE_INVALID = 93614, MERCHANT_EMAIL_FORMAT_IS_INVALID = 93602, MERCHANT_EMAIL_IS_REQUIRED = 83601, MERCHANT_INCONSISTENT_COUNTRY = 93612, MERCHANT_PAYMENT_METHODS_ARE_INVALID = 93613, MERCHANT_PAYMENT_METHODS_ARE_NOT_ALLOWED = 93615, MERCHANT_ACCOUNT_CANNOT_BE_UPDATED = 82674, MERCHANT_ACCOUNT_ID_CANNOT_BE_UPDATED = 82675, MERCHANT_ACCOUNT_ID_FORMAT_IS_INVALID = 82603, MERCHANT_ACCOUNT_ID_IS_IN_USE = 82604, MERCHANT_ACCOUNT_ID_IS_NOT_ALLOWED = 82605, MERCHANT_ACCOUNT_ID_IS_TOO_LONG = 82602, MERCHANT_ACCOUNT_MASTER_MERCHANT_ACCOUNT_ID_CANNOT_BE_UPDATED = 82676, MERCHANT_ACCOUNT_MASTER_MERCHANT_ACCOUNT_ID_IS_INVALID = 82607, MERCHANT_ACCOUNT_MASTER_MERCHANT_ACCOUNT_ID_IS_REQUIRED = 82606, MERCHANT_ACCOUNT_MASTER_MERCHANT_ACCOUNT_MUST_BE_ACTIVE = 82608, MERCHANT_ACCOUNT_TOS_ACCEPTED_IS_REQUIRED = 82610, MERCHANT_ACCOUNT_APPLICANT_DETAILS_ACCOUNT_NUMBER_IS_INVALID = 82670, MERCHANT_ACCOUNT_APPLICANT_DETAILS_ACCOUNT_NUMBER_IS_REQUIRED = 82614, MERCHANT_ACCOUNT_APPLICANT_DETAILS_COMPANY_NAME_IS_INVALID = 82631, MERCHANT_ACCOUNT_APPLICANT_DETAILS_COMPANY_NAME_IS_REQUIRED_WITH_TAX_ID = 82633, MERCHANT_ACCOUNT_APPLICANT_DETAILS_DATE_OF_BIRTH_IS_INVALID = 82663, MERCHANT_ACCOUNT_APPLICANT_DETAILS_DATE_OF_BIRTH_IS_REQUIRED = 82612, MERCHANT_ACCOUNT_APPLICANT_DETAILS_DECLINED = 82626, MERCHANT_ACCOUNT_APPLICANT_DETAILS_DECLINED_MASTER_CARD_MATCH = 82622, MERCHANT_ACCOUNT_APPLICANT_DETAILS_DECLINED_OFAC = 82621, MERCHANT_ACCOUNT_APPLICANT_DETAILS_DECLINED_FAILED_KYC = 82623, MERCHANT_ACCOUNT_APPLICANT_DETAILS_DECLINED_SSN_INVALID = 82624, MERCHANT_ACCOUNT_APPLICANT_DETAILS_DECLINED_SSN_MATCHES_DECEASED = 82625, MERCHANT_ACCOUNT_APPLICANT_DETAILS_EMAIL_ADDRESS_IS_INVALID = 82616, MERCHANT_ACCOUNT_APPLICANT_DETAILS_EMAIL_ADDRESS_IS_REQUIRED = 82665, MERCHANT_ACCOUNT_APPLICANT_DETAILS_FIRST_NAME_IS_INVALID = 82627, MERCHANT_ACCOUNT_APPLICANT_DETAILS_FIRST_NAME_IS_REQUIRED = 82609, MERCHANT_ACCOUNT_APPLICANT_DETAILS_LAST_NAME_IS_INVALID = 82628, MERCHANT_ACCOUNT_APPLICANT_DETAILS_LAST_NAME_IS_REQUIRED = 82611, MERCHANT_ACCOUNT_APPLICANT_DETAILS_PHONE_IS_INVALID = 82636, MERCHANT_ACCOUNT_APPLICANT_DETAILS_ROUTING_NUMBER_IS_INVALID = 82635, MERCHANT_ACCOUNT_APPLICANT_DETAILS_ROUTING_NUMBER_IS_REQUIRED = 82613, MERCHANT_ACCOUNT_APPLICANT_DETAILS_SSN_IS_INVALID = 82615, MERCHANT_ACCOUNT_APPLICANT_DETAILS_TAX_ID_IS_INVALID = 82632, MERCHANT_ACCOUNT_APPLICANT_DETAILS_TAX_ID_IS_REQUIRED_WITH_COMPANY_NAME = 82634, MERCHANT_ACCOUNT_APPLICANT_DETAILS_TAX_ID_MUST_BE_BLANK = 82673, MERCHANT_ACCOUNT_APPLICANT_DETAILS_ADDRESS_LOCALITY_IS_REQUIRED = 82618, MERCHANT_ACCOUNT_APPLICANT_DETAILS_ADDRESS_POSTAL_CODE_IS_INVALID = 82630, MERCHANT_ACCOUNT_APPLICANT_DETAILS_ADDRESS_POSTAL_CODE_IS_REQUIRED = 82619, MERCHANT_ACCOUNT_APPLICANT_DETAILS_ADDRESS_REGION_IS_INVALID = 82664, MERCHANT_ACCOUNT_APPLICANT_DETAILS_ADDRESS_REGION_IS_REQUIRED = 82620, MERCHANT_ACCOUNT_APPLICANT_DETAILS_ADDRESS_STREET_ADDRESS_IS_INVALID = 82629, MERCHANT_ACCOUNT_APPLICANT_DETAILS_ADDRESS_STREET_ADDRESS_IS_REQUIRED = 82617, MERCHANT_ACCOUNT_BUSINESS_DBA_NAME_IS_INVALID = 82646, MERCHANT_ACCOUNT_BUSINESS_LEGAL_NAME_IS_INVALID = 82677, MERCHANT_ACCOUNT_BUSINESS_TAX_ID_IS_INVALID = 82647, MERCHANT_ACCOUNT_BUSINESS_LEGAL_NAME_IS_REQUIRED_WITH_TAX_ID = 82669, MERCHANT_ACCOUNT_BUSINESS_TAX_ID_IS_REQUIRED_WITH_LEGAL_NAME = 82648, MERCHANT_ACCOUNT_BUSINESS_TAX_ID_MUST_BE_BLANK = 82672, MERCHANT_ACCOUNT_BUSINESS_ADDRESS_STREET_ADDRESS_IS_INVALID = 82685, MERCHANT_ACCOUNT_BUSINESS_ADDRESS_POSTAL_CODE_IS_INVALID = 82686, MERCHANT_ACCOUNT_BUSINESS_ADDRESS_REGION_IS_INVALID = 82684, MERCHANT_ACCOUNT_FUNDING_ACCOUNT_NUMBER_IS_INVALID = 82671, MERCHANT_ACCOUNT_FUNDING_ACCOUNT_NUMBER_IS_REQUIRED = 82641, MERCHANT_ACCOUNT_FUNDING_ROUTING_NUMBER_IS_INVALID = 82649, MERCHANT_ACCOUNT_FUNDING_ROUTING_NUMBER_IS_REQUIRED = 82640, MERCHANT_ACCOUNT_FUNDING_DESTINATION_IS_INVALID = 82679, MERCHANT_ACCOUNT_FUNDING_DESTINATION_IS_REQUIRED = 82678, MERCHANT_ACCOUNT_FUNDING_EMAIL_IS_INVALID = 82681, MERCHANT_ACCOUNT_FUNDING_EMAIL_IS_REQUIRED = 82680, MERCHANT_ACCOUNT_FUNDING_MOBILE_PHONE_IS_INVALID = 82683, MERCHANT_ACCOUNT_FUNDING_MOBILE_PHONE_IS_REQUIRED = 82682, MERCHANT_ACCOUNT_INDIVIDUAL_FIRST_NAME_IS_INVALID = 82644, MERCHANT_ACCOUNT_INDIVIDUAL_FIRST_NAME_IS_REQUIRED = 82637, MERCHANT_ACCOUNT_INDIVIDUAL_LAST_NAME_IS_INVALID = 82645, MERCHANT_ACCOUNT_INDIVIDUAL_LAST_NAME_IS_REQUIRED = 82638, MERCHANT_ACCOUNT_INDIVIDUAL_DATE_OF_BIRTH_IS_INVALID = 82666, MERCHANT_ACCOUNT_INDIVIDUAL_DATE_OF_BIRTH_IS_REQUIRED = 82639, MERCHANT_ACCOUNT_INDIVIDUAL_EMAIL_IS_INVALID = 82643, MERCHANT_ACCOUNT_INDIVIDUAL_EMAIL_IS_REQUIRED = 82667, MERCHANT_ACCOUNT_INDIVIDUAL_PHONE_IS_INVALID = 82656, MERCHANT_ACCOUNT_INDIVIDUAL_SSN_IS_INVALID = 82642, MERCHANT_ACCOUNT_INDIVIDUAL_ADDRESS_STREET_ADDRESS_IS_REQUIRED = 82657, MERCHANT_ACCOUNT_INDIVIDUAL_ADDRESS_STREET_ADDRESS_IS_INVALID = 82661, MERCHANT_ACCOUNT_INDIVIDUAL_ADDRESS_LOCALITY_IS_REQUIRED = 82658, MERCHANT_ACCOUNT_INDIVIDUAL_ADDRESS_POSTAL_CODE_IS_INVALID = 82662, MERCHANT_ACCOUNT_INDIVIDUAL_ADDRESS_POSTAL_CODE_IS_REQUIRED = 82659, MERCHANT_ACCOUNT_INDIVIDUAL_ADDRESS_REGION_IS_INVALID = 82668, MERCHANT_ACCOUNT_INDIVIDUAL_ADDRESS_REGION_IS_REQUIRED = 82660, OAUTH_INVALID_GRANT = 93801, OAUTH_INVALID_CREDENTIALS = 93802, OAUTH_INVALID_SCOPE = 93803, OAUTH_INVALID_REQUEST = 93804, OAUTH_UNSUPPORTED_GRANT_TYPE = 93805, PAYMENT_METHOD_CANNOT_FORWARD_PAYMENT_METHOD_TYPE = 93106, PAYMENT_METHOD_CUSTOMER_ID_IS_INVALID = 93105, PAYMENT_METHOD_CUSTOMER_ID_IS_REQUIRED = 93104, PAYMENT_METHOD_NONCE_IS_INVALID = 93102, PAYMENT_METHOD_NONCE_IS_REQUIRED = 93103, PAYMENT_METHOD_PAYMENT_METHOD_PARAMS_ARE_REQUIRED = 93101, PAYMENT_METHOD_PAYMENT_METHOD_NONCE_CONSUMED = 93107, PAYMENT_METHOD_PAYMENT_METHOD_NONCE_UNKNOWN = 93108, PAYMENT_METHOD_PAYMENT_METHOD_NONCE_LOCKED = 93109, PAYPAL_ACCOUNT_AUTH_EXPIRED = 92911, PAYPAL_ACCOUNT_CANNOT_HAVE_BOTH_ACCESS_TOKEN_AND_CONSENT_CODE = 82903, PAYPAL_ACCOUNT_CANNOT_HAVE_FUNDING_SOURCE_WITHOUT_ACCESS_TOKEN = 92912, PAYPAL_ACCOUNT_CANNOT_UPDATE_PAYPAL_ACCOUNT_USING_PAYMENT_METHOD_NONCE = 92914, PAYPAL_ACCOUNT_CANNOT_VAULT_ONE_TIME_USE_PAYPAL_ACCOUNT = 82902, PAYPAL_ACCOUNT_CONSENT_CODE_OR_ACCESS_TOKEN_IS_REQUIRED = 82901, PAYPAL_ACCOUNT_CUSTOMER_ID_IS_REQUIRED_FOR_VAULTING = 82905, PAYPAL_ACCOUNT_INVALID_FUNDING_SOURCE_SELECTION = 92913, PAYPAL_ACCOUNT_INVALID_PARAMS_FOR_PAYPAL_ACCOUNT_UPDATE = 92915, PAYPAL_ACCOUNT_PAYMENT_METHOD_NONCE_CONSUMED = 92907, PAYPAL_ACCOUNT_PAYMENT_METHOD_NONCE_LOCKED = 92909, PAYPAL_ACCOUNT_PAYMENT_METHOD_NONCE_UNKNOWN = 92908, PAYPAL_ACCOUNT_PAYPAL_ACCOUNTS_ARE_NOT_ACCEPTED = 82904, PAYPAL_ACCOUNT_PAYPAL_COMMUNICATION_ERROR = 92910, PAYPAL_ACCOUNT_TOKEN_IS_IN_USE = 92906, SEPA_BANK_ACCOUNT_ACCOUNT_HOLDER_NAME_IS_REQUIRED = 93003, SEPA_BANK_ACCOUNT_BIC_IS_REQUIRED = 93002, SEPA_BANK_ACCOUNT_IBAN_IS_REQUIRED = 93001, SEPA_MANDATE_ACCOUNT_HOLDER_NAME_IS_REQUIRED = 83301, SEPA_MANDATE_BIC_INVALID_CHARACTER = 83306, SEPA_MANDATE_BIC_IS_REQUIRED = 83302, SEPA_MANDATE_BIC_LENGTH_IS_INVALID = 83307, SEPA_MANDATE_BIC_UNSUPPORTED_COUNTRY = 83308, SEPA_MANDATE_BILLING_ADDRESS_CONFLICT = 93312, SEPA_MANDATE_BILLING_ADDRESS_ID_IS_INVALID = 93313, SEPA_MANDATE_IBAN_INVALID_CHARACTER = 83305, SEPA_MANDATE_IBAN_INVALID_FORMAT = 83310, SEPA_MANDATE_IBAN_IS_REQUIRED = 83303, SEPA_MANDATE_IBAN_UNSUPPORTED_COUNTRY = 83309, SEPA_MANDATE_LOCALE_IS_UNSUPPORTED = 93311, SEPA_MANDATE_TYPE_IS_REQUIRED = 93304, SETTLEMENT_BATCH_SUMMARY_CUSTOM_FIELD_IS_INVALID = 82303, SETTLEMENT_BATCH_SUMMARY_SETTLEMENT_DATE_IS_INVALID = 82302, SETTLEMENT_BATCH_SUMMARY_SETTLEMENT_DATE_IS_REQUIRED = 82301, SUBSCRIPTION_BILLING_DAY_OF_MONTH_CANNOT_BE_UPDATED = 91918, SUBSCRIPTION_BILLING_DAY_OF_MONTH_IS_INVALID = 91914, SUBSCRIPTION_BILLING_DAY_OF_MONTH_MUST_BE_NUMERIC = 91913, SUBSCRIPTION_CANNOT_ADD_DUPLICATE_ADDON_OR_DISCOUNT = 91911, SUBSCRIPTION_CANNOT_EDIT_CANCELED_SUBSCRIPTION = 81901, SUBSCRIPTION_CANNOT_EDIT_EXPIRED_SUBSCRIPTION = 81910, SUBSCRIPTION_CANNOT_EDIT_PRICE_CHANGING_FIELDS_ON_PAST_DUE_SUBSCRIPTION = 91920, SUBSCRIPTION_FIRST_BILLING_DATE_CANNOT_BE_IN_THE_PAST = 91916, SUBSCRIPTION_FIRST_BILLING_DATE_CANNOT_BE_UPDATED = 91919, SUBSCRIPTION_FIRST_BILLING_DATE_IS_INVALID = 91915, SUBSCRIPTION_ID_IS_IN_USE = 81902, SUBSCRIPTION_INCONSISTENT_NUMBER_OF_BILLING_CYCLES = 91908, SUBSCRIPTION_INCONSISTENT_START_DATE = 91917, SUBSCRIPTION_INVALID_REQUEST_FORMAT = 91921, SUBSCRIPTION_MERCHANT_ACCOUNT_DOES_NOT_SUPPORT_INSTRUMENT_TYPE = 91930, SUBSCRIPTION_MERCHANT_ACCOUNT_ID_IS_INVALID = 91901, SUBSCRIPTION_MISMATCH_CURRENCY_ISO_CODE = 91923, SUBSCRIPTION_NUMBER_OF_BILLING_CYCLES_CANNOT_BE_BLANK = 91912, SUBSCRIPTION_NUMBER_OF_BILLING_CYCLES_IS_TOO_SMALL = 91909, SUBSCRIPTION_NUMBER_OF_BILLING_CYCLES_MUST_BE_GREATER_THAN_ZERO = 91907, SUBSCRIPTION_NUMBER_OF_BILLING_CYCLES_MUST_BE_NUMERIC = 91906, SUBSCRIPTION_PAYMENT_METHOD_NONCE_INSTRUMENT_TYPE_DOES_NOT_SUPPORT_SUBSCRIPTIONS = 91929, SUBSCRIPTION_PAYMENT_METHOD_TOKEN_CARD_TYPE_IS_NOT_ACCEPTED = 91902, SUBSCRIPTION_PAYMENT_METHOD_TOKEN_INSTRUMENT_TYPE_DOES_NOT_SUPPORT_SUBSCRIPTIONS = 91928, SUBSCRIPTION_PAYMENT_METHOD_TOKEN_IS_INVALID = 91903, SUBSCRIPTION_PAYMENT_METHOD_TOKEN_NOT_ASSOCIATED_WITH_CUSTOMER = 91905, SUBSCRIPTION_PLAN_BILLING_FREQUENCY_CANNOT_BE_UPDATED = 91922, SUBSCRIPTION_PLAN_ID_IS_INVALID = 91904, SUBSCRIPTION_PRICE_CANNOT_BE_BLANK = 81903, SUBSCRIPTION_PRICE_FORMAT_IS_INVALID = 81904, SUBSCRIPTION_PRICE_IS_TOO_LARGE = 81923, SUBSCRIPTION_STATUS_IS_CANCELED = 81905, SUBSCRIPTION_TOKEN_FORMAT_IS_INVALID = 81906, SUBSCRIPTION_TRIAL_DURATION_FORMAT_IS_INVALID = 81907, SUBSCRIPTION_TRIAL_DURATION_IS_REQUIRED = 81908, SUBSCRIPTION_TRIAL_DURATION_UNIT_IS_INVALID = 81909, SUBSCRIPTION_MODIFICATION_ID_TO_REMOVE_IS_INVALID = 92025, SUBSCRIPTION_MODIFICATION_AMOUNT_CANNOT_BE_BLANK = 92003, SUBSCRIPTION_MODIFICATION_AMOUNT_IS_INVALID = 92002, SUBSCRIPTION_MODIFICATION_AMOUNT_IS_TOO_LARGE = 92023, SUBSCRIPTION_MODIFICATION_CANNOT_EDIT_MODIFICATIONS_ON_PAST_DUE_SUBSCRIPTION = 92022, SUBSCRIPTION_MODIFICATION_CANNOT_UPDATE_AND_REMOVE = 92015, SUBSCRIPTION_MODIFICATION_EXISTING_ID_IS_INCORRECT_KIND = 92020, SUBSCRIPTION_MODIFICATION_EXISTING_ID_IS_INVALID = 92011, SUBSCRIPTION_MODIFICATION_EXISTING_ID_IS_REQUIRED = 92012, SUBSCRIPTION_MODIFICATION_ID_TO_REMOVE_IS_INCORRECT_KIND = 92021, SUBSCRIPTION_MODIFICATION_ID_TO_REMOVE_IS_NOT_PRESENT = 92016, SUBSCRIPTION_MODIFICATION_INCONSISTENT_NUMBER_OF_BILLING_CYCLES = 92018, SUBSCRIPTION_MODIFICATION_INHERITED_FROM_ID_IS_INVALID = 92013, SUBSCRIPTION_MODIFICATION_INHERITED_FROM_ID_IS_REQUIRED = 92014, SUBSCRIPTION_MODIFICATION_MISSING = 92024, SUBSCRIPTION_MODIFICATION_NUMBER_OF_BILLING_CYCLES_CANNOT_BE_BLANK = 92017, SUBSCRIPTION_MODIFICATION_NUMBER_OF_BILLING_CYCLES_IS_INVALID = 92005, SUBSCRIPTION_MODIFICATION_NUMBER_OF_BILLING_CYCLES_MUST_BE_GREATER_THAN_ZERO = 92019, SUBSCRIPTION_MODIFICATION_QUANTITY_CANNOT_BE_BLANK = 92004, SUBSCRIPTION_MODIFICATION_QUANTITY_IS_INVALID = 92001, SUBSCRIPTION_MODIFICATION_QUANTITY_MUST_BE_GREATER_THAN_ZERO = 92010, SUBSCRIPTION_PAYMENT_METHOD_NONCE_CARD_TYPE_IS_NOT_ACCEPTED = 91924, SUBSCRIPTION_PAYMENT_METHOD_NONCE_IS_INVALID = 91925, SUBSCRIPTION_PAYMENT_METHOD_NONCE_NOT_ASSOCIATED_WITH_CUSTOMER = 91926, SUBSCRIPTION_PAYMENT_METHOD_NONCE_UNVAULTED_CARD_IS_NOT_ACCEPTED = 91927, TRANSACTION_AMOUNT_CANNOT_BE_NEGATIVE = 81501, TRANSACTION_AMOUNT_DOES_NOT_MATCH3_D_SECURE_AMOUNT = 91585, TRANSACTION_AMOUNT_FORMAT_IS_INVALID = 81503, TRANSACTION_AMOUNT_IS_INVALID = 81503, TRANSACTION_AMOUNT_IS_REQUIRED = 81502, TRANSACTION_AMOUNT_IS_TOO_LARGE = 81528, TRANSACTION_AMOUNT_MUST_BE_GREATER_THAN_ZERO = 81531, TRANSACTION_BILLING_ADDRESS_CONFLICT = 91530, TRANSACTION_CANNOT_BE_VOIDED = 91504, TRANSACTION_CANNOT_CANCEL_RELEASE = 91562, TRANSACTION_CANNOT_CLONE_CREDIT = 91543, TRANSACTION_CANNOT_CLONE_TRANSACTION_WITH_PAYPAL_ACCOUNT = 91573, TRANSACTION_CANNOT_CLONE_TRANSACTION_WITH_VAULT_CREDIT_CARD = 91540, TRANSACTION_CANNOT_CLONE_UNSUCCESSFUL_TRANSACTION = 91542, TRANSACTION_CANNOT_CLONE_VOICE_AUTHORIZATIONS = 91541, TRANSACTION_CANNOT_HOLD_IN_ESCROW = 91560, TRANSACTION_CANNOT_PARTIALLY_REFUND_ESCROWED_TRANSACTION = 91563, TRANSACTION_CANNOT_REFUND_CREDIT = 91505, TRANSACTION_CANNOT_REFUND_SETTLING_TRANSACTION = 91574, TRANSACTION_CANNOT_REFUND_UNLESS_SETTLED = 91506, TRANSACTION_CANNOT_REFUND_WITH_PENDING_MERCHANT_ACCOUNT = 91559, TRANSACTION_CANNOT_REFUND_WITH_SUSPENDED_MERCHANT_ACCOUNT = 91538, TRANSACTION_CANNOT_RELEASE_FROM_ESCROW = 91561, TRANSACTION_CANNOT_SIMULATE_SETTLEMENT = 91575, TRANSACTION_CANNOT_SUBMIT_FOR_PARTIAL_SETTLEMENT = 915103, TRANSACTION_CANNOT_SUBMIT_FOR_SETTLEMENT = 91507, TRANSACTION_CANNOT_UPDATE_DETAILS_NOT_SUBMITTED_FOR_SETTLEMENT = 915129, TRANSACTION_CHANNEL_IS_TOO_LONG = 91550, TRANSACTION_CREDIT_CARD_IS_REQUIRED = 91508, TRANSACTION_CUSTOMER_DEFAULT_PAYMENT_METHOD_CARD_TYPE_IS_NOT_ACCEPTED = 81509, TRANSACTION_CUSTOMER_DOES_NOT_HAVE_CREDIT_CARD = 91511, TRANSACTION_CUSTOMER_ID_IS_INVALID = 91510, TRANSACTION_CUSTOM_FIELD_IS_INVALID = 91526, TRANSACTION_CUSTOM_FIELD_IS_TOO_LONG = 81527, TRANSACTION_HAS_ALREADY_BEEN_REFUNDED = 91512, TRANSACTION_MERCHANT_ACCOUNT_DOES_NOT_MATCH3_D_SECURE_MERCHANT_ACCOUNT = 91584, TRANSACTION_MERCHANT_ACCOUNT_DOES_NOT_SUPPORT_MOTO = 91558, TRANSACTION_MERCHANT_ACCOUNT_DOES_NOT_SUPPORT_REFUNDS = 91547, TRANSACTION_MERCHANT_ACCOUNT_ID_IS_INVALID = 91513, TRANSACTION_MERCHANT_ACCOUNT_IS_SUSPENDED = 91514, TRANSACTION_MERCHANT_ACCOUNT_NAME_IS_INVALID = 91513, //Deprecated TRANSACTION_OPTIONS_PAY_PAL_CUSTOM_FIELD_TOO_LONG = 91580, TRANSACTION_OPTIONS_SUBMIT_FOR_SETTLEMENT_IS_REQUIRED_FOR_CLONING = 91544, TRANSACTION_OPTIONS_SUBMIT_FOR_SETTLEMENT_IS_REQUIRED_FOR_PAYPAL_UNILATERAL = 91582, TRANSACTION_OPTIONS_USE_BILLING_FOR_SHIPPING_DISABLED = 91572, TRANSACTION_OPTIONS_VAULT_IS_DISABLED = 91525, TRANSACTION_ORDER_ID_IS_TOO_LONG = 91501, TRANSACTION_PAYMENT_INSTRUMENT_NOT_SUPPORTED_BY_MERCHANT_ACCOUNT = 91577, TRANSACTION_PAYMENT_INSTRUMENT_TYPE_IS_NOT_ACCEPTED = 915101, TRANSACTION_PAYMENT_METHOD_CONFLICT = 91515, TRANSACTION_PAYMENT_METHOD_CONFLICT_WITH_VENMO_SDK = 91549, TRANSACTION_PAYMENT_METHOD_DOES_NOT_BELONG_TO_CUSTOMER = 91516, TRANSACTION_PAYMENT_METHOD_DOES_NOT_BELONG_TO_SUBSCRIPTION = 91527, TRANSACTION_PAYMENT_METHOD_NONCE_CARD_TYPE_IS_NOT_ACCEPTED = 91567, TRANSACTION_PAYMENT_METHOD_NONCE_CONSUMED = 91564, TRANSACTION_PAYMENT_METHOD_NONCE_HAS_NO_VALID_PAYMENT_INSTRUMENT_TYPE = 91569, TRANSACTION_PAYMENT_METHOD_NONCE_LOCKED = 91566, TRANSACTION_PAYMENT_METHOD_NONCE_UNKNOWN = 91565, TRANSACTION_PAYMENT_METHOD_TOKEN_CARD_TYPE_IS_NOT_ACCEPTED = 91517, TRANSACTION_PAYMENT_METHOD_TOKEN_IS_INVALID = 91518, TRANSACTION_PAYPAL_NOT_ENABLED = 91576, TRANSACTION_PAY_PAL_AUTH_EXPIRED = 91579, TRANSACTION_PAY_PAL_VAULT_RECORD_MISSING_DATA = 91583, TRANSACTION_PROCESSOR_AUTHORIZATION_CODE_CANNOT_BE_SET = 91519, TRANSACTION_PROCESSOR_AUTHORIZATION_CODE_IS_INVALID = 81520, TRANSACTION_PROCESSOR_DOES_NOT_SUPPORT_AUTHS = 915104, TRANSACTION_PROCESSOR_DOES_NOT_SUPPORT_CREDITS = 91546, TRANSACTION_PROCESSOR_DOES_NOT_SUPPORT_PARTIAL_SETTLEMENT = 915102, TRANSACTION_PROCESSOR_DOES_NOT_SUPPORT_UPDATING_DETAILS = 915130, TRANSACTION_PROCESSOR_DOES_NOT_SUPPORT_VOICE_AUTHORIZATIONS = 91545, TRANSACTION_PURCHASE_ORDER_NUMBER_IS_INVALID = 91548, TRANSACTION_PURCHASE_ORDER_NUMBER_IS_TOO_LONG = 91537, TRANSACTION_REFUND_AMOUNT_IS_TOO_LARGE = 91521, TRANSACTION_SERVICE_FEE_AMOUNT_CANNOT_BE_NEGATIVE = 91554, TRANSACTION_SERVICE_FEE_AMOUNT_FORMAT_IS_INVALID = 91555, TRANSACTION_SERVICE_FEE_AMOUNT_IS_TOO_LARGE = 91556, TRANSACTION_SERVICE_FEE_AMOUNT_NOT_ALLOWED_ON_MASTER_MERCHANT_ACCOUNT = 91557, TRANSACTION_SERVICE_FEE_IS_NOT_ALLOWED_ON_CREDITS = 91552, TRANSACTION_SERVICE_FEE_NOT_ACCEPTED_FOR_PAYPAL = 91578, TRANSACTION_SETTLEMENT_AMOUNT_IS_LESS_THAN_SERVICE_FEE_AMOUNT = 91551, TRANSACTION_SETTLEMENT_AMOUNT_IS_TOO_LARGE = 91522, TRANSACTION_SHIPPING_ADDRESS_DOESNT_MATCH_CUSTOMER = 91581, TRANSACTION_SUBSCRIPTION_DOES_NOT_BELONG_TO_CUSTOMER = 91529, TRANSACTION_SUBSCRIPTION_ID_IS_INVALID = 91528, TRANSACTION_SUBSCRIPTION_STATUS_MUST_BE_PAST_DUE = 91531, TRANSACTION_SUB_MERCHANT_ACCOUNT_REQUIRES_SERVICE_FEE_AMOUNT = 91553, TRANSACTION_TAX_AMOUNT_CANNOT_BE_NEGATIVE = 81534, TRANSACTION_TAX_AMOUNT_FORMAT_IS_INVALID = 81535, TRANSACTION_TAX_AMOUNT_IS_TOO_LARGE = 81536, TRANSACTION_THREE_D_SECURE_AUTHENTICATION_FAILED = 81571, TRANSACTION_THREE_D_SECURE_TOKEN_IS_INVALID = 91568, TRANSACTION_THREE_D_SECURE_TRANSACTION_DATA_DOESNT_MATCH_VERIFY = 91570, TRANSACTION_THREE_D_SECURE_PASS_THRU_ECI_FLAG_IS_REQUIRED = 915113, TRANSACTION_THREE_D_SECURE_PASS_THRU_CAVV_IS_REQUIRED = 915116, TRANSACTION_THREE_D_SECURE_PASS_THRU_XID_IS_REQUIRED = 915115, TRANSACTION_THREE_D_SECURE_PASS_THRU_ECI_FLAG_IS_INVALID = 915114, TRANSACTION_THREE_D_SECURE_PASS_THRU_MERCHANT_ACCOUNT_DOES_NOT_SUPPORT_CARD_TYPE = 915131, TRANSACTION_TYPE_IS_INVALID = 91523, TRANSACTION_TYPE_IS_REQUIRED = 91524, TRANSACTION_UNSUPPORTED_VOICE_AUTHORIZATION = 91539, VERIFICATION_OPTIONS_AMOUNT_CANNOT_BE_NEGATIVE = 94201, VERIFICATION_OPTIONS_AMOUNT_FORMAT_IS_INVALID = 94202, VERIFICATION_OPTIONS_AMOUNT_IS_TOO_LARGE = 94207, VERIFICATION_OPTIONS_AMOUNT_NOT_SUPPORTED_BY_PROCESSOR = 94203, VERIFICATION_OPTIONS_MERCHANT_ACCOUNT_ID_IS_INVALID = 94204, VERIFICATION_OPTIONS_MERCHANT_ACCOUNT_IS_SUSPENDED = 94205, VERIFICATION_OPTIONS_MERCHANT_ACCOUNT_IS_FORBIDDEN = 94206 } }
/****************************************************************************** * 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 Leap.Unity.Query; using System; using System.Collections; using System.Collections.Generic; #if UNITY_EDITOR using UnityEditor; #endif using UnityEngine; namespace Leap.Unity.Attachments { /// <summary> /// This MonoBehaviour is managed by an AttachmentHands component on a parent MonoBehaviour. /// Instead of adding AttachmentHand directly to a GameObject, add an AttachmentHands component /// to a parent GameObject to manage the construction and updating of AttachmentHand objects. /// </summary> [AddComponentMenu("")] [ExecuteInEditMode] public class AttachmentHand : MonoBehaviour { /// <summary> /// Called when the AttachmentHand refreshes its AttachmentPointBehaviour transforms. If the /// user unchecks an attachment point in the AttachmentHands inspector, those Transforms will /// be destroyed; otherwise, existing Transforms will persist, so be careful not to unnecessarily /// duplicate any objects or components you may want to attach via this callback. /// /// Also, you can use AttachmentHand.points for an enumerator of all existing AttachmentPointBehaviour /// transforms on a given AttachmentHand object. /// </summary> public Action OnAttachmentPointsModified = () => { }; #region AttachmentPointBehaviours [HideInInspector] public AttachmentPointBehaviour wrist; [HideInInspector] public AttachmentPointBehaviour palm; [HideInInspector] public AttachmentPointBehaviour thumbProximalJoint; [HideInInspector] public AttachmentPointBehaviour thumbDistalJoint; [HideInInspector] public AttachmentPointBehaviour thumbTip; [HideInInspector] public AttachmentPointBehaviour indexKnuckle; [HideInInspector] public AttachmentPointBehaviour indexMiddleJoint; [HideInInspector] public AttachmentPointBehaviour indexDistalJoint; [HideInInspector] public AttachmentPointBehaviour indexTip; [HideInInspector] public AttachmentPointBehaviour middleKnuckle; [HideInInspector] public AttachmentPointBehaviour middleMiddleJoint; [HideInInspector] public AttachmentPointBehaviour middleDistalJoint; [HideInInspector] public AttachmentPointBehaviour middleTip; [HideInInspector] public AttachmentPointBehaviour ringKnuckle; [HideInInspector] public AttachmentPointBehaviour ringMiddleJoint; [HideInInspector] public AttachmentPointBehaviour ringDistalJoint; [HideInInspector] public AttachmentPointBehaviour ringTip; [HideInInspector] public AttachmentPointBehaviour pinkyKnuckle; [HideInInspector] public AttachmentPointBehaviour pinkyMiddleJoint; [HideInInspector] public AttachmentPointBehaviour pinkyDistalJoint; [HideInInspector] public AttachmentPointBehaviour pinkyTip; #endregion /// <summary> /// Gets an enumerator that traverses all of the AttachmentPoints beneath this AttachmentHand. /// </summary> public AttachmentPointsEnumerator points { get { return new AttachmentPointsEnumerator(this); } } private bool _attachmentPointsDirty = false; /// <summary> /// Used by AttachmentHands as a hint to help prevent mixing up hand chiralities /// when refreshing its AttachmentHand references. /// </summary> [SerializeField, Disable] private Chirality _chirality; /// <summary> /// Gets the chirality of this AttachmentHand. This is set automatically by the /// AttachmentHands parent object of this AttachmentHand. /// </summary> public Chirality chirality { get { return _chirality; } set { _chirality = value; } } /// <summary> /// Used by AttachmentHands as a hint to help prevent mixing up hand chiralities /// when refreshing its AttachmentHand references. /// </summary> [SerializeField, Disable] private bool _isTracked; /// <summary> /// Gets the chirality of this AttachmentHand. This is set automatically by the /// AttachmentHands parent object of this AttachmentHand. /// </summary> public bool isTracked { get { return _isTracked; } set { _isTracked = value; } } void OnValidate() { initializeAttachmentPointFlagConstants(); } void Awake() { initializeAttachmentPointFlagConstants(); } #if !UNITY_EDITOR #pragma warning disable 0414 #endif private bool _isBeingDestroyed = false; #if !UNITY_EDITOR #pragma warning restore 0414 #endif void OnDestroy() { _isBeingDestroyed = true; } /// <summary> /// Returns the AttachmentPointBehaviour child object of this AttachmentHand given a /// reference to a single AttachmentPointFlags flag, or null if there is no such child object. /// </summary> public AttachmentPointBehaviour GetBehaviourForPoint(AttachmentPointFlags singlePoint) { AttachmentPointBehaviour behaviour = null; switch (singlePoint) { case AttachmentPointFlags.None: break; case AttachmentPointFlags.Wrist: behaviour = wrist; break; case AttachmentPointFlags.Palm: behaviour = palm; break; case AttachmentPointFlags.ThumbProximalJoint: behaviour = thumbProximalJoint; break; case AttachmentPointFlags.ThumbDistalJoint: behaviour = thumbDistalJoint; break; case AttachmentPointFlags.ThumbTip: behaviour = thumbTip; break; case AttachmentPointFlags.IndexKnuckle: behaviour = indexKnuckle; break; case AttachmentPointFlags.IndexMiddleJoint: behaviour = indexMiddleJoint; break; case AttachmentPointFlags.IndexDistalJoint: behaviour = indexDistalJoint; break; case AttachmentPointFlags.IndexTip: behaviour = indexTip; break; case AttachmentPointFlags.MiddleKnuckle: behaviour = middleKnuckle; break; case AttachmentPointFlags.MiddleMiddleJoint: behaviour = middleMiddleJoint; break; case AttachmentPointFlags.MiddleDistalJoint: behaviour = middleDistalJoint; break; case AttachmentPointFlags.MiddleTip: behaviour = middleTip; break; case AttachmentPointFlags.RingKnuckle: behaviour = ringKnuckle; break; case AttachmentPointFlags.RingMiddleJoint: behaviour = ringMiddleJoint; break; case AttachmentPointFlags.RingDistalJoint: behaviour = ringDistalJoint; break; case AttachmentPointFlags.RingTip: behaviour = ringTip; break; case AttachmentPointFlags.PinkyKnuckle: behaviour = pinkyKnuckle; break; case AttachmentPointFlags.PinkyMiddleJoint: behaviour = pinkyMiddleJoint; break; case AttachmentPointFlags.PinkyDistalJoint: behaviour = pinkyDistalJoint; break; case AttachmentPointFlags.PinkyTip: behaviour = pinkyTip; break; } return behaviour; } public void refreshAttachmentTransforms(AttachmentPointFlags points) { if (_attachmentPointFlagConstants == null || _attachmentPointFlagConstants.Length == 0) { initializeAttachmentPointFlagConstants(); } // First just _check_ whether we'll need to do any destruction or creation bool requiresDestructionOrCreation = false; foreach (var flag in _attachmentPointFlagConstants) { if (flag == AttachmentPointFlags.None) continue; if ((!points.Contains(flag) && GetBehaviourForPoint(flag) != null) || (points.Contains(flag) && GetBehaviourForPoint(flag) == null)) { requiresDestructionOrCreation = true; } } // Go through the work of flattening and rebuilding if it is necessary. if (requiresDestructionOrCreation) { // Remove parent-child relationships so deleting parent Transforms doesn't annihilate // child Transforms that don't need to be deleted themselves. flattenAttachmentTransformHierarchy(); foreach (AttachmentPointFlags flag in _attachmentPointFlagConstants) { if (flag == AttachmentPointFlags.None) continue; if (points.Contains(flag)) { ensureTransformExists(flag); } else { ensureTransformDoesNotExist(flag); } } // Organize transforms, restoring parent-child relationships. organizeAttachmentTransforms(); } if (_attachmentPointsDirty) { OnAttachmentPointsModified(); _attachmentPointsDirty = false; } } public void notifyPointBehaviourDeleted(AttachmentPointBehaviour point) { #if UNITY_EDITOR // Only valid if the AttachmentHand itself is also not being destroyed. if (_isBeingDestroyed) return; // Refresh this hand's attachment transforms on a slight delay. // Only AttachmentHands can _truly_ remove attachment points! AttachmentHands attachHands = GetComponentInParent<AttachmentHands>(); if (attachHands != null) { EditorApplication.delayCall += () => { refreshAttachmentTransforms(attachHands.attachmentPoints); }; } #endif } #region Internal private AttachmentPointFlags[] _attachmentPointFlagConstants; private void initializeAttachmentPointFlagConstants() { Array flagConstants = Enum.GetValues(typeof(AttachmentPointFlags)); if (_attachmentPointFlagConstants == null || _attachmentPointFlagConstants.Length == 0) { _attachmentPointFlagConstants = new AttachmentPointFlags[flagConstants.Length]; } int i = 0; foreach (int f in flagConstants) { _attachmentPointFlagConstants[i++] = (AttachmentPointFlags)f; } } private void setBehaviourForPoint(AttachmentPointFlags singlePoint, AttachmentPointBehaviour behaviour) { switch (singlePoint) { case AttachmentPointFlags.None: break; case AttachmentPointFlags.Wrist: wrist = behaviour; break; case AttachmentPointFlags.Palm: palm = behaviour; break; case AttachmentPointFlags.ThumbProximalJoint: thumbProximalJoint = behaviour; break; case AttachmentPointFlags.ThumbDistalJoint: thumbDistalJoint = behaviour; break; case AttachmentPointFlags.ThumbTip: thumbTip = behaviour; break; case AttachmentPointFlags.IndexKnuckle: indexKnuckle = behaviour; break; case AttachmentPointFlags.IndexMiddleJoint: indexMiddleJoint = behaviour; break; case AttachmentPointFlags.IndexDistalJoint: indexDistalJoint = behaviour; break; case AttachmentPointFlags.IndexTip: indexTip = behaviour; break; case AttachmentPointFlags.MiddleKnuckle: middleKnuckle = behaviour; break; case AttachmentPointFlags.MiddleMiddleJoint: middleMiddleJoint = behaviour; break; case AttachmentPointFlags.MiddleDistalJoint: middleDistalJoint = behaviour; break; case AttachmentPointFlags.MiddleTip: middleTip = behaviour; break; case AttachmentPointFlags.RingKnuckle: ringKnuckle = behaviour; break; case AttachmentPointFlags.RingMiddleJoint: ringMiddleJoint = behaviour; break; case AttachmentPointFlags.RingDistalJoint: ringDistalJoint = behaviour; break; case AttachmentPointFlags.RingTip: ringTip = behaviour; break; case AttachmentPointFlags.PinkyKnuckle: pinkyKnuckle = behaviour; break; case AttachmentPointFlags.PinkyMiddleJoint: pinkyMiddleJoint = behaviour; break; case AttachmentPointFlags.PinkyDistalJoint: pinkyDistalJoint = behaviour; break; case AttachmentPointFlags.PinkyTip: pinkyTip = behaviour; break; } #if UNITY_EDITOR EditorUtility.SetDirty(this); #endif } private void ensureTransformExists(AttachmentPointFlags singlePoint) { if (!singlePoint.IsSinglePoint()) { Debug.LogError("Tried to ensure transform exists for singlePoint, but it contains more than one set flag."); return; } AttachmentPointBehaviour pointBehaviour = GetBehaviourForPoint(singlePoint); if (pointBehaviour == null) { // First, see if there's already one in the hierarchy! Might exist due to, e.g. an Undo operation var existingPointBehaviour = this.gameObject.GetComponentsInChildren<AttachmentPointBehaviour>() .Query() .FirstOrDefault(p => p.attachmentPoint == singlePoint); // Only make a new object if the transform really doesn't exist. if (existingPointBehaviour == AttachmentPointFlags.None) { GameObject obj = new GameObject(Enum.GetName(typeof(AttachmentPointFlags), singlePoint)); #if UNITY_EDITOR Undo.RegisterCreatedObjectUndo(obj, "Created Object"); pointBehaviour = Undo.AddComponent<AttachmentPointBehaviour>(obj); #else pointBehaviour = obj.AddComponent<AttachmentPointBehaviour>(); #endif } else { pointBehaviour = existingPointBehaviour; } #if UNITY_EDITOR Undo.RecordObject(pointBehaviour, "Set Attachment Point"); #endif pointBehaviour.attachmentPoint = singlePoint; pointBehaviour.attachmentHand = this; setBehaviourForPoint(singlePoint, pointBehaviour); SetTransformParent(pointBehaviour.transform, this.transform); _attachmentPointsDirty = true; #if UNITY_EDITOR EditorUtility.SetDirty(this); #endif } } private static void SetTransformParent(Transform t, Transform parent) { #if UNITY_EDITOR Undo.SetTransformParent(t, parent, "Set Transform Parent"); #else t.parent = parent; #endif } private void ensureTransformDoesNotExist(AttachmentPointFlags singlePoint) { if (!singlePoint.IsSinglePoint()) { Debug.LogError("Tried to ensure transform exists for singlePoint, but it contains more than one set flag"); return; } var pointBehaviour = GetBehaviourForPoint(singlePoint); if (pointBehaviour != null) { InternalUtility.Destroy(pointBehaviour.gameObject); setBehaviourForPoint(singlePoint, null); pointBehaviour = null; _attachmentPointsDirty = true; #if UNITY_EDITOR EditorUtility.SetDirty(this); #endif } } private void flattenAttachmentTransformHierarchy() { foreach (var point in this.points) { SetTransformParent(point.transform, this.transform); } } private void organizeAttachmentTransforms() { int siblingIdx = 0; // Wrist if (wrist != null) { wrist.transform.SetSiblingIndex(siblingIdx++); } // Palm if (palm != null) { palm.transform.SetSiblingIndex(siblingIdx++); } Transform topLevelTransform; // Thumb topLevelTransform = tryStackTransformHierarchy(thumbProximalJoint, thumbDistalJoint, thumbTip); if (topLevelTransform != null) { topLevelTransform.SetSiblingIndex(siblingIdx++); } // Index topLevelTransform = tryStackTransformHierarchy(indexKnuckle, indexMiddleJoint, indexDistalJoint, indexTip); if (topLevelTransform != null) { topLevelTransform.SetSiblingIndex(siblingIdx++); } // Middle topLevelTransform = tryStackTransformHierarchy(middleKnuckle, middleMiddleJoint, middleDistalJoint, middleTip); if (topLevelTransform != null) { topLevelTransform.SetSiblingIndex(siblingIdx++); } // Ring topLevelTransform = tryStackTransformHierarchy(ringKnuckle, ringMiddleJoint, ringDistalJoint, ringTip); if (topLevelTransform != null) { topLevelTransform.SetSiblingIndex(siblingIdx++); } // Pinky topLevelTransform = tryStackTransformHierarchy(pinkyKnuckle, pinkyMiddleJoint, pinkyDistalJoint, pinkyTip); if (topLevelTransform != null) { topLevelTransform.SetSiblingIndex(siblingIdx++); } } private static Transform[] s_hierarchyTransformsBuffer = new Transform[4]; /// <summary> /// Tries to build a parent-child stack (index 0 is the first parent) of the argument /// transforms (they might be null) and returns the top-level parent transform (or null /// if there is none). /// </summary> private Transform tryStackTransformHierarchy(params Transform[] transforms) { for (int i = 0; i < s_hierarchyTransformsBuffer.Length; i++) { s_hierarchyTransformsBuffer[i] = null; } int hierarchyCount = 0; foreach (var transform in transforms.Query().Where(t => t != null)) { s_hierarchyTransformsBuffer[hierarchyCount++] = transform; } for (int i = hierarchyCount - 1; i > 0; i--) { SetTransformParent(s_hierarchyTransformsBuffer[i], s_hierarchyTransformsBuffer[i - 1]); } if (hierarchyCount > 0) { return s_hierarchyTransformsBuffer[0]; } return null; } private static Transform[] s_transformsBuffer = new Transform[4]; private Transform tryStackTransformHierarchy(params MonoBehaviour[] monoBehaviours) { for (int i = 0; i < s_transformsBuffer.Length; i++) { s_transformsBuffer[i] = null; } int tIdx = 0; foreach (var behaviour in monoBehaviours.Query().Where(b => b != null)) { s_transformsBuffer[tIdx++] = behaviour.transform; } return tryStackTransformHierarchy(s_transformsBuffer); } /// <summary> /// An enumerator that traverses all of the existing AttachmentPointBehaviours beneath an /// AttachmentHand. /// </summary> public struct AttachmentPointsEnumerator { private int _curIdx; private AttachmentHand _hand; private int _flagsCount; public AttachmentPointsEnumerator GetEnumerator() { return this; } public AttachmentPointsEnumerator(AttachmentHand hand) { if (hand != null && hand._attachmentPointFlagConstants != null) { _curIdx = -1; _hand = hand; _flagsCount = hand._attachmentPointFlagConstants.Length; } else { // Hand doesn't exist (destroyed?) or isn't initialized yet. _curIdx = -1; _hand = null; _flagsCount = 0; } } public AttachmentPointBehaviour Current { get { if (_hand == null) return null; return _hand.GetBehaviourForPoint(GetFlagFromFlagIdx(_curIdx)); } } public bool MoveNext() { do { _curIdx++; } while (_curIdx < _flagsCount && _hand.GetBehaviourForPoint(GetFlagFromFlagIdx(_curIdx)) == null); return _curIdx < _flagsCount; } } private static AttachmentPointFlags GetFlagFromFlagIdx(int pointIdx) { return (AttachmentPointFlags)(1 << pointIdx + 1); } #endregion } }
/* * CryptoTestCase.cs - encapsulate a cryptographic algorithm test case. * * Copyright (C) 2002 Southern Storm Software, Pty Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using CSUnit; using System; using System.Reflection; using System.IO; using System.Text; using System.Security.Cryptography; #if CONFIG_CRYPTO public class CryptoTestCase : TestCase { // Constructor. public CryptoTestCase(String name) : base(name) { // Nothing to do here. } // Set up for the tests. protected override void Setup() { // Nothing to do here. } // Clean up after the tests. protected override void Cleanup() { // Nothing to do here. } // Determine if two byte blocks are identical. public static bool IdenticalBlock(byte[] block1, int offset1, byte[] block2, int offset2, int length) { while(length > 0) { if(block1[offset1++] != block2[offset2++]) { return false; } --length; } return true; } // Determine if the random number generator appears to be working. // We use this before calling "GenerateKey" for "DES" and "TripleDES", // to prevent infinite loops in the test suite. public static bool RandomWorks() { int index; byte[] rand = new byte [16]; RandomNumberGenerator rng = RandomNumberGenerator.Create(); rng.GetBytes(rand); for(index = 0; index < 16; ++index) { if(rand[index] != 0x00) { return true; } } return false; } // Run a symmetric algorithm test. protected void RunSymmetric(SymmetricAlgorithm alg, byte[] key, byte[] plaintext, byte[] expected) { // Set up the algorithm the way we want. alg.Mode = CipherMode.ECB; alg.Padding = PaddingMode.None; // Create an encryptor and run the test forwards. ICryptoTransform encryptor = alg.CreateEncryptor(key, null); byte[] output = new byte [plaintext.Length * 2]; byte[] tail; int len = encryptor.TransformBlock (plaintext, 0, plaintext.Length, output, 0); AssertEquals("ECB encrypt length mismatch", len, expected.Length); tail = encryptor.TransformFinalBlock (plaintext, 0, 0); AssertNotNull("ECB encrypt tail should be non-null"); AssertEquals("ECB encrypt tail should be zero length", tail.Length, 0); if(!IdenticalBlock(expected, 0, output, 0, expected.Length)) { Fail("did not encrypt to the expected output"); } encryptor.Dispose(); // Create a decryptor and run the test backwards. ICryptoTransform decryptor = alg.CreateDecryptor(key, null); len = decryptor.TransformBlock (expected, 0, expected.Length, output, 0); AssertEquals("ECB decrypt length mismatch", len, expected.Length); tail = decryptor.TransformFinalBlock (expected, 0, 0); AssertNotNull("ECB decrypt tail should be non-null"); AssertEquals("ECB decrypt tail should be zero length", tail.Length, 0); if(!IdenticalBlock(plaintext, 0, output, 0, plaintext.Length)) { Fail("did not decrypt to the original plaintext"); } decryptor.Dispose(); } protected void RunSymmetric(String name, byte[] key, byte[] plaintext, byte[] expected) { int index = name.IndexOf(':'); if(index != -1) { // Use the default algorithm. Type type = Type.GetType("System.Security.Cryptography." + name.Substring(0, index), false, false); Object[] args; if((index + 1) < name.Length) { args = new Object [1]; args[0] = name.Substring(index + 1); } else { args = new Object [0]; } SymmetricAlgorithm alg = (SymmetricAlgorithm) (type.InvokeMember("Create", BindingFlags.DeclaredOnly | BindingFlags.Static | BindingFlags.Public | BindingFlags.InvokeMethod, null, null, args)); AssertEquals("default key size is wrong", alg.KeySize, key.Length * 8); RunSymmetric(alg, key, plaintext, expected); } else { // Use the specified algorithm. RunSymmetric(SymmetricAlgorithm.Create(name), key, plaintext, expected); } } // Run a hash algorithm test. protected void RunHash(HashAlgorithm alg, String value, byte[] expected) { // Make sure that the hash size is what we expect. AssertEquals("hash size is incorrect", alg.HashSize, expected.Length * 8); // Convert the string form of the input into a byte array. byte[] input = Encoding.ASCII.GetBytes(value); // Get the hash value over the input. byte[] hash = alg.ComputeHash(input); // Compare the hash with the expected value. AssertNotNull("returned hash was null", hash); AssertEquals("hash length is wrong", hash.Length, expected.Length); if(!IdenticalBlock(hash, 0, expected, 0, expected.Length)) { Fail("incorrect hash value produced"); } // Get the hash value over the input in a sub-buffer. byte[] input2 = new byte [input.Length + 20]; Array.Copy(input, 0, input2, 10, input.Length); hash = alg.ComputeHash(input2, 10, input.Length); // Compare the hash with the expected value. AssertNotNull("returned hash was null", hash); AssertEquals("hash length is wrong", hash.Length, expected.Length); if(!IdenticalBlock(hash, 0, expected, 0, expected.Length)) { Fail("incorrect hash value produced"); } // Get the hash value over the input via a stream. MemoryStream stream = new MemoryStream(input, false); hash = alg.ComputeHash(stream); // Compare the hash with the expected value. AssertNotNull("returned hash was null", hash); AssertEquals("hash length is wrong", hash.Length, expected.Length); if(!IdenticalBlock(hash, 0, expected, 0, expected.Length)) { Fail("incorrect hash value produced"); } } protected void RunHash(String name, String value, byte[] expected) { int index = name.IndexOf(':'); if(index != -1) { // Use the default algorithm. Type type = Type.GetType("System.Security.Cryptography." + name.Substring(0, index), false, false); Object[] args; if((index + 1) < name.Length) { args = new Object [1]; args[0] = name.Substring(index + 1); } else { args = new Object [0]; } HashAlgorithm alg = (HashAlgorithm) (type.InvokeMember("Create", BindingFlags.DeclaredOnly | BindingFlags.Static | BindingFlags.Public | BindingFlags.InvokeMethod, null, null, args)); RunHash(alg, value, expected); } else { // Use the specified algorithm. RunHash(HashAlgorithm.Create(name), value, expected); } } // Check that a size value is in a size list. private void CheckSize(String msg, KeySizes[] sizes, int value) { foreach(KeySizes size in sizes) { if(value >= size.MinSize && value <= size.MaxSize && ((value - size.MinSize) % size.SkipSize) == 0) { return; } } Fail(msg); } // Test the properties on a symmetric algorithm instance. protected void SymmetricPropertyTest(SymmetricAlgorithm alg, int expectedKeySize, int expectedBlockSize) { // Check the initial property values. AssertEquals("initial key size is incorrect", expectedKeySize, alg.KeySize); AssertEquals("initial block size is incorrect", expectedBlockSize, alg.BlockSize); AssertEquals("initial feedback block size is incorrect", expectedBlockSize, alg.FeedbackSize); AssertEquals("initial cipher mode is incorrect", CipherMode.CBC, alg.Mode); AssertEquals("initial padding mode is incorrect", PaddingMode.PKCS7, alg.Padding); AssertNotNull("legal key size array is null", alg.LegalKeySizes); AssertNotNull("legal block size array is null", alg.LegalBlockSizes); // Check that the size values are initially valid. CheckSize("initial key size is not legal", alg.LegalKeySizes, alg.KeySize); CheckSize("initial block size is not legal", alg.LegalBlockSizes, alg.BlockSize); // TODO: Try setting the key size to all legal values. // Check automatic key and IV generation. If the random // number generator doesn't work, then skip the test for // DES and TripleDES, to prevent an infinite loop within // those algorithm's weak key checking code. if((!(alg is DES) && !(alg is TripleDES)) || RandomWorks()) { byte[] key = alg.Key; AssertNotNull("generated key should not be null", key); AssertEquals("generated key is the wrong size", alg.KeySize, key.Length * 8); byte[] iv = alg.IV; AssertNotNull("generated IV should not be null", iv); AssertEquals("generated IV is the wrong size", alg.BlockSize, iv.Length * 8); } } // Test the properties on a hash algorithm instance. protected void HashPropertyTest(HashAlgorithm alg, int expectedHashSize) { AssertEquals("hash size is incorrect", alg.HashSize, expectedHashSize); AssertEquals("input block size is incorrect", alg.InputBlockSize, 1); AssertEquals("output block size is incorrect", alg.OutputBlockSize, 1); AssertEquals("multiple block transform flag is incorrect", alg.CanTransformMultipleBlocks, true); try { byte[] hash = alg.Hash; Fail("should not be able to get the hash yet"); } catch(CryptographicException) { // Success } } // Perform a primitive ECB encryption on a block. private void ECBBlock(byte[] buf, int index, SymmetricAlgorithm alg, byte[] key) { ICryptoTransform encryptor; CipherMode mode = alg.Mode; PaddingMode padding = alg.Padding; alg.Mode = CipherMode.ECB; alg.Padding = PaddingMode.None; encryptor = alg.CreateEncryptor(key, null); alg.Mode = mode; alg.Padding = padding; encryptor.TransformBlock(buf, index, alg.BlockSize / 8, buf, index); encryptor.Dispose(); } // XOR two blocks. private void XorBlock(byte[] buf1, int index1, byte[] buf2, int index2, SymmetricAlgorithm alg) { int length = alg.BlockSize / 8; while(length-- > 0) { buf1[index1++] ^= buf2[index2++]; } } // XOR two blocks. private void XorBlock(byte[] buf1, int index1, byte[] buf2, int index2, int length) { while(length-- > 0) { buf1[index1++] ^= buf2[index2++]; } } // Copy one block to another. private void CopyBlock(byte[] src, int srcIndex, byte[] dest, int destIndex, SymmetricAlgorithm alg) { int length = alg.BlockSize / 8; while(length-- > 0) { dest[destIndex++] = src[srcIndex++]; } } // Convert a string into a byte array, with padding applied. private byte[] StringToBytes(String str, SymmetricAlgorithm alg) { PaddingMode padding = alg.Padding; CipherMode cipher = alg.Mode; int size = alg.BlockSize / 8; int len, pad; byte[] input = Encoding.ASCII.GetBytes(str); byte[] padded; if(cipher == CipherMode.ECB || cipher == CipherMode.CBC) { // Block cipher mode - zero or PKCS7 padding only. if(padding == PaddingMode.None) { padding = PaddingMode.Zeros; } } else { // Stream cipher mode - padding is never required. padding = PaddingMode.None; } switch(padding) { case PaddingMode.None: break; case PaddingMode.PKCS7: { len = input.Length; len += size - (len % size); pad = len - input.Length; padded = new byte [len]; Array.Copy(input, 0, padded, 0, input.Length); len = input.Length; while(len < padded.Length) { padded[len++] = (byte)pad; } input = padded; } break; case PaddingMode.Zeros: { len = input.Length; if((len % size) != 0) { len += size - (len % size); } padded = new byte [len]; Array.Copy(input, 0, padded, 0, input.Length); input = padded; } break; } return input; } // Create a test key for a specific algorihtm. private byte[] CreateKey(SymmetricAlgorithm alg) { byte[] key = new byte [alg.KeySize / 8]; int posn; for(posn = 0; posn < key.Length; ++posn) { key[posn] = (byte)posn; } return key; } // Create a test IV for a specific algorithm. private byte[] CreateIV(SymmetricAlgorithm alg) { if(alg.Mode == CipherMode.ECB) { // ECB modes don't need an IV. return null; } else { // All other modes do need an IV. byte[] iv = new byte [alg.BlockSize / 8]; int posn; for(posn = 0; posn < iv.Length; ++posn) { iv[posn] = (byte)(iv.Length - posn); } return iv; } } // ECB-encrypt a buffer. private byte[] DoECB(byte[] input, SymmetricAlgorithm alg, byte[] key) { byte[] output = new byte [input.Length]; int size = alg.BlockSize / 8; Array.Copy(input, 0, output, 0, input.Length); int index = 0; while(index < input.Length) { ECBBlock(output, index, alg, key); index += size; } return output; } // CBC-encrypt a buffer. private byte[] DoCBC(byte[] input, SymmetricAlgorithm alg, byte[] key, byte[] _iv) { byte[] iv = new byte [_iv.Length]; Array.Copy(_iv, 0, iv, 0, _iv.Length); byte[] output = new byte [input.Length]; int size = alg.BlockSize / 8; Array.Copy(input, 0, output, 0, input.Length); int index = 0; while(index < input.Length) { XorBlock(output, index, iv, 0, alg); ECBBlock(output, index, alg, key); CopyBlock(output, index, iv, 0, alg); index += size; } return output; } // OFB-encrypt a buffer. private byte[] DoOFB(byte[] input, SymmetricAlgorithm alg, byte[] key, byte[] _iv) { byte[] iv = new byte [_iv.Length]; Array.Copy(_iv, 0, iv, 0, _iv.Length); byte[] output = new byte [input.Length]; Array.Copy(input, 0, output, 0, input.Length); int size = alg.BlockSize / 8; int index = 0; while(index < input.Length) { ECBBlock(iv, 0, alg, key); if((input.Length - index) >= size) { XorBlock(output, index, iv, 0, alg); } else { XorBlock(output, index, iv, 0, input.Length - index); } index += size; } return output; } // CFB-encrypt a buffer. private byte[] DoCFB(byte[] input, SymmetricAlgorithm alg, byte[] key, byte[] _iv) { byte[] iv = new byte [_iv.Length]; Array.Copy(_iv, 0, iv, 0, _iv.Length); byte[] output = new byte [input.Length]; Array.Copy(input, 0, output, 0, input.Length); int size = alg.BlockSize / 8; int index = 0; while(index < input.Length) { ECBBlock(iv, 0, alg, key); if((input.Length - index) >= size) { XorBlock(output, index, iv, 0, alg); CopyBlock(output, index, iv, 0, alg); } else { XorBlock(output, index, iv, 0, input.Length - index); } index += size; } return output; } // CTS-encrypt a buffer. private byte[] DoCTS(byte[] input, SymmetricAlgorithm alg, byte[] key, byte[] _iv) { if(input.Length < (alg.BlockSize / 8)) { // Streams shorter than one block are CFB-encrypted. return DoCFB(input, alg, key, _iv); } byte[] iv = new byte [_iv.Length]; Array.Copy(_iv, 0, iv, 0, _iv.Length); byte[] output = new byte [input.Length]; int size = alg.BlockSize / 8; Array.Copy(input, 0, output, 0, input.Length); int index = 0; int limit = input.Length; limit -= limit % size; limit -= size; // Encrypt the bulk of the input with CBC. while(index < limit) { XorBlock(output, index, iv, 0, alg); ECBBlock(output, index, alg, key); CopyBlock(output, index, iv, 0, alg); index += size; } // Encrypt the last two blocks using ciphertext stealing. byte[] last = new byte [size * 2]; Array.Copy(output, index, last, 0, input.Length - limit); XorBlock(last, 0, iv, 0, alg); ECBBlock(last, 0, alg, key); XorBlock(last, size, last, 0, alg); ECBBlock(last, size, alg, key); Array.Copy(last, size, output, index, size); Array.Copy(last, 0, output, index + size, input.Length % size); return output; } // Get a string that describes a particular cipher mode test, // for use in error messages. private static String GetError(String msg, SymmetricAlgorithm alg, String input) { return msg + String.Format (" ({0}, {1}, \"{2}\")", alg.Mode, alg.Padding, input); } // Run a cipher mode test. private void RunModeTest(SymmetricAlgorithm alg, CipherMode mode, PaddingMode padding, String input) { // Set the algorithm modes. alg.Mode = mode; alg.Padding = padding; // Get the raw and padded versions of the input. byte[] rawInput = Encoding.ASCII.GetBytes(input); byte[] paddedInput = StringToBytes(input, alg); // Generate key and IV values. byte[] key = CreateKey(alg); byte[] iv = CreateIV(alg); // Encrypt the raw input in the selected mode. int size = alg.BlockSize / 8; int cutoff = rawInput.Length - rawInput.Length % size; ICryptoTransform encryptor; encryptor = alg.CreateEncryptor(key, iv); Assert(GetError("encryptor cannot transform multiple blocks", alg, input), encryptor.CanTransformMultipleBlocks); if(mode == CipherMode.ECB || mode == CipherMode.CBC) { AssertEquals(GetError("encryptor has wrong input size", alg, input), size, encryptor.InputBlockSize); AssertEquals(GetError("encryptor has wrong output size", alg, input), size, encryptor.OutputBlockSize); } else { AssertEquals(GetError("encryptor has wrong input size", alg, input), 1, encryptor.InputBlockSize); AssertEquals(GetError("encryptor has wrong output size", alg, input), 1, encryptor.OutputBlockSize); } byte[] rawOutput = new byte [rawInput.Length + 256]; int len = encryptor.TransformBlock (rawInput, 0, cutoff, rawOutput, 0); byte[] rawTail = encryptor.TransformFinalBlock (rawInput, cutoff, rawInput.Length - cutoff); Array.Copy(rawTail, 0, rawOutput, len, rawTail.Length); len += rawTail.Length; ((IDisposable)encryptor).Dispose(); // Reverse the ciphertext back to the original. cutoff = len - len % size; ICryptoTransform decryptor; decryptor = alg.CreateDecryptor(key, iv); Assert(GetError("decryptor cannot transform multiple blocks", alg, input), decryptor.CanTransformMultipleBlocks); if(mode == CipherMode.ECB || mode == CipherMode.CBC) { AssertEquals(GetError("decryptor has wrong input size", alg, input), size, decryptor.InputBlockSize); AssertEquals(GetError("decryptor has wrong output size", alg, input), size, decryptor.OutputBlockSize); } else { AssertEquals(GetError("decryptor has wrong input size", alg, input), 1, decryptor.InputBlockSize); AssertEquals(GetError("decryptor has wrong output size", alg, input), 1, decryptor.OutputBlockSize); } byte[] rawReverse = new byte [rawInput.Length + 256]; int rlen = decryptor.TransformBlock (rawOutput, 0, cutoff, rawReverse, 0); rawTail = decryptor.TransformFinalBlock (rawOutput, cutoff, len - cutoff); Array.Copy(rawTail, 0, rawReverse, rlen, rawTail.Length); rlen += rawTail.Length; ((IDisposable)decryptor).Dispose(); // Compare the reversed plaintext with the original. if(padding != PaddingMode.None) { AssertEquals(GetError ("reversed plaintext has incorrect length", alg, input), rawInput.Length, rlen); if(!IdenticalBlock(rawInput, 0, rawReverse, 0, rlen)) { Fail(GetError ("reversed plaintext is not the same as original", alg, input)); } } else { if(rawInput.Length > rlen) { Fail(GetError ("reversed plaintext has incorrect length", alg, input)); } if(!IdenticalBlock(rawInput, 0, rawReverse, 0, rawInput.Length)) { Fail(GetError ("reversed plaintext is not the same as original", alg, input)); } } // Encrypt the padded plaintext using a primitive // algorithm simulation to verify the expected output. byte[] paddedOutput; switch(mode) { case CipherMode.ECB: { paddedOutput = DoECB(paddedInput, alg, key); } break; case CipherMode.CBC: { paddedOutput = DoCBC(paddedInput, alg, key, iv); } break; case CipherMode.OFB: { paddedOutput = DoOFB(paddedInput, alg, key, iv); } break; case CipherMode.CFB: { paddedOutput = DoCFB(paddedInput, alg, key, iv); } break; case CipherMode.CTS: default: { paddedOutput = DoCTS(paddedInput, alg, key, iv); } break; } // Compare the actual output with the expected output. AssertEquals(GetError("ciphertext has incorrect length", alg, input), paddedOutput.Length, len); if(!IdenticalBlock(paddedOutput, 0, rawOutput, 0, len)) { Fail(GetError("ciphertext was not the expected value", alg, input)); } } // Run a mode test using a number of different inputs and padding modes. protected void RunModeTest(SymmetricAlgorithm alg, CipherMode mode, PaddingMode padding) { RunModeTest(alg, mode, padding, ""); RunModeTest(alg, mode, padding, "abc"); RunModeTest(alg, mode, padding, "abcdefgh"); RunModeTest(alg, mode, padding, "abcdefghijk"); RunModeTest(alg, mode, padding, "abcdefghijklmno"); RunModeTest(alg, mode, padding, "The time has come the walrus said."); } protected void RunModeTest(SymmetricAlgorithm alg, CipherMode mode) { RunModeTest(alg, mode, PaddingMode.None); RunModeTest(alg, mode, PaddingMode.PKCS7); RunModeTest(alg, mode, PaddingMode.Zeros); } }; // CryptoTestCase #endif // CONFIG_CRYPTO
using System; using System.Reflection; using System.Windows; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Data; using ControlzEx; namespace MahApps.Metro.Controls { /// <summary> /// A Button that allows the user to toggle between two states. /// </summary> [TemplatePart(Name = PART_BackgroundTranslate, Type = typeof(TranslateTransform))] [TemplatePart(Name = PART_DraggingThumb, Type = typeof(Thumb))] [TemplatePart(Name = PART_SwitchTrack, Type = typeof(Grid))] [TemplatePart(Name = PART_ThumbIndicator, Type = typeof(FrameworkElement))] [TemplatePart(Name = PART_ThumbTranslate, Type = typeof(TranslateTransform))] public class ToggleSwitchButton : ToggleButton { private const string PART_BackgroundTranslate = "PART_BackgroundTranslate"; private const string PART_DraggingThumb = "PART_DraggingThumb"; private const string PART_SwitchTrack = "PART_SwitchTrack"; private const string PART_ThumbIndicator = "PART_ThumbIndicator"; private const string PART_ThumbTranslate = "PART_ThumbTranslate"; private TranslateTransform _BackgroundTranslate; private Thumb _DraggingThumb; private Grid _SwitchTrack; private FrameworkElement _ThumbIndicator; private TranslateTransform _ThumbTranslate; private readonly PropertyChangeNotifier isCheckedPropertyChangeNotifier; public static readonly DependencyProperty OnSwitchBrushProperty = DependencyProperty.Register("OnSwitchBrush", typeof(Brush), typeof(ToggleSwitchButton), null); public static readonly DependencyProperty OffSwitchBrushProperty = DependencyProperty.Register("OffSwitchBrush", typeof(Brush), typeof(ToggleSwitchButton), null); public static readonly DependencyProperty ThumbIndicatorBrushProperty = DependencyProperty.Register("ThumbIndicatorBrush", typeof(Brush), typeof(ToggleSwitchButton), null); public static readonly DependencyProperty ThumbIndicatorDisabledBrushProperty = DependencyProperty.Register("ThumbIndicatorDisabledBrush", typeof(Brush), typeof(ToggleSwitchButton), null); public static readonly DependencyProperty ThumbIndicatorWidthProperty = DependencyProperty.Register("ThumbIndicatorWidth", typeof(double), typeof(ToggleSwitchButton), new PropertyMetadata(13d)); /// <summary> /// Gets/sets the brush used for the on-switch's foreground. /// </summary> public Brush OnSwitchBrush { get { return (Brush)GetValue(OnSwitchBrushProperty); } set { SetValue(OnSwitchBrushProperty, value); } } /// <summary> /// Gets/sets the brush used for the off-switch's foreground. /// </summary> public Brush OffSwitchBrush { get { return (Brush)GetValue(OffSwitchBrushProperty); } set { SetValue(OffSwitchBrushProperty, value); } } /// <summary> /// Gets/sets the brush used for the thumb indicator. /// </summary> public Brush ThumbIndicatorBrush { get { return (Brush)GetValue(ThumbIndicatorBrushProperty); } set { SetValue(ThumbIndicatorBrushProperty, value); } } /// <summary> /// Gets/sets the brush used for the thumb indicator. /// </summary> public Brush ThumbIndicatorDisabledBrush { get { return (Brush)GetValue(ThumbIndicatorDisabledBrushProperty); } set { SetValue(ThumbIndicatorDisabledBrushProperty, value); } } /// <summary> /// Gets/sets the width of the thumb indicator. /// </summary> public double ThumbIndicatorWidth { get { return (double)GetValue(ThumbIndicatorWidthProperty); } set { SetValue(ThumbIndicatorWidthProperty, value); } } static ToggleSwitchButton() { DefaultStyleKeyProperty.OverrideMetadata(typeof(ToggleSwitchButton), new FrameworkPropertyMetadata(typeof(ToggleSwitchButton))); } public ToggleSwitchButton() { isCheckedPropertyChangeNotifier = new PropertyChangeNotifier(this, ToggleSwitchButton.IsCheckedProperty); isCheckedPropertyChangeNotifier.ValueChanged += IsCheckedPropertyChangeNotifierValueChanged; } private void IsCheckedPropertyChangeNotifierValueChanged(object sender, EventArgs e) { UpdateThumb(); } DoubleAnimation _thumbAnimation; private void UpdateThumb() { if (_ThumbTranslate != null && _SwitchTrack != null && _ThumbIndicator != null) { double destination = IsChecked.GetValueOrDefault() ? ActualWidth - (_SwitchTrack.Margin.Left + _SwitchTrack.Margin.Right + _ThumbIndicator.ActualWidth + _ThumbIndicator.Margin.Left + _ThumbIndicator.Margin.Right) : 0; _thumbAnimation = new DoubleAnimation(); _thumbAnimation.To = destination; _thumbAnimation.Duration = TimeSpan.FromMilliseconds(500); _thumbAnimation.EasingFunction = new ExponentialEase() { Exponent = 9 }; _thumbAnimation.FillBehavior = FillBehavior.Stop; AnimationTimeline currentAnimation = _thumbAnimation; _thumbAnimation.Completed += (sender, e) => { if (_thumbAnimation != null && currentAnimation == _thumbAnimation) { _ThumbTranslate.X = destination; _thumbAnimation = null; } }; _ThumbTranslate.BeginAnimation(TranslateTransform.XProperty, _thumbAnimation); } } public override void OnApplyTemplate() { base.OnApplyTemplate(); _BackgroundTranslate = GetTemplateChild(PART_BackgroundTranslate) as TranslateTransform; _DraggingThumb = GetTemplateChild(PART_DraggingThumb) as Thumb; _SwitchTrack = GetTemplateChild(PART_SwitchTrack) as Grid; _ThumbIndicator = GetTemplateChild(PART_ThumbIndicator) as FrameworkElement; _ThumbTranslate = GetTemplateChild(PART_ThumbTranslate) as TranslateTransform; if (_ThumbIndicator != null && _ThumbTranslate != null && _BackgroundTranslate != null) { Binding translationBinding; translationBinding = new System.Windows.Data.Binding("X"); translationBinding.Source = _ThumbTranslate; BindingOperations.SetBinding(_BackgroundTranslate, TranslateTransform.XProperty, translationBinding); } if (_DraggingThumb != null && _ThumbIndicator != null && _ThumbTranslate != null) { _DraggingThumb.DragStarted -= _DraggingThumb_DragStarted; _DraggingThumb.DragDelta -= _DraggingThumb_DragDelta; _DraggingThumb.DragCompleted -= _DraggingThumb_DragCompleted; _DraggingThumb.DragStarted += _DraggingThumb_DragStarted; _DraggingThumb.DragDelta += _DraggingThumb_DragDelta; _DraggingThumb.DragCompleted += _DraggingThumb_DragCompleted; if (_SwitchTrack != null) { _SwitchTrack.SizeChanged -= _SwitchTrack_SizeChanged; _SwitchTrack.SizeChanged += _SwitchTrack_SizeChanged; } } } private void SetIsPressed(bool pressed) { // we can't use readonly IsPressedProperty typeof(ToggleButton).GetMethod("set_IsPressed", BindingFlags.Instance | BindingFlags.NonPublic) .Invoke(this, new object[] { pressed }); } private double? _lastDragPosition; private bool _isDragging; void _DraggingThumb_DragStarted(object sender, DragStartedEventArgs e) { if (Mouse.LeftButton == MouseButtonState.Pressed) { if (!IsPressed) { SetIsPressed(true); } } if (_ThumbTranslate != null) { _ThumbTranslate.BeginAnimation(TranslateTransform.XProperty, null); double destination = IsChecked.GetValueOrDefault() ? ActualWidth - (_SwitchTrack.Margin.Left + _SwitchTrack.Margin.Right + _ThumbIndicator.ActualWidth + _ThumbIndicator.Margin.Left + _ThumbIndicator.Margin.Right) : 0; _ThumbTranslate.X = destination; _thumbAnimation = null; } _lastDragPosition = _ThumbTranslate.X; _isDragging = false; } void _DraggingThumb_DragDelta(object sender, DragDeltaEventArgs e) { if (_lastDragPosition.HasValue) { if (Math.Abs(e.HorizontalChange) > 3) _isDragging = true; if (_SwitchTrack != null && _ThumbIndicator != null) { double lastDragPosition = _lastDragPosition.Value; _ThumbTranslate.X = Math.Min(ActualWidth - (_SwitchTrack.Margin.Left + _SwitchTrack.Margin.Right + _ThumbIndicator.ActualWidth + _ThumbIndicator.Margin.Left + _ThumbIndicator.Margin.Right), Math.Max(0, lastDragPosition + e.HorizontalChange)); } } } void _DraggingThumb_DragCompleted(object sender, DragCompletedEventArgs e) { SetIsPressed(false); _lastDragPosition = null; if (!_isDragging) { OnClick(); } else if (_ThumbTranslate != null && _SwitchTrack != null) { if (!IsChecked.GetValueOrDefault() && _ThumbTranslate.X + 6.5 >= _SwitchTrack.ActualWidth / 2) { OnClick(); } else if (IsChecked.GetValueOrDefault() && _ThumbTranslate.X + 6.5 <= _SwitchTrack.ActualWidth / 2) { OnClick(); } UpdateThumb(); } } void _SwitchTrack_SizeChanged(object sender, SizeChangedEventArgs e) { if (_ThumbTranslate != null && _SwitchTrack != null && _ThumbIndicator != null) { double destination = IsChecked.GetValueOrDefault() ? ActualWidth - (_SwitchTrack.Margin.Left + _SwitchTrack.Margin.Right + _ThumbIndicator.ActualWidth + _ThumbIndicator.Margin.Left + _ThumbIndicator.Margin.Right) : 0; _ThumbTranslate.X = destination; } } } }
// Copyright 2005-2010 Gallio Project - http://www.gallio.org/ // Portions Copyright 2000-2004 Jonathan de Halleux // // 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.Reflection; using Gallio.Framework.Assertions; using MbUnit.Framework; #pragma warning disable 0618 namespace MbUnit.Compatibility.Tests.Framework { [TestFixture] [TestsOn(typeof(Assert))] public class OldAssertWithReflectionTest { #region IsSealed [Test] public void IsSealed() { OldReflectionAssert.IsSealed(typeof(SuccessClass)); } [Test] [ExpectedException(typeof(AssertionException))] public void IsSealedFail() { OldReflectionAssert.IsSealed(typeof(FailClass)); } #endregion #region HasConstructor [Test] public void HasConstructorNoParamter() { OldReflectionAssert.HasConstructor(typeof(SuccessClass)); } [Test] [ExpectedException(typeof(AssertionException))] public void HasConstructorNoParamterFail() { OldReflectionAssert.HasConstructor(typeof(FailClass)); } [Test] public void HasConstructorStringParamter() { OldReflectionAssert.HasConstructor(typeof(SuccessClass),typeof(string)); } [Test] [ExpectedException(typeof(AssertionException))] public void HasConstructorStringParameterFail() { OldReflectionAssert.HasConstructor(typeof(FailClass),typeof(string)); } [Test] public void HasConstructorPrivate() { OldReflectionAssert.HasConstructor(typeof(NoPublicConstructor), BindingFlags.Instance | BindingFlags.NonPublic); } #endregion #region HasDefaultConstructor [Test] public void HasDefaultConstructor() { OldReflectionAssert.HasDefaultConstructor(typeof(SuccessClass)); } [Test] [ExpectedException(typeof(AssertionException))] public void HasDefaultConstructorFail() { OldReflectionAssert.HasDefaultConstructor(typeof(FailClass)); } #endregion #region NotCreatable [Test] public void NotCreatable() { OldReflectionAssert.NotCreatable(typeof(NoPublicConstructor)); } [Test] [ExpectedException(typeof(AssertionException))] public void NotCreatableFail() { OldReflectionAssert.NotCreatable(typeof(SuccessClass)); } #endregion #region HasField [Test] public void HasField() { OldReflectionAssert.HasField(typeof(SuccessClass),"PublicField"); } [Test] [ExpectedException(typeof(AssertionException))] public void HasFieldFail() { OldReflectionAssert.HasField(typeof(FailClass), "PublicField"); } [Test] [ExpectedException(typeof(AssertionException))] public void HasPrivateFieldFail() { OldReflectionAssert.HasField(typeof(SuccessClass), "privateField"); } #endregion #region HasMethod [Test] public void HasMethod() { OldReflectionAssert.HasMethod(typeof(SuccessClass), "Method"); } [Test] public void HasMethodOneParameter() { OldReflectionAssert.HasMethod(typeof(SuccessClass), "Method",typeof(string)); } [Test] [ExpectedException(typeof(AssertionException))] public void HasMethodFail() { OldReflectionAssert.HasMethod(typeof(FailClass), "Method"); } [Test] [ExpectedException(typeof(AssertionException))] public void HasMethodOneParameterFail() { OldReflectionAssert.HasMethod(typeof(FailClass), "Method",typeof(string)); } #endregion #region IsAssignableFrom [Test] public void ObjectIsAssignableFromString() { OldReflectionAssert.IsAssignableFrom(typeof(Object), typeof(string)); } [Test] [ExpectedException(typeof(AssertionException))] public void StringIsNotAssignableFromObject() { OldReflectionAssert.IsAssignableFrom(typeof(string),typeof(Object)); } #endregion #region IsInstanceOf [Test] public void IsInstanceOf() { OldReflectionAssert.IsInstanceOf(typeof(string), "hello"); } [Test] [ExpectedException(typeof(AssertionException))] public void IsInstanceOfFail() { OldReflectionAssert.IsInstanceOf(typeof(string), 1); } #endregion #region ReadOnlyProperty [Test] public void ReadOnlyProperty() { OldReflectionAssert.ReadOnlyProperty(typeof(string), "Length"); } [Test] [ExpectedException(typeof(AssertionException))] public void ReadOnlyPropertyFail() { OldReflectionAssert.ReadOnlyProperty(typeof(SuccessClass), "Prop"); } #endregion #region dummy test classes internal class FailClass { public FailClass(int i) { } } internal class NoPublicConstructor { private NoPublicConstructor() { } } internal sealed class SuccessClass { public string PublicField = "public"; private string privateField = "private"; public SuccessClass() { } public SuccessClass(string s) { } public string Prop { get { return privateField; } set { } } public void Method() { } public void Method(string s) { } } #endregion } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== // // <OWNER>[....]</OWNER> using Microsoft.Win32; using Microsoft.Win32.SafeHandles; namespace System.Threading { using System; using System.Security; using System.Security.Permissions; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.ConstrainedExecution; using System.Runtime.Versioning; using System.Diagnostics.Contracts; using System.Diagnostics.Tracing; [System.Runtime.InteropServices.ComVisible(true)] public delegate void TimerCallback(Object state); // // TimerQueue maintains a list of active timers in this AppDomain. We use a single native timer, supplied by the VM, // to schedule all managed timers in the AppDomain. // // Perf assumptions: We assume that timers are created and destroyed frequently, but rarely actually fire. // There are roughly two types of timer: // // - timeouts for operations. These are created and destroyed very frequently, but almost never fire, because // the whole point is that the timer only fires if something has gone wrong. // // - scheduled background tasks. These typically do fire, but they usually have quite long durations. // So the impact of spending a few extra cycles to fire these is negligible. // // Because of this, we want to choose a data structure with very fast insert and delete times, but we can live // with linear traversal times when firing timers. // // The data structure we've chosen is an unordered doubly-linked list of active timers. This gives O(1) insertion // and removal, and O(N) traversal when finding expired timers. // // Note that all instance methods of this class require that the caller hold a lock on TimerQueue.Instance. // class TimerQueue { #region singleton pattern implementation // The one-and-only TimerQueue for the AppDomain. static TimerQueue s_queue = new TimerQueue(); public static TimerQueue Instance { get { return s_queue; } } private TimerQueue() { // empty private constructor to ensure we remain a singleton. } #endregion #region interface to native per-AppDomain timer // // We need to keep our notion of time synchronized with the calls to SleepEx that drive // the underlying native timer. In Win8, SleepEx does not count the time the machine spends // sleeping/hibernating. Environment.TickCount (GetTickCount) *does* count that time, // so we will get out of [....] with SleepEx if we use that method. // // So, on Win8, we use QueryUnbiasedInterruptTime instead; this does not count time spent // in sleep/hibernate mode. // private static int TickCount { [SecuritySafeCritical] get { // note: QueryUnbiasedInterruptTime is apparently not supported on CoreSystem currently. // Presumably this will be a problem. Will follow up with Windows team, but for now this is diabled // for CoreSystem builds. #if !FEATURE_PAL && !FEATURE_CORESYSTEM && !MONO if (Environment.IsWindows8OrAbove) { ulong time100ns; bool result = Win32Native.QueryUnbiasedInterruptTime(out time100ns); if (!result) throw Marshal.GetExceptionForHR(Marshal.GetLastWin32Error()); // convert to 100ns to milliseconds, and truncate to 32 bits. return (int)(uint)(time100ns / 10000); } else #endif //!FEATURE_PAL && !FEATURE_CORESYSTEM { return Environment.TickCount; } } } // // We use a SafeHandle to ensure that the native timer is destroyed when the AppDomain is unloaded. // [SecurityCritical] class AppDomainTimerSafeHandle : SafeHandleZeroOrMinusOneIsInvalid { public AppDomainTimerSafeHandle() : base(true) { } [SecurityCritical] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] protected override bool ReleaseHandle() { return DeleteAppDomainTimer(handle); } } [SecurityCritical] AppDomainTimerSafeHandle m_appDomainTimer; bool m_isAppDomainTimerScheduled; int m_currentAppDomainTimerStartTicks; uint m_currentAppDomainTimerDuration; [SecuritySafeCritical] private bool EnsureAppDomainTimerFiresBy(uint requestedDuration) { // // The VM's timer implementation does not work well for very long-duration timers. // See kb 950807. // So we'll limit our native timer duration to a "small" value. // This may cause us to attempt to fire timers early, but that's ok - // we'll just see that none of our timers has actually reached its due time, // and schedule the native timer again. // const uint maxPossibleDuration = 0x0fffffff; uint actualDuration = Math.Min(requestedDuration, maxPossibleDuration); if (m_isAppDomainTimerScheduled) { uint elapsed = (uint)(TickCount - m_currentAppDomainTimerStartTicks); if (elapsed >= m_currentAppDomainTimerDuration) return true; //the timer's about to fire uint remainingDuration = m_currentAppDomainTimerDuration - elapsed; if (actualDuration >= remainingDuration) return true; //the timer will fire earlier than this request } // If Pause is underway then do not schedule the timers // A later update during resume will re-schedule if(m_pauseTicks != 0) { Contract.Assert(!m_isAppDomainTimerScheduled); Contract.Assert(m_appDomainTimer == null); return true; } if (m_appDomainTimer == null || m_appDomainTimer.IsInvalid) { Contract.Assert(!m_isAppDomainTimerScheduled); m_appDomainTimer = CreateAppDomainTimer(actualDuration); if (!m_appDomainTimer.IsInvalid) { m_isAppDomainTimerScheduled = true; m_currentAppDomainTimerStartTicks = TickCount; m_currentAppDomainTimerDuration = actualDuration; return true; } else { return false; } } else { if (ChangeAppDomainTimer(m_appDomainTimer, actualDuration)) { m_isAppDomainTimerScheduled = true; m_currentAppDomainTimerStartTicks = TickCount; m_currentAppDomainTimerDuration = actualDuration; return true; } else { return false; } } } // // The VM calls this when the native timer fires. // [SecuritySafeCritical] internal static void AppDomainTimerCallback() { Instance.FireNextTimers(); } [System.Security.SecurityCritical] [ResourceExposure(ResourceScope.None)] [MethodImplAttribute(MethodImplOptions.InternalCall)] [SuppressUnmanagedCodeSecurity] static extern AppDomainTimerSafeHandle CreateAppDomainTimer(uint dueTime); [System.Security.SecurityCritical] [ResourceExposure(ResourceScope.None)] [MethodImplAttribute(MethodImplOptions.InternalCall)] [SuppressUnmanagedCodeSecurity] static extern bool ChangeAppDomainTimer(AppDomainTimerSafeHandle handle, uint dueTime); [System.Security.SecurityCritical] [ResourceExposure(ResourceScope.None)] [MethodImplAttribute(MethodImplOptions.InternalCall)] [SuppressUnmanagedCodeSecurity] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] static extern bool DeleteAppDomainTimer(IntPtr handle); #endregion #region Firing timers // // The list of timers // TimerQueueTimer m_timers; volatile int m_pauseTicks = 0; // Time when Pause was called [SecurityCritical] internal void Pause() { lock(this) { // Delete the native timer so that no timers are fired in the Pause zone if(m_appDomainTimer != null && !m_appDomainTimer.IsInvalid) { m_appDomainTimer.Dispose(); m_appDomainTimer = null; m_isAppDomainTimerScheduled = false; m_pauseTicks = TickCount; } } } [SecurityCritical] internal void Resume() { // // Update timers to adjust their due-time to accomodate Pause/Resume // lock (this) { // prevent ThreadAbort while updating state try { } finally { int pauseTicks = m_pauseTicks; m_pauseTicks = 0; // Set this to 0 so that now timers can be scheduled int resumedTicks = TickCount; int pauseDuration = resumedTicks - pauseTicks; bool haveTimerToSchedule = false; uint nextAppDomainTimerDuration = uint.MaxValue; TimerQueueTimer timer = m_timers; while (timer != null) { Contract.Assert(timer.m_dueTime != Timeout.UnsignedInfinite); Contract.Assert(resumedTicks >= timer.m_startTicks); uint elapsed; // How much of the timer dueTime has already elapsed // Timers started before the paused event has to be sufficiently delayed to accomodate // for the Pause time. However, timers started after the Paused event shouldnt be adjusted. // E.g. ones created by the app in its Activated event should fire when it was designated. // The Resumed event which is where this routine is executing is after this Activated and hence // shouldn't delay this timer if(timer.m_startTicks <= pauseTicks) elapsed = (uint)(pauseTicks - timer.m_startTicks); else elapsed = (uint)(resumedTicks - timer.m_startTicks); // Handling the corner cases where a Timer was already due by the time Resume is happening, // We shouldn't delay those timers. // Example is a timer started in App's Activated event with a very small duration timer.m_dueTime = (timer.m_dueTime > elapsed) ? timer.m_dueTime - elapsed : 0;; timer.m_startTicks = resumedTicks; // re-baseline if (timer.m_dueTime < nextAppDomainTimerDuration) { haveTimerToSchedule = true; nextAppDomainTimerDuration = timer.m_dueTime; } timer = timer.m_next; } if (haveTimerToSchedule) { EnsureAppDomainTimerFiresBy(nextAppDomainTimerDuration); } } } } // // Fire any timers that have expired, and update the native timer to schedule the rest of them. // private void FireNextTimers() { // // we fire the first timer on this thread; any other timers that might have fired are queued // to the ThreadPool. // TimerQueueTimer timerToFireOnThisThread = null; lock (this) { // prevent ThreadAbort while updating state try { } finally { // // since we got here, that means our previous timer has fired. // m_isAppDomainTimerScheduled = false; bool haveTimerToSchedule = false; uint nextAppDomainTimerDuration = uint.MaxValue; int nowTicks = TickCount; // // Sweep through all timers. The ones that have reached their due time // will fire. We will calculate the next native timer due time from the // other timers. // TimerQueueTimer timer = m_timers; while (timer != null) { Contract.Assert(timer.m_dueTime != Timeout.UnsignedInfinite); uint elapsed = (uint)(nowTicks - timer.m_startTicks); if (elapsed >= timer.m_dueTime) { // // Remember the next timer in case we delete this one // TimerQueueTimer nextTimer = timer.m_next; if (timer.m_period != Timeout.UnsignedInfinite) { timer.m_startTicks = nowTicks; timer.m_dueTime = timer.m_period; // // This is a repeating timer; schedule it to run again. // if (timer.m_dueTime < nextAppDomainTimerDuration) { haveTimerToSchedule = true; nextAppDomainTimerDuration = timer.m_dueTime; } } else { // // Not repeating; remove it from the queue // DeleteTimer(timer); } // // If this is the first timer, we'll fire it on this thread. Otherwise, queue it // to the ThreadPool. // if (timerToFireOnThisThread == null) timerToFireOnThisThread = timer; else QueueTimerCompletion(timer); timer = nextTimer; } else { // // This timer hasn't fired yet. Just update the next time the native timer fires. // uint remaining = timer.m_dueTime - elapsed; if (remaining < nextAppDomainTimerDuration) { haveTimerToSchedule = true; nextAppDomainTimerDuration = remaining; } timer = timer.m_next; } } if (haveTimerToSchedule) EnsureAppDomainTimerFiresBy(nextAppDomainTimerDuration); } } // // Fire the user timer outside of the lock! // if (timerToFireOnThisThread != null) timerToFireOnThisThread.Fire(); } [SecuritySafeCritical] private static void QueueTimerCompletion(TimerQueueTimer timer) { WaitCallback callback = s_fireQueuedTimerCompletion; if (callback == null) s_fireQueuedTimerCompletion = callback = new WaitCallback(FireQueuedTimerCompletion); // Can use "unsafe" variant because we take care of capturing and restoring // the ExecutionContext. ThreadPool.UnsafeQueueUserWorkItem(callback, timer); } private static WaitCallback s_fireQueuedTimerCompletion; private static void FireQueuedTimerCompletion(object state) { ((TimerQueueTimer)state).Fire(); } #endregion #region Queue implementation public bool UpdateTimer(TimerQueueTimer timer, uint dueTime, uint period) { if (timer.m_dueTime == Timeout.UnsignedInfinite) { // the timer is not in the list; add it (as the head of the list). timer.m_next = m_timers; timer.m_prev = null; if (timer.m_next != null) timer.m_next.m_prev = timer; m_timers = timer; } timer.m_dueTime = dueTime; timer.m_period = (period == 0) ? Timeout.UnsignedInfinite : period; timer.m_startTicks = TickCount; return EnsureAppDomainTimerFiresBy(dueTime); } public void DeleteTimer(TimerQueueTimer timer) { if (timer.m_dueTime != Timeout.UnsignedInfinite) { if (timer.m_next != null) timer.m_next.m_prev = timer.m_prev; if (timer.m_prev != null) timer.m_prev.m_next = timer.m_next; if (m_timers == timer) m_timers = timer.m_next; timer.m_dueTime = Timeout.UnsignedInfinite; timer.m_period = Timeout.UnsignedInfinite; timer.m_startTicks = 0; timer.m_prev = null; timer.m_next = null; } } #endregion } // // A timer in our TimerQueue. // sealed class TimerQueueTimer { // // All fields of this class are protected by a lock on TimerQueue.Instance. // // The first four fields are maintained by TimerQueue itself. // internal TimerQueueTimer m_next; internal TimerQueueTimer m_prev; // // The time, according to TimerQueue.TickCount, when this timer's current interval started. // internal int m_startTicks; // // Timeout.UnsignedInfinite if we are not going to fire. Otherwise, the offset from m_startTime when we will fire. // internal uint m_dueTime; // // Timeout.UnsignedInfinite if we are a single-shot timer. Otherwise, the repeat interval. // internal uint m_period; // // Info about the user's callback // readonly TimerCallback m_timerCallback; readonly Object m_state; readonly ExecutionContext m_executionContext; // // When Timer.Dispose(WaitHandle) is used, we need to signal the wait handle only // after all pending callbacks are complete. We set m_canceled to prevent any callbacks that // are already queued from running. We track the number of callbacks currently executing in // m_callbacksRunning. We set m_notifyWhenNoCallbacksRunning only when m_callbacksRunning // reaches zero. // int m_callbacksRunning; volatile bool m_canceled; volatile WaitHandle m_notifyWhenNoCallbacksRunning; [SecurityCritical] internal TimerQueueTimer(TimerCallback timerCallback, object state, uint dueTime, uint period, ref StackCrawlMark stackMark) { m_timerCallback = timerCallback; m_state = state; m_dueTime = Timeout.UnsignedInfinite; m_period = Timeout.UnsignedInfinite; if (!ExecutionContext.IsFlowSuppressed()) { m_executionContext = ExecutionContext.Capture( ref stackMark, ExecutionContext.CaptureOptions.IgnoreSyncCtx | ExecutionContext.CaptureOptions.OptimizeDefaultCase); } // // After the following statement, the timer may fire. No more manipulation of timer state outside of // the lock is permitted beyond this point! // if (dueTime != Timeout.UnsignedInfinite) Change(dueTime, period); } internal bool Change(uint dueTime, uint period) { bool success; lock (TimerQueue.Instance) { if (m_canceled) throw new ObjectDisposedException(null, Environment.GetResourceString("ObjectDisposed_Generic")); // prevent ThreadAbort while updating state try { } finally { m_period = period; if (dueTime == Timeout.UnsignedInfinite) { TimerQueue.Instance.DeleteTimer(this); success = true; } else { #if !FEATURE_CORECLR && !MONO if (FrameworkEventSource.IsInitialized && FrameworkEventSource.Log.IsEnabled(EventLevel.Informational, FrameworkEventSource.Keywords.ThreadTransfer)) FrameworkEventSource.Log.ThreadTransferSendObj(this, 1, string.Empty, true); #endif // !FEATURE_CORECLR success = TimerQueue.Instance.UpdateTimer(this, dueTime, period); } } } return success; } public void Close() { lock (TimerQueue.Instance) { // prevent ThreadAbort while updating state try { } finally { if (!m_canceled) { m_canceled = true; TimerQueue.Instance.DeleteTimer(this); } } } } public bool Close(WaitHandle toSignal) { bool success; bool shouldSignal = false; lock (TimerQueue.Instance) { // prevent ThreadAbort while updating state try { } finally { if (m_canceled) { success = false; } else { m_canceled = true; m_notifyWhenNoCallbacksRunning = toSignal; TimerQueue.Instance.DeleteTimer(this); if (m_callbacksRunning == 0) shouldSignal = true; success = true; } } } if (shouldSignal) SignalNoCallbacksRunning(); return success; } internal void Fire() { bool canceled = false; lock (TimerQueue.Instance) { // prevent ThreadAbort while updating state try { } finally { canceled = m_canceled; if (!canceled) m_callbacksRunning++; } } if (canceled) return; CallCallback(); bool shouldSignal = false; lock (TimerQueue.Instance) { // prevent ThreadAbort while updating state try { } finally { m_callbacksRunning--; if (m_canceled && m_callbacksRunning == 0 && m_notifyWhenNoCallbacksRunning != null) shouldSignal = true; } } if (shouldSignal) SignalNoCallbacksRunning(); } [SecuritySafeCritical] internal void SignalNoCallbacksRunning() { #if !MONO Win32Native.SetEvent(m_notifyWhenNoCallbacksRunning.SafeWaitHandle); #else NativeEventCalls.SetEvent_internal (m_notifyWhenNoCallbacksRunning.SafeWaitHandle.DangerousGetHandle ()); #endif } [SecuritySafeCritical] internal void CallCallback() { #if !FEATURE_CORECLR && !MONO if (FrameworkEventSource.IsInitialized && FrameworkEventSource.Log.IsEnabled(EventLevel.Informational, FrameworkEventSource.Keywords.ThreadTransfer)) FrameworkEventSource.Log.ThreadTransferReceiveObj(this, 1, string.Empty); #endif // !FEATURE_CORECLR // call directly if EC flow is suppressed if (m_executionContext == null) { m_timerCallback(m_state); } else { using (ExecutionContext executionContext = m_executionContext.IsPreAllocatedDefault ? m_executionContext : m_executionContext.CreateCopy()) { ContextCallback callback = s_callCallbackInContext; if (callback == null) s_callCallbackInContext = callback = new ContextCallback(CallCallbackInContext); ExecutionContext.Run( executionContext, callback, this, // state true); // ignoreSyncCtx } } } [SecurityCritical] private static ContextCallback s_callCallbackInContext; [SecurityCritical] private static void CallCallbackInContext(object state) { TimerQueueTimer t = (TimerQueueTimer)state; t.m_timerCallback(t.m_state); } } // // TimerHolder serves as an intermediary between Timer and TimerQueueTimer, releasing the TimerQueueTimer // if the Timer is collected. // This is necessary because Timer itself cannot use its finalizer for this purpose. If it did, // then users could control timer lifetimes using GC.SuppressFinalize/ReRegisterForFinalize. // You might ask, wouldn't that be a good thing? Maybe (though it would be even better to offer this // via first-class APIs), but Timer has never offered this, and adding it now would be a breaking // change, because any code that happened to be suppressing finalization of Timer objects would now // unwittingly be changing the lifetime of those timers. // sealed class TimerHolder { internal TimerQueueTimer m_timer; public TimerHolder(TimerQueueTimer timer) { m_timer = timer; } ~TimerHolder() { // // If shutdown has started, another thread may be suspended while holding the timer lock. // So we can't safely close the timer. // // Similarly, we should not close the timer during AD-unload's live-object finalization phase. // A rude abort may have prevented us from releasing the lock. // // Note that in either case, the Timer still won't fire, because ThreadPool threads won't be // allowed to run in this AppDomain. // if (Environment.HasShutdownStarted || AppDomain.CurrentDomain.IsFinalizingForUnload()) return; m_timer.Close(); } public void Close() { m_timer.Close(); GC.SuppressFinalize(this); } public bool Close(WaitHandle notifyObject) { bool result = m_timer.Close(notifyObject); GC.SuppressFinalize(this); return result; } } [HostProtection(Synchronization=true, ExternalThreading=true)] [System.Runtime.InteropServices.ComVisible(true)] #if FEATURE_REMOTING public sealed class Timer : MarshalByRefObject, IDisposable #else // FEATURE_REMOTING public sealed class Timer : IDisposable #endif // FEATURE_REMOTING { private const UInt32 MAX_SUPPORTED_TIMEOUT = (uint)0xfffffffe; private TimerHolder m_timer; [SecuritySafeCritical] [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable public Timer(TimerCallback callback, Object state, int dueTime, int period) { if (dueTime < -1) throw new ArgumentOutOfRangeException("dueTime", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1")); if (period < -1 ) throw new ArgumentOutOfRangeException("period", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1")); Contract.EndContractBlock(); StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; TimerSetup(callback,state,(UInt32)dueTime,(UInt32)period,ref stackMark); } [SecuritySafeCritical] [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable public Timer(TimerCallback callback, Object state, TimeSpan dueTime, TimeSpan period) { long dueTm = (long)dueTime.TotalMilliseconds; if (dueTm < -1) throw new ArgumentOutOfRangeException("dueTm",Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1")); if (dueTm > MAX_SUPPORTED_TIMEOUT) throw new ArgumentOutOfRangeException("dueTm",Environment.GetResourceString("ArgumentOutOfRange_TimeoutTooLarge")); long periodTm = (long)period.TotalMilliseconds; if (periodTm < -1) throw new ArgumentOutOfRangeException("periodTm",Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1")); if (periodTm > MAX_SUPPORTED_TIMEOUT) throw new ArgumentOutOfRangeException("periodTm",Environment.GetResourceString("ArgumentOutOfRange_PeriodTooLarge")); StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; TimerSetup(callback,state,(UInt32)dueTm,(UInt32)periodTm,ref stackMark); } [CLSCompliant(false)] [SecuritySafeCritical] [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable public Timer(TimerCallback callback, Object state, UInt32 dueTime, UInt32 period) { StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; TimerSetup(callback,state,dueTime,period,ref stackMark); } [SecuritySafeCritical] [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable public Timer(TimerCallback callback, Object state, long dueTime, long period) { if (dueTime < -1) throw new ArgumentOutOfRangeException("dueTime",Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1")); if (period < -1) throw new ArgumentOutOfRangeException("period",Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1")); if (dueTime > MAX_SUPPORTED_TIMEOUT) throw new ArgumentOutOfRangeException("dueTime",Environment.GetResourceString("ArgumentOutOfRange_TimeoutTooLarge")); if (period > MAX_SUPPORTED_TIMEOUT) throw new ArgumentOutOfRangeException("period",Environment.GetResourceString("ArgumentOutOfRange_PeriodTooLarge")); Contract.EndContractBlock(); StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; TimerSetup(callback,state,(UInt32) dueTime, (UInt32) period,ref stackMark); } [SecuritySafeCritical] [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable public Timer(TimerCallback callback) { int dueTime = -1; // we want timer to be registered, but not activated. Requires caller to call int period = -1; // Change after a timer instance is created. This is to avoid the potential // for a timer to be fired before the returned value is assigned to the variable, // potentially causing the callback to reference a bogus value (if passing the timer to the callback). StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; TimerSetup(callback, this, (UInt32)dueTime, (UInt32)period, ref stackMark); } [SecurityCritical] private void TimerSetup(TimerCallback callback, Object state, UInt32 dueTime, UInt32 period, ref StackCrawlMark stackMark) { if (callback == null) throw new ArgumentNullException("TimerCallback"); Contract.EndContractBlock(); m_timer = new TimerHolder(new TimerQueueTimer(callback, state, dueTime, period, ref stackMark)); } [SecurityCritical] internal static void Pause() { TimerQueue.Instance.Pause(); } [SecurityCritical] internal static void Resume() { TimerQueue.Instance.Resume(); } public bool Change(int dueTime, int period) { if (dueTime < -1 ) throw new ArgumentOutOfRangeException("dueTime",Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1")); if (period < -1) throw new ArgumentOutOfRangeException("period",Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1")); Contract.EndContractBlock(); return m_timer.m_timer.Change((UInt32)dueTime, (UInt32)period); } public bool Change(TimeSpan dueTime, TimeSpan period) { return Change((long) dueTime.TotalMilliseconds, (long) period.TotalMilliseconds); } [CLSCompliant(false)] public bool Change(UInt32 dueTime, UInt32 period) { return m_timer.m_timer.Change(dueTime, period); } public bool Change(long dueTime, long period) { if (dueTime < -1 ) throw new ArgumentOutOfRangeException("dueTime", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1")); if (period < -1) throw new ArgumentOutOfRangeException("period", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1")); if (dueTime > MAX_SUPPORTED_TIMEOUT) throw new ArgumentOutOfRangeException("dueTime", Environment.GetResourceString("ArgumentOutOfRange_TimeoutTooLarge")); if (period > MAX_SUPPORTED_TIMEOUT) throw new ArgumentOutOfRangeException("period", Environment.GetResourceString("ArgumentOutOfRange_PeriodTooLarge")); Contract.EndContractBlock(); return m_timer.m_timer.Change((UInt32)dueTime, (UInt32)period); } public bool Dispose(WaitHandle notifyObject) { if (notifyObject==null) throw new ArgumentNullException("notifyObject"); Contract.EndContractBlock(); return m_timer.Close(notifyObject); } public void Dispose() { m_timer.Close(); } internal void KeepRootedWhileScheduled() { GC.SuppressFinalize(m_timer); } } }
using System; using System.Runtime.CompilerServices; using Svelto.Common; namespace Svelto.ECS.DataStructures { //Necessary to be sure that the user won't pass random values public struct UnsafeArrayIndex { internal uint index; } /// <summary> /// Note: this must work inside burst, so it must follow burst restrictions /// It's a typeless native queue based on a ring-buffer model. This means that the writing head and the /// reading head always advance independently. If there is enough space left by dequeued elements, /// the writing head will wrap around if it reaches the end of the array. The writing head cannot ever surpass the reading head. /// /// </summary> struct UnsafeBlob : IDisposable { internal unsafe byte* ptr { get; set; } //expressed in bytes internal uint capacity { get; private set; } //expressed in bytes internal uint size { get { var currentSize = (uint) _writeIndex - _readIndex; #if DEBUG && !PROFILE_SVELTO if ((currentSize & (4 - 1)) != 0) throw new Exception("size is expected to be a multiple of 4"); #endif return currentSize; } } //expressed in bytes internal uint availableSpace => capacity - size; /// <summary> /// </summary> internal Allocator allocator; [MethodImpl(MethodImplOptions.AggressiveInlining)] internal void Enqueue<T>(in T item) where T : struct { unsafe { var structSize = (uint) MemoryUtilities.SizeOf<T>(); var writeHead = _writeIndex % capacity; #if DEBUG && !PROFILE_SVELTO var size = _writeIndex - _readIndex; var spaceAvailable = capacity - size; if (spaceAvailable - (int) structSize < 0) throw new Exception("no writing authorized"); if ((writeHead & (4 - 1)) != 0) throw new Exception("write head is expected to be a multiple of 4"); #endif if (writeHead + structSize <= capacity) { Unsafe.Write(ptr + writeHead, item); } else //copy with wrap, will start to copy and wrap for the remainder { var byteCountToEnd = capacity - writeHead; var localCopyToAvoidGcIssues = item; //read and copy the first portion of Item until the end of the stream Unsafe.CopyBlock(ptr + writeHead, Unsafe.AsPointer(ref localCopyToAvoidGcIssues) , (uint) byteCountToEnd); var restCount = structSize - byteCountToEnd; //read and copy the remainder Unsafe.CopyBlock(ptr, (byte*) Unsafe.AsPointer(ref localCopyToAvoidGcIssues) + byteCountToEnd , (uint) restCount); } //this is may seems a waste if you are going to use an unsafeBlob just for bytes, but it's necessary for mixed types. //it's still possible to use WriteUnaligned though uint paddedStructSize = (uint) (structSize + (int) MemoryUtilities.Pad4(structSize)); _writeIndex += paddedStructSize; //we want _writeIndex to be always aligned by 4 } } [MethodImpl(MethodImplOptions.AggressiveInlining)] //The index returned is the index of the unwrapped ring. It must be wrapped again before to be used internal ref T Reserve<T>(out UnsafeArrayIndex index) where T : struct { unsafe { var structSize = (uint) MemoryUtilities.SizeOf<T>(); var wrappedIndex = _writeIndex % capacity; #if DEBUG && !PROFILE_SVELTO var size = _writeIndex - _readIndex; var spaceAvailable = capacity - size; if (spaceAvailable - (int) structSize < 0) throw new Exception("no writing authorized"); if ((wrappedIndex & (4 - 1)) != 0) throw new Exception("write head is expected to be a multiple of 4"); #endif ref var buffer = ref Unsafe.AsRef<T>(ptr + wrappedIndex); index.index = _writeIndex; _writeIndex += structSize + MemoryUtilities.Pad4(structSize); return ref buffer; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal ref T AccessReserved<T>(UnsafeArrayIndex index) where T : struct { unsafe { var wrappedIndex = index.index % capacity; #if DEBUG && !PROFILE_SVELTO if ((index.index & 3) != 0) throw new Exception($"invalid index detected"); #endif return ref Unsafe.AsRef<T>(ptr + wrappedIndex); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal T Dequeue<T>() where T : struct { unsafe { var structSize = (uint) MemoryUtilities.SizeOf<T>(); var readHead = _readIndex % capacity; #if DEBUG && !PROFILE_SVELTO var size = _writeIndex - _readIndex; if (size < structSize) //are there enough bytes to read? throw new Exception("dequeuing empty queue or unexpected type dequeued"); if (_readIndex > _writeIndex) throw new Exception("unexpected read"); if ((readHead & (4 - 1)) != 0) throw new Exception("read head is expected to be a multiple of 4"); #endif var paddedStructSize = structSize + MemoryUtilities.Pad4(structSize); _readIndex += paddedStructSize; if (_readIndex == _writeIndex) { //resetting the Indices has the benefit to let the Reserve work in more occasions and //the rapping happening less often. If the _readIndex reached the _writeIndex, it means //that there is no data left to read, so we can start to write again from the begin of the memory _writeIndex = 0; _readIndex = 0; } if (readHead + paddedStructSize <= capacity) return Unsafe.Read<T>(ptr + readHead); //handle the case the structure wraps around so it must be reconstructed from the part at the //end of the stream and the part starting from the begin. T item = default; var byteCountToEnd = capacity - readHead; Unsafe.CopyBlock(Unsafe.AsPointer(ref item), ptr + readHead, byteCountToEnd); var restCount = structSize - byteCountToEnd; Unsafe.CopyBlock((byte*) Unsafe.AsPointer(ref item) + byteCountToEnd, ptr, restCount); return item; } } /// <summary> /// This version of Realloc unwraps a queue, but doesn't change the unwrapped index of existing elements. /// In this way the previously indices will remain valid /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] internal void Realloc(uint newCapacity) { unsafe { //be sure it's multiple of 4. Assuming that what we write is aligned to 4, then we will always have aligned wrapped heads. //the reading and writing head always increment in multiple of 4 newCapacity += MemoryUtilities.Pad4(newCapacity); byte* newPointer = null; #if DEBUG && !PROFILE_SVELTO if (newCapacity <= capacity) throw new Exception("new capacity must be bigger than current"); #endif newPointer = (byte*) MemoryUtilities.Alloc(newCapacity, allocator); //copy wrapped content if there is any var currentSize = _writeIndex - _readIndex; if (currentSize > 0) { var oldReaderHead = _readIndex % capacity; var writerHead = _writeIndex % capacity; //there was no wrapping if (oldReaderHead < writerHead) { var newReaderHead = _readIndex % newCapacity; Unsafe.CopyBlock(newPointer + newReaderHead, ptr + oldReaderHead, (uint) currentSize); } else { var byteCountToEnd = capacity - oldReaderHead; var newReaderHead = _readIndex % newCapacity; #if DEBUG && !PROFILE_SVELTO if (newReaderHead + byteCountToEnd + writerHead > newCapacity) throw new Exception("something is wrong with my previous assumptions"); #endif Unsafe.CopyBlock(newPointer + newReaderHead, ptr + oldReaderHead, byteCountToEnd); //from the old reader head to the end of the old array Unsafe.CopyBlock(newPointer + newReaderHead + byteCountToEnd, ptr + 0, (uint) writerHead); //from the begin of the old array to the old writer head (rember the writerHead wrapped) } } if (ptr != null) MemoryUtilities.Free((IntPtr) ptr, allocator); ptr = newPointer; capacity = newCapacity; //_readIndex = 0; readIndex won't change to keep the previous reserved indices valid _writeIndex = _readIndex + currentSize; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Dispose() { unsafe { if (ptr != null) MemoryUtilities.Free((IntPtr) ptr, allocator); ptr = null; _writeIndex = 0; capacity = 0; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Clear() { _writeIndex = 0; _readIndex = 0; } uint _writeIndex; uint _readIndex; } }
using System; using System.Collections.Generic; namespace Snowflake.Service.HttpServer { public static class MimeTypes { private static readonly Dictionary<string, string> TypeMap; static MimeTypes() { MimeTypes.TypeMap = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase){ {"323", "text/h323"}, {"3dmf", "x-world/x-3dmf"}, {"3dm", "x-world/x-3dmf"}, {"3g2", "video/3gpp2"}, {"3gp", "video/3gpp"}, {"7z", "application/x-7z-compressed"}, {"aab", "application/x-authorware-bin"}, {"aac", "audio/aac"}, {"aam", "application/x-authorware-map"}, {"aas", "application/x-authorware-seg"}, {"abc", "text/vnd.abc"}, {"acgi", "text/html"}, {"acx", "application/internet-property-stream"}, {"afl", "video/animaflex"}, {"ai", "application/postscript"}, {"aif", "audio/aiff"}, {"aifc", "audio/aiff"}, {"aiff", "audio/aiff"}, {"aim", "application/x-aim"}, {"aip", "text/x-audiosoft-intra"}, {"ani", "application/x-navi-animation"}, {"aos", "application/x-nokia-9000-communicator-add-on-software"}, {"appcache", "text/cache-manifest"}, {"application", "application/x-ms-application"}, {"aps", "application/mime"}, {"art", "image/x-jg"}, {"asf", "video/x-ms-asf"}, {"asm", "text/x-asm"}, {"asp", "text/asp"}, {"asr", "video/x-ms-asf"}, {"asx", "application/x-mplayer2"}, {"atom", "application/atom+xml"}, {"au", "audio/x-au"}, {"avi", "video/avi"}, {"avs", "video/avs-video"}, {"axs", "application/olescript"}, {"bas", "text/plain"}, {"bcpio", "application/x-bcpio"}, {"bin", "application/octet-stream"}, {"bm", "image/bmp"}, {"bmp", "image/bmp"}, {"boo", "application/book"}, {"book", "application/book"}, {"boz", "application/x-bzip2"}, {"bsh", "application/x-bsh"}, {"bz2", "application/x-bzip2"}, {"bz", "application/x-bzip"}, {"cat", "application/vnd.ms-pki.seccat"}, {"ccad", "application/clariscad"}, {"cco", "application/x-cocoa"}, {"cc", "text/plain"}, {"cdf", "application/cdf"}, {"cer", "application/pkix-cert"}, {"cha", "application/x-chat"}, {"chat", "application/x-chat"}, {"class", "application/x-java-applet"}, {"clp", "application/x-msclip"}, {"cmx", "image/x-cmx"}, {"cod", "image/cis-cod"}, {"coffee", "text/x-coffeescript"}, {"conf", "text/plain"}, {"cpio", "application/x-cpio"}, {"cpp", "text/plain"}, {"cpt", "application/x-cpt"}, {"crd", "application/x-mscardfile"}, {"crl", "application/pkix-crl"}, {"crt", "application/pkix-cert"}, {"csh", "application/x-csh"}, {"css", "text/css"}, {"c", "text/plain"}, {"c++", "text/plain"}, {"cxx", "text/plain"}, {"dart", "application/dart"}, {"dcr", "application/x-director"}, {"deb", "application/x-deb"}, {"deepv", "application/x-deepv"}, {"def", "text/plain"}, {"deploy", "application/octet-stream"}, {"der", "application/x-x509-ca-cert"}, {"dib", "image/bmp"}, {"dif", "video/x-dv"}, {"dir", "application/x-director"}, {"disco", "text/xml"}, {"dll", "application/x-msdownload"}, {"dl", "video/dl"}, {"doc", "application/msword"}, {"docm", "application/vnd.ms-word.document.macroEnabled.12"}, {"docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"}, {"dot", "application/msword"}, {"dotm", "application/vnd.ms-word.template.macroEnabled.12"}, {"dotx", "application/vnd.openxmlformats-officedocument.wordprocessingml.template"}, {"dp", "application/commonground"}, {"drw", "application/drafting"}, {"dtd", "application/xml-dtd"}, {"dvi", "application/x-dvi"}, {"dv", "video/x-dv"}, {"dwf", "drawing/x-dwf {old)"}, {"dwg", "application/acad"}, {"dxf", "application/dxf"}, {"dxr", "application/x-director"}, {"elc", "application/x-elc"}, {"el", "text/x-script.elisp"}, {"eml", "message/rfc822"}, {"eot", "application/vnd.bw-fontobject"}, {"eps", "application/postscript"}, {"es", "application/x-esrehber"}, {"etx", "text/x-setext"}, {"evy", "application/envoy"}, {"exe", "application/octet-stream"}, {"f77", "text/plain"}, {"f90", "text/plain"}, {"fdf", "application/vnd.fdf"}, {"fif", "image/fif"}, {"flac", "audio/x-flac"}, {"fli", "video/fli"}, {"flo", "image/florian"}, {"flr", "x-world/x-vrml"}, {"flx", "text/vnd.fmi.flexstor"}, {"fmf", "video/x-atomic3d-feature"}, {"for", "text/plain"}, {"fpx", "image/vnd.fpx"}, {"frl", "application/freeloader"}, {"f", "text/plain"}, {"funk", "audio/make"}, {"g3", "image/g3fax"}, {"gif", "image/gif"}, {"gl", "video/gl"}, {"gsd", "audio/x-gsm"}, {"gsm", "audio/x-gsm"}, {"gsp", "application/x-gsp"}, {"gss", "application/x-gss"}, {"gtar", "application/x-gtar"}, {"g", "text/plain"}, {"gz", "application/x-gzip"}, {"gzip", "application/x-gzip"}, {"hdf", "application/x-hdf"}, {"help", "application/x-helpfile"}, {"hgl", "application/vnd.hp-HPGL"}, {"hh", "text/plain"}, {"hlb", "text/x-script"}, {"hlp", "application/x-helpfile"}, {"hpg", "application/vnd.hp-HPGL"}, {"hpgl", "application/vnd.hp-HPGL"}, {"hqx", "application/binhex"}, {"hta", "application/hta"}, {"htc", "text/x-component"}, {"h", "text/plain"}, {"htmls", "text/html"}, {"html", "text/html"}, {"htm", "text/html"}, {"htt", "text/webviewhtml"}, {"htx", "text/html"}, {"ice", "x-conference/x-cooltalk"}, {"ico", "image/x-icon"}, {"ics", "text/calendar"}, {"idc", "text/plain"}, {"ief", "image/ief"}, {"iefs", "image/ief"}, {"iges", "application/iges"}, {"igs", "application/iges"}, {"iii", "application/x-iphone"}, {"ima", "application/x-ima"}, {"imap", "application/x-httpd-imap"}, {"inf", "application/inf"}, {"ins", "application/x-internett-signup"}, {"ip", "application/x-ip2"}, {"isp", "application/x-internet-signup"}, {"isu", "video/x-isvideo"}, {"it", "audio/it"}, {"iv", "application/x-inventor"}, {"ivf", "video/x-ivf"}, {"ivr", "i-world/i-vrml"}, {"ivy", "application/x-livescreen"}, {"jam", "audio/x-jam"}, {"jar", "application/java-archive"}, {"java", "text/plain"}, {"jav", "text/plain"}, {"jcm", "application/x-java-commerce"}, {"jfif", "image/jpeg"}, {"jfif-tbnl", "image/jpeg"}, {"jpeg", "image/jpeg"}, {"jpe", "image/jpeg"}, {"jpg", "image/jpeg"}, {"jps", "image/x-jps"}, {"js", "application/javascript"}, {"json", "application/json"}, {"jut", "image/jutvision"}, {"kar", "audio/midi"}, {"ksh", "text/x-script.ksh"}, {"la", "audio/nspaudio"}, {"lam", "audio/x-liveaudio"}, {"latex", "application/x-latex"}, {"list", "text/plain"}, {"lma", "audio/nspaudio"}, {"log", "text/plain"}, {"lsp", "application/x-lisp"}, {"lst", "text/plain"}, {"lsx", "text/x-la-asf"}, {"ltx", "application/x-latex"}, {"m13", "application/x-msmediaview"}, {"m14", "application/x-msmediaview"}, {"m1v", "video/mpeg"}, {"m2a", "audio/mpeg"}, {"m2v", "video/mpeg"}, {"m3u", "audio/x-mpequrl"}, {"m4a", "audio/mp4"}, {"m4v", "video/mp4"}, {"man", "application/x-troff-man"}, {"manifest", "application/x-ms-manifest"}, {"map", "application/x-navimap"}, {"mar", "text/plain"}, {"mbd", "application/mbedlet"}, {"mc$", "application/x-magic-cap-package-1.0"}, {"mcd", "application/mcad"}, {"mcf", "image/vasa"}, {"mcp", "application/netmc"}, {"mdb", "application/x-msaccess"}, {"mesh", "model/mesh"}, {"me", "application/x-troff-me"}, {"mid", "audio/midi"}, {"midi", "audio/midi"}, {"mif", "application/x-mif"}, {"mjf", "audio/x-vnd.AudioExplosion.MjuiceMediaFile"}, {"mjpg", "video/x-motion-jpeg"}, {"mm", "application/base64"}, {"mme", "application/base64"}, {"mny", "application/x-msmoney"}, {"mod", "audio/mod"}, {"mov", "video/quicktime"}, {"movie", "video/x-sgi-movie"}, {"mp2", "video/mpeg"}, {"mp3", "audio/mpeg"}, {"mp4", "video/mp4"}, {"mp4a", "audio/mp4"}, {"mp4v", "video/mp4"}, {"mpa", "audio/mpeg"}, {"mpc", "application/x-project"}, {"mpeg", "video/mpeg"}, {"mpe", "video/mpeg"}, {"mpga", "audio/mpeg"}, {"mpg", "video/mpeg"}, {"mpp", "application/vnd.ms-project"}, {"mpt", "application/x-project"}, {"mpv2", "video/mpeg"}, {"mpv", "application/x-project"}, {"mpx", "application/x-project"}, {"mrc", "application/marc"}, {"ms", "application/x-troff-ms"}, {"msh", "model/mesh"}, {"m", "text/plain"}, {"mvb", "application/x-msmediaview"}, {"mv", "video/x-sgi-movie"}, {"my", "audio/make"}, {"mzz", "application/x-vnd.AudioExplosion.mzz"}, {"nap", "image/naplps"}, {"naplps", "image/naplps"}, {"nc", "application/x-netcdf"}, {"ncm", "application/vnd.nokia.configuration-message"}, {"niff", "image/x-niff"}, {"nif", "image/x-niff"}, {"nix", "application/x-mix-transfer"}, {"nsc", "application/x-conference"}, {"nvd", "application/x-navidoc"}, {"nws", "message/rfc822"}, {"oda", "application/oda"}, {"ods", "application/oleobject"}, {"oga", "audio/ogg"}, {"ogg", "audio/ogg"}, {"ogv", "video/ogg"}, {"ogx", "application/ogg"}, {"omc", "application/x-omc"}, {"omcd", "application/x-omcdatamaker"}, {"omcr", "application/x-omcregerator"}, {"opus", "audio/ogg"}, {"oxps", "application/oxps"}, {"p10", "application/pkcs10"}, {"p12", "application/pkcs-12"}, {"p7a", "application/x-pkcs7-signature"}, {"p7b", "application/x-pkcs7-certificates"}, {"p7c", "application/pkcs7-mime"}, {"p7m", "application/pkcs7-mime"}, {"p7r", "application/x-pkcs7-certreqresp"}, {"p7s", "application/pkcs7-signature"}, {"part", "application/pro_eng"}, {"pas", "text/pascal"}, {"pbm", "image/x-portable-bitmap"}, {"pcl", "application/x-pcl"}, {"pct", "image/x-pict"}, {"pcx", "image/x-pcx"}, {"pdb", "chemical/x-pdb"}, {"pdf", "application/pdf"}, {"pfunk", "audio/make"}, {"pfx", "application/x-pkcs12"}, {"pgm", "image/x-portable-graymap"}, {"pic", "image/pict"}, {"pict", "image/pict"}, {"pkg", "application/x-newton-compatible-pkg"}, {"pko", "application/vnd.ms-pki.pko"}, {"pl", "text/plain"}, {"plx", "application/x-PiXCLscript"}, {"pm4", "application/x-pagemaker"}, {"pm5", "application/x-pagemaker"}, {"pma", "application/x-perfmon"}, {"pmc", "application/x-perfmon"}, {"pm", "image/x-xpixmap"}, {"pml", "application/x-perfmon"}, {"pmr", "application/x-perfmon"}, {"pmw", "application/x-perfmon"}, {"png", "image/png"}, {"pnm", "application/x-portable-anymap"}, {"pot", "application/vnd.ms-powerpoint"}, {"potm", "application/vnd.ms-powerpoint.template.macroEnabled.12"}, {"potx", "application/vnd.openxmlformats-officedocument.presentationml.template"}, {"pov", "model/x-pov"}, {"ppa", "application/vnd.ms-powerpoint"}, {"ppam", "application/vnd.ms-powerpoint.addin.macroEnabled.12"}, {"ppm", "image/x-portable-pixmap"}, {"pps", "application/vnd.ms-powerpoint"}, {"ppsm", "application/vnd.ms-powerpoint.slideshow.macroEnabled.12"}, {"ppsx", "application/vnd.openxmlformats-officedocument.presentationml.slideshow"}, {"ppt", "application/vnd.ms-powerpoint"}, {"pptm", "application/vnd.ms-powerpoint.presentation.macroEnabled.12"}, {"pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation"}, {"ppz", "application/mspowerpoint"}, {"pre", "application/x-freelance"}, {"prf", "application/pics-rules"}, {"prt", "application/pro_eng"}, {"ps", "application/postscript"}, {"p", "text/x-pascal"}, {"pub", "application/x-mspublisher"}, {"pvu", "paleovu/x-pv"}, {"pwz", "application/vnd.ms-powerpoint"}, {"pyc", "applicaiton/x-bytecode.python"}, {"py", "text/x-script.phyton"}, {"qcp", "audio/vnd.qcelp"}, {"qd3d", "x-world/x-3dmf"}, {"qd3", "x-world/x-3dmf"}, {"qif", "image/x-quicktime"}, {"qtc", "video/x-qtc"}, {"qtif", "image/x-quicktime"}, {"qti", "image/x-quicktime"}, {"qt", "video/quicktime"}, {"ra", "audio/x-pn-realaudio"}, {"ram", "audio/x-pn-realaudio"}, {"ras", "application/x-cmu-raster"}, {"rast", "image/cmu-raster"}, {"rexx", "text/x-script.rexx"}, {"rf", "image/vnd.rn-realflash"}, {"rgb", "image/x-rgb"}, {"rm", "application/vnd.rn-realmedia"}, {"rmi", "audio/mid"}, {"rmm", "audio/x-pn-realaudio"}, {"rmp", "audio/x-pn-realaudio"}, {"rng", "application/ringing-tones"}, {"rnx", "application/vnd.rn-realplayer"}, {"roff", "application/x-troff"}, {"rp", "image/vnd.rn-realpix"}, {"rpm", "audio/x-pn-realaudio-plugin"}, {"rss", "application/rss+xml"}, {"rtf", "text/richtext"}, {"rt", "text/richtext"}, {"rtx", "text/richtext"}, {"rv", "video/vnd.rn-realvideo"}, {"s3m", "audio/s3m"}, {"sbk", "application/x-tbook"}, {"scd", "application/x-msschedule"}, {"scm", "application/x-lotusscreencam"}, {"sct", "text/scriptlet"}, {"sdml", "text/plain"}, {"sdp", "application/sdp"}, {"sdr", "application/sounder"}, {"sea", "application/sea"}, {"set", "application/set"}, {"setpay", "application/set-payment-initiation"}, {"setreg", "application/set-registration-initiation"}, {"sgml", "text/sgml"}, {"sgm", "text/sgml"}, {"shar", "application/x-bsh"}, {"sh", "text/x-script.sh"}, {"shtml", "text/html"}, {"sid", "audio/x-psid"}, {"silo", "model/mesh"}, {"sit", "application/x-sit"}, {"skd", "application/x-koan"}, {"skm", "application/x-koan"}, {"skp", "application/x-koan"}, {"skt", "application/x-koan"}, {"sl", "application/x-seelogo"}, {"smi", "application/smil"}, {"smil", "application/smil"}, {"snd", "audio/basic"}, {"sol", "application/solids"}, {"spc", "application/x-pkcs7-certificates"}, {"spl", "application/futuresplash"}, {"spr", "application/x-sprite"}, {"sprite", "application/x-sprite"}, {"spx", "audio/ogg"}, {"src", "application/x-wais-source"}, {"ssi", "text/x-server-parsed-html"}, {"ssm", "application/streamingmedia"}, {"sst", "application/vnd.ms-pki.certstore"}, {"step", "application/step"}, {"s", "text/x-asm"}, {"stl", "application/sla"}, {"stm", "text/html"}, {"stp", "application/step"}, {"sv4cpio", "application/x-sv4cpio"}, {"sv4crc", "application/x-sv4crc"}, {"svf", "image/x-dwg"}, {"svg", "image/svg+xml"}, {"svr", "application/x-world"}, {"swf", "application/x-shockwave-flash"}, {"talk", "text/x-speech"}, {"t", "application/x-troff"}, {"tar", "application/x-tar"}, {"tbk", "application/toolbook"}, {"tcl", "text/x-script.tcl"}, {"tcsh", "text/x-script.tcsh"}, {"tex", "application/x-tex"}, {"texi", "application/x-texinfo"}, {"texinfo", "application/x-texinfo"}, {"text", "text/plain"}, {"tgz", "application/x-compressed"}, {"tiff", "image/tiff"}, {"tif", "image/tiff"}, {"tr", "application/x-troff"}, {"trm", "application/x-msterminal"}, {"ts", "text/x-typescript"}, {"tsi", "audio/tsp-audio"}, {"tsp", "audio/tsplayer"}, {"tsv", "text/tab-separated-values"}, {"ttf", "application/x-font-ttf"}, {"turbot", "image/florian"}, {"txt", "text/plain"}, {"uil", "text/x-uil"}, {"uls", "text/iuls"}, {"unis", "text/uri-list"}, {"uni", "text/uri-list"}, {"unv", "application/i-deas"}, {"uris", "text/uri-list"}, {"uri", "text/uri-list"}, {"ustar", "multipart/x-ustar"}, {"uue", "text/x-uuencode"}, {"uu", "text/x-uuencode"}, {"vcd", "application/x-cdlink"}, {"vcf", "text/vcard"}, {"vcard", "text/vcard"}, {"vcs", "text/x-vCalendar"}, {"vda", "application/vda"}, {"vdo", "video/vdo"}, {"vew", "application/groupwise"}, {"vivo", "video/vivo"}, {"viv", "video/vivo"}, {"vmd", "application/vocaltec-media-desc"}, {"vmf", "application/vocaltec-media-file"}, {"voc", "audio/voc"}, {"vos", "video/vosaic"}, {"vox", "audio/voxware"}, {"vqe", "audio/x-twinvq-plugin"}, {"vqf", "audio/x-twinvq"}, {"vql", "audio/x-twinvq-plugin"}, {"vrml", "application/x-vrml"}, {"vrt", "x-world/x-vrt"}, {"vsd", "application/x-visio"}, {"vst", "application/x-visio"}, {"vsw", "application/x-visio"}, {"w60", "application/wordperfect6.0"}, {"w61", "application/wordperfect6.1"}, {"w6w", "application/msword"}, {"wav", "audio/wav"}, {"wb1", "application/x-qpro"}, {"wbmp", "image/vnd.wap.wbmp"}, {"wcm", "application/vnd.ms-works"}, {"wdb", "application/vnd.ms-works"}, {"web", "application/vnd.xara"}, {"webm", "video/webm"}, {"wiz", "application/msword"}, {"wk1", "application/x-123"}, {"wks", "application/vnd.ms-works"}, {"wmf", "windows/metafile"}, {"wmlc", "application/vnd.wap.wmlc"}, {"wmlsc", "application/vnd.wap.wmlscriptc"}, {"wmls", "text/vnd.wap.wmlscript"}, {"wml", "text/vnd.wap.wml"}, {"wmp", "video/x-ms-wmp"}, {"wmv", "video/x-ms-wmv"}, {"wmx", "video/x-ms-wmx"}, {"woff", "application/x-woff"}, {"word", "application/msword"}, {"wp5", "application/wordperfect"}, {"wp6", "application/wordperfect"}, {"wp", "application/wordperfect"}, {"wpd", "application/wordperfect"}, {"wps", "application/vnd.ms-works"}, {"wq1", "application/x-lotus"}, {"wri", "application/mswrite"}, {"wrl", "application/x-world"}, {"wrz", "model/vrml"}, {"wsc", "text/scriplet"}, {"wsdl", "text/xml"}, {"wsrc", "application/x-wais-source"}, {"wtk", "application/x-wintalk"}, {"wvx", "video/x-ms-wvx"}, {"x3d", "model/x3d+xml"}, {"x3db", "model/x3d+fastinfoset"}, {"x3dv", "model/x3d-vrml"}, {"xaf", "x-world/x-vrml"}, {"xaml", "application/xaml+xml"}, {"xap", "application/x-silverlight-app"}, {"xbap", "application/x-ms-xbap"}, {"xbm", "image/x-xbitmap"}, {"xdr", "video/x-amt-demorun"}, {"xgz", "xgl/drawing"}, {"xht", "application/xhtml+xml"}, {"xhtml", "application/xhtml+xml"}, {"xif", "image/vnd.xiff"}, {"xla", "application/vnd.ms-excel"}, {"xlam", "application/vnd.ms-excel.addin.macroEnabled.12"}, {"xl", "application/excel"}, {"xlb", "application/excel"}, {"xlc", "application/excel"}, {"xld", "application/excel"}, {"xlk", "application/excel"}, {"xll", "application/excel"}, {"xlm", "application/excel"}, {"xls", "application/vnd.ms-excel"}, {"xlsb", "application/vnd.ms-excel.sheet.binary.macroEnabled.12"}, {"xlsm", "application/vnd.ms-excel.sheet.macroEnabled.12"}, {"xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"}, {"xlt", "application/vnd.ms-excel"}, {"xltm", "application/vnd.ms-excel.template.macroEnabled.12"}, {"xltx", "application/vnd.openxmlformats-officedocument.spreadsheetml.template"}, {"xlv", "application/excel"}, {"xlw", "application/excel"}, {"xm", "audio/xm"}, {"xml", "text/xml"}, {"xmz", "xgl/movie"}, {"xof", "x-world/x-vrml"}, {"xpi", "application/x-xpinstall"}, {"xpix", "application/x-vnd.ls-xpix"}, {"xpm", "image/xpm"}, {"xps", "application/vnd.ms-xpsdocument"}, {"x-png", "image/png"}, {"xsd", "text/xml"}, {"xsl", "text/xml"}, {"xslt", "text/xml"}, {"xsr", "video/x-amt-showrun"}, {"xwd", "image/x-xwd"}, {"xyz", "chemical/x-pdb"}, {"z", "application/x-compressed"}, {"zip", "application/zip"}, {"zsh", "text/x-script.zsh"} }; } /// <summary> /// Gets the MIME type for the given file name, /// or "application/octet-stream" if a mapping doesn't exist. /// </summary> /// <param name="fileName">Name of the file.</param> /// <returns>The MIME type for the given file name.</returns> public static string GetMimeType(string fileName) { string result = null; var dotIndex = fileName.LastIndexOf('.'); if (dotIndex != -1 && fileName.Length > dotIndex + 1) { MimeTypes.TypeMap.TryGetValue(fileName.Substring(dotIndex + 1), out result); } return result ?? "application/octet-stream"; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.IO; using System.Net.Http.Headers; using System.Net.Test.Common; using System.Security.Cryptography; using System.Text; using System.Threading.Tasks; using Xunit; using Xunit.Abstractions; namespace System.Net.Http.Functional.Tests { using Configuration = System.Net.Test.Common.Configuration; // Note: Disposing the HttpClient object automatically disposes the handler within. So, it is not necessary // to separately Dispose (or have a 'using' statement) for the handler. public class PostScenarioTest { private const string ExpectedContent = "Test contest"; private const string UserName = "user1"; private const string Password = "password1"; private static readonly Uri BasicAuthServerUri = Configuration.Http.BasicAuthUriForCreds(false, UserName, Password); private static readonly Uri SecureBasicAuthServerUri = Configuration.Http.BasicAuthUriForCreds(true, UserName, Password); private readonly ITestOutputHelper _output; public static readonly object[][] EchoServers = Configuration.Http.EchoServers; public static readonly object[][] BasicAuthEchoServers = new object[][] { new object[] { BasicAuthServerUri }, new object[] { SecureBasicAuthServerUri } }; public PostScenarioTest(ITestOutputHelper output) { _output = output; } [OuterLoop] // TODO: Issue #11345 [Theory, MemberData(nameof(EchoServers))] public async Task PostNoContentUsingContentLengthSemantics_Success(Uri serverUri) { await PostHelper(serverUri, string.Empty, null, useContentLengthUpload: true, useChunkedEncodingUpload: false); } [OuterLoop] // TODO: Issue #11345 [Theory, MemberData(nameof(EchoServers))] public async Task PostEmptyContentUsingContentLengthSemantics_Success(Uri serverUri) { await PostHelper(serverUri, string.Empty, new StringContent(string.Empty), useContentLengthUpload: true, useChunkedEncodingUpload: false); } [OuterLoop] // TODO: Issue #11345 [Theory, MemberData(nameof(EchoServers))] public async Task PostEmptyContentUsingChunkedEncoding_Success(Uri serverUri) { await PostHelper(serverUri, string.Empty, new StringContent(string.Empty), useContentLengthUpload: false, useChunkedEncodingUpload: true); } [OuterLoop] // TODO: Issue #11345 [Theory, MemberData(nameof(EchoServers))] public async Task PostUsingContentLengthSemantics_Success(Uri serverUri) { await PostHelper(serverUri, ExpectedContent, new StringContent(ExpectedContent), useContentLengthUpload: true, useChunkedEncodingUpload: false); } [OuterLoop] // TODO: Issue #11345 [Theory, MemberData(nameof(EchoServers))] public async Task PostUsingChunkedEncoding_Success(Uri serverUri) { await PostHelper(serverUri, ExpectedContent, new StringContent(ExpectedContent), useContentLengthUpload: false, useChunkedEncodingUpload: true); } [OuterLoop] // TODO: Issue #11345 [Theory, MemberData(nameof(EchoServers))] public async Task PostSyncBlockingContentUsingChunkedEncoding_Success(Uri serverUri) { await PostHelper(serverUri, ExpectedContent, new SyncBlockingContent(ExpectedContent), useContentLengthUpload: false, useChunkedEncodingUpload: true); } [OuterLoop] // TODO: Issue #11345 [Theory, MemberData(nameof(EchoServers))] public async Task PostRepeatedFlushContentUsingChunkedEncoding_Success(Uri serverUri) { await PostHelper(serverUri, ExpectedContent, new RepeatedFlushContent(ExpectedContent), useContentLengthUpload: false, useChunkedEncodingUpload: true); } [OuterLoop] // TODO: Issue #11345 [Theory, MemberData(nameof(EchoServers))] public async Task PostUsingUsingConflictingSemantics_UsesChunkedSemantics(Uri serverUri) { await PostHelper(serverUri, ExpectedContent, new StringContent(ExpectedContent), useContentLengthUpload: true, useChunkedEncodingUpload: true); } [OuterLoop] // TODO: Issue #11345 [Theory, MemberData(nameof(EchoServers))] public async Task PostUsingNoSpecifiedSemantics_UsesChunkedSemantics(Uri serverUri) { await PostHelper(serverUri, ExpectedContent, new StringContent(ExpectedContent), useContentLengthUpload: false, useChunkedEncodingUpload: false); } [OuterLoop] // TODO: Issue #11345 [Theory] [InlineData(5 * 1024)] [InlineData(63 * 1024)] public async Task PostLongerContentLengths_UsesChunkedSemantics(int contentLength) { var rand = new Random(42); var sb = new StringBuilder(contentLength); for (int i = 0; i < contentLength; i++) { sb.Append((char)(rand.Next(0, 26) + 'a')); } string content = sb.ToString(); await PostHelper(Configuration.Http.RemoteEchoServer, content, new StringContent(content), useContentLengthUpload: true, useChunkedEncodingUpload: false); } [OuterLoop] // TODO: Issue #11345 [Theory, MemberData(nameof(BasicAuthEchoServers))] public async Task PostRewindableContentUsingAuth_NoPreAuthenticate_Success(Uri serverUri) { HttpContent content = CustomContent.Create(ExpectedContent, true); var credential = new NetworkCredential(UserName, Password); await PostUsingAuthHelper(serverUri, ExpectedContent, content, credential, false); } [OuterLoop] // TODO: Issue #11345 [Theory, MemberData(nameof(BasicAuthEchoServers))] public async Task PostNonRewindableContentUsingAuth_NoPreAuthenticate_ThrowsInvalidOperationException(Uri serverUri) { HttpContent content = CustomContent.Create(ExpectedContent, false); var credential = new NetworkCredential(UserName, Password); await Assert.ThrowsAsync<InvalidOperationException>(() => PostUsingAuthHelper(serverUri, ExpectedContent, content, credential, preAuthenticate: false)); } [OuterLoop] // TODO: Issue #11345 [Theory, MemberData(nameof(BasicAuthEchoServers))] [ActiveIssue(9228, TestPlatforms.Windows)] public async Task PostNonRewindableContentUsingAuth_PreAuthenticate_Success(Uri serverUri) { HttpContent content = CustomContent.Create(ExpectedContent, false); var credential = new NetworkCredential(UserName, Password); await PostUsingAuthHelper(serverUri, ExpectedContent, content, credential, preAuthenticate: true); } private async Task PostHelper( Uri serverUri, string requestBody, HttpContent requestContent, bool useContentLengthUpload, bool useChunkedEncodingUpload) { using (var client = new HttpClient()) { if (!useContentLengthUpload && requestContent != null) { requestContent.Headers.ContentLength = null; } if (useChunkedEncodingUpload) { client.DefaultRequestHeaders.TransferEncodingChunked = true; } using (HttpResponseMessage response = await client.PostAsync(serverUri, requestContent)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); string responseContent = await response.Content.ReadAsStringAsync(); _output.WriteLine(responseContent); if (!useContentLengthUpload && !useChunkedEncodingUpload) { useChunkedEncodingUpload = true; } TestHelper.VerifyResponseBody( responseContent, response.Content.Headers.ContentMD5, useChunkedEncodingUpload, requestBody); } } } private async Task PostUsingAuthHelper( Uri serverUri, string requestBody, HttpContent requestContent, NetworkCredential credential, bool preAuthenticate) { var handler = new HttpClientHandler(); handler.PreAuthenticate = preAuthenticate; handler.Credentials = credential; using (var client = new HttpClient(handler)) { // Send HEAD request to help bypass the 401 auth challenge for the latter POST assuming // that the authentication will be cached and re-used later when PreAuthenticate is true. var request = new HttpRequestMessage(HttpMethod.Head, serverUri); using (HttpResponseMessage response = await client.SendAsync(request)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); } // Now send POST request. request = new HttpRequestMessage(HttpMethod.Post, serverUri); request.Content = requestContent; requestContent.Headers.ContentLength = null; request.Headers.TransferEncodingChunked = true; using (HttpResponseMessage response = await client.PostAsync(serverUri, requestContent)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); string responseContent = await response.Content.ReadAsStringAsync(); _output.WriteLine(responseContent); TestHelper.VerifyResponseBody( responseContent, response.Content.Headers.ContentMD5, true, requestBody); } } } } }
// The MIT License (MIT) // // Copyright (c) 2014-2017, Institute for Software & Systems Engineering // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. namespace ISSE.SafetyChecking.FaultMinimalKripkeStructure { using System; using System.Collections.Generic; using System.Runtime.CompilerServices; using ExecutableModel; using AnalysisModel; using AnalysisModelTraverser; using Utilities; /// <summary> /// Creates an activation-minimal set of <see cref="CandidateTransition" /> instances. /// </summary> internal sealed unsafe class ActivationMinimalTransitionSetBuilder<TExecutableModel> : DisposableObject where TExecutableModel : ExecutableModel<TExecutableModel> { private const int ProbeThreshold = 1000; private readonly long _capacity; private readonly FaultSetInfo* _faults; private readonly MemoryBuffer _faultsBuffer = new MemoryBuffer(); private readonly Func<bool>[] _formulas; private readonly MemoryBuffer _hashedStateBuffer = new MemoryBuffer(); private readonly byte* _hashedStateMemory; private readonly int* _lookup; private readonly MemoryBuffer _lookupBuffer = new MemoryBuffer(); private readonly int _stateVectorSize; private readonly List<uint> _successors; private readonly MemoryBuffer _transitionBuffer = new MemoryBuffer(); private readonly CandidateTransition* _transitions; private int _computedCount; private int _count; private int _nextFaultIndex; /// <summary> /// A storage where temporal states can be saved to. /// </summary> private readonly TemporaryStateStorage _temporalStateStorage; /// <summary> /// Initializes a new instance. /// </summary> /// <param name="temporalStateStorage">A storage where temporal states can be saved to.</param> /// <param name="capacity">The maximum number of successors that can be cached.</param> /// <param name="formulas">The formulas that should be checked for all successor states.</param> public ActivationMinimalTransitionSetBuilder(TemporaryStateStorage temporalStateStorage, long capacity, params Func<bool>[] formulas) { Requires.NotNull(temporalStateStorage, nameof(temporalStateStorage)); Requires.NotNull(formulas, nameof(formulas)); Requires.That(formulas.Length < 32, "At most 32 formulas are supported."); Requires.That(capacity <= (1 << 30), nameof(capacity), $"Maximum supported capacity is {1 << 30}."); _temporalStateStorage = temporalStateStorage; _stateVectorSize = temporalStateStorage.AnalysisModelStateVectorSize; _formulas = formulas; _transitionBuffer.Resize(capacity * sizeof(CandidateTransition), zeroMemory: false); _transitions = (CandidateTransition*)_transitionBuffer.Pointer; _lookupBuffer.Resize(capacity * sizeof(int), zeroMemory: false); _faultsBuffer.Resize(capacity * sizeof(FaultSetInfo), zeroMemory: false); _hashedStateBuffer.Resize(capacity * _stateVectorSize, zeroMemory: false); _successors = new List<uint>(); _capacity = capacity; _lookup = (int*)_lookupBuffer.Pointer; _faults = (FaultSetInfo*)_faultsBuffer.Pointer; _hashedStateMemory = _hashedStateBuffer.Pointer; for (var i = 0; i < capacity; ++i) _lookup[i] = -1; } /// <summary> /// Adds a transition to the <paramref name="model" />'s current state. /// </summary> /// <param name="model">The model the transition should be added for.</param> public void Add(ExecutableModel<TExecutableModel> model) { if (_count >= _capacity) throw new OutOfMemoryException("Unable to store an additional transition. Try increasing the successor state capacity."); ++_computedCount; // 1. Serialize the model's computed state; that is the successor state of the transition's source state // modulo any changes resulting from notifications of fault activations var successorState = _temporalStateStorage.GetFreeTemporalSpaceAddress(); var activatedFaults = FaultSet.FromActivatedFaults(model.NondeterministicFaults); model.Serialize(successorState); // 2. Make sure the transition we're about to add is activation-minimal if (!Add(successorState, activatedFaults)) return; // 3. Execute fault activation notifications and serialize the updated state if necessary if (model.NotifyFaultActivations()) model.Serialize(successorState); // 4. Store the transition _transitions[_count] = new CandidateTransition { TargetStatePointer = successorState, Formulas = new StateFormulaSet(_formulas), ActivatedFaults = activatedFaults, Flags = TransitionFlags.IsValidFlag, }; ++_count; } /// <summary> /// Clears the cache, removing all cached states. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Clear() { _count = 0; _computedCount = 0; foreach (var state in _successors) _lookup[state] = -1; _successors.Clear(); _nextFaultIndex = 0; } /// <summary> /// Adds the <paramref name="successorState" /> to the transition set if neccessary, reached using the /// <paramref name="activatedFaults" />. /// </summary> /// <param name="successorState">The successor state that should be added.</param> /// <param name="activatedFaults">The faults activated by the transition to reach the state.</param> private bool Add(byte* successorState, FaultSet activatedFaults) { var hash = MemoryBuffer.Hash(successorState, _stateVectorSize, 0); for (var i = 1; i < ProbeThreshold; ++i) { var stateHash = MemoryBuffer.Hash((byte*)&hash, sizeof(int), i * 8345723) % _capacity; var faultIndex = _lookup[stateHash]; // If we don't know the state yet, set everything up and add the transition if (faultIndex == -1) { _successors.Add((uint)stateHash); AddFaultMetadata(stateHash, -1); MemoryBuffer.Copy(successorState, _hashedStateMemory + stateHash * _stateVectorSize, _stateVectorSize); return true; } // If there is a hash conflict, try again if (!MemoryBuffer.AreEqual(successorState, _hashedStateMemory + stateHash * _stateVectorSize, _stateVectorSize)) continue; // The transition has an already-known target state; it might have to be added or invalidate previously found transitions return UpdateTransitions(stateHash, activatedFaults, faultIndex); } throw new OutOfMemoryException( "Failed to find an empty hash table slot within a reasonable amount of time. Try increasing the successor state capacity."); } /// <summary> /// Adds the current transition if it is activation-minimal. Previously found transition might have to be removed if they are /// no longer activation-minimal. /// </summary> private bool UpdateTransitions(long stateHash, FaultSet activatedFaults, int faultIndex) { bool addTransition; bool addFaults; bool cleanupTransitions; ClassifyActivatedFaults(activatedFaults, faultIndex, out addTransition, out addFaults, out cleanupTransitions); if (cleanupTransitions) CleanupTransitions(activatedFaults, faultIndex, stateHash); if (addFaults) AddFaultMetadata(stateHash, _lookup[stateHash]); return addTransition; } /// <summary> /// Removes all transitions that are no longer activation minimal due to the current transition. /// </summary> private void CleanupTransitions(FaultSet activatedFaults, int faultIndex, long stateHash) { var current = faultIndex; var nextPointer = &_lookup[stateHash]; while (current != -1) { var faultSet = &_faults[current]; // Remove the fault set and the corresponding transition if it is a proper subset of the activated faults if (activatedFaults.IsSubsetOf(faultSet->Transition->ActivatedFaults) && activatedFaults != faultSet->Transition->ActivatedFaults) { faultSet->Transition->Flags = TransitionFlags.RemoveValid(faultSet->Transition->Flags); *nextPointer = faultSet->NextSet; } if (nextPointer != &_lookup[stateHash]) nextPointer = &faultSet->NextSet; current = faultSet->NextSet; } } /// <summary> /// Classifies how the transition set must be updated. /// </summary> private void ClassifyActivatedFaults(FaultSet activatedFaults, int faultIndex, out bool addTransition, out bool addFaults, out bool cleanupTransitions) { addFaults = false; cleanupTransitions = false; // Basic invariant of the fault list: it contains only sets of activation-minimal faults while (faultIndex != -1) { var faultSet = &_faults[faultIndex]; faultIndex = faultSet->NextSet; // If the fault set is a subset of the activated faults, the current transition is not activation-minimal; // we can therefore safely ignore the transition; due to the list invariant, none of the remaining // fault sets in the list can be a superset of the activated faults because then the current fault set // would also be a subset of that other fault set, violating the invariant if (faultSet->Transition->ActivatedFaults.IsSubsetOf(activatedFaults)) { addTransition = faultSet->Transition->ActivatedFaults == activatedFaults; return; } // If at least one of the previously added transitions that we assumed to be activation-minimal is // in fact not activation-minimal, we have to clean up the transition set if (activatedFaults.IsSubsetOf(faultSet->Transition->ActivatedFaults)) cleanupTransitions = true; } // If we get here, we must add the faults and the transition addTransition = true; addFaults = true; } /// <summary> /// Adds the fault metadata of the current transition. /// </summary> private void AddFaultMetadata(long stateHash, int nextSet) { if (_nextFaultIndex >= _capacity) throw new OutOfMemoryException("Unable to store an additional transition. Try increasing the successor state capacity."); _faults[_nextFaultIndex] = new FaultSetInfo { NextSet = nextSet, Transition = &_transitions[_count] }; _lookup[stateHash] = _nextFaultIndex; _nextFaultIndex++; } /// <summary> /// Disposes the object, releasing all managed and unmanaged resources. /// </summary> /// <param name="disposing">If true, indicates that the object is disposed; otherwise, the object is finalized.</param> protected override void OnDisposing(bool disposing) { if (!disposing) return; _transitionBuffer.SafeDispose(); _hashedStateBuffer.SafeDispose(); _faultsBuffer.SafeDispose(); _lookupBuffer.SafeDispose(); } /// <summary> /// Creates a <see cref="TransitionCollection" /> instance for all transitions contained in the set. /// </summary> public TransitionCollection ToCollection() { return new TransitionCollection((Transition*)_transitions, _count, _computedCount, sizeof(CandidateTransition)); } } /// <summary> /// Represents an element of a linked list of activated faults. /// </summary> internal unsafe struct FaultSetInfo { public int NextSet; public CandidateTransition* Transition; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using System.Runtime.InteropServices; using System.Text; namespace System.IO { public sealed partial class DriveInfo { private static string NormalizeDriveName(string driveName) { Debug.Assert(driveName != null); string name; if (driveName.Length == 1) name = driveName + ":\\"; else { // GetPathRoot does not check all invalid characters if (PathInternal.HasIllegalCharacters(driveName)) throw new ArgumentException(SR.Format(SR.Arg_InvalidDriveChars, driveName), nameof(driveName)); name = Path.GetPathRoot(driveName); // Disallow null or empty drive letters and UNC paths if (name == null || name.Length == 0 || name.StartsWith("\\\\", StringComparison.Ordinal)) throw new ArgumentException(SR.Arg_MustBeDriveLetterOrRootDir); } // We want to normalize to have a trailing backslash so we don't have two equivalent forms and // because some Win32 API don't work without it. if (name.Length == 2 && name[1] == ':') { name = name + "\\"; } // Now verify that the drive letter could be a real drive name. // On Windows this means it's between A and Z, ignoring case. char letter = driveName[0]; if (!((letter >= 'A' && letter <= 'Z') || (letter >= 'a' && letter <= 'z'))) throw new ArgumentException(SR.Arg_MustBeDriveLetterOrRootDir); return name; } public DriveType DriveType { [System.Security.SecuritySafeCritical] get { // GetDriveType can't fail return (DriveType)Interop.Kernel32.GetDriveType(Name); } } public String DriveFormat { [System.Security.SecuritySafeCritical] // auto-generated get { const int volNameLen = 50; StringBuilder volumeName = new StringBuilder(volNameLen); const int fileSystemNameLen = 50; StringBuilder fileSystemName = new StringBuilder(fileSystemNameLen); int serialNumber, maxFileNameLen, fileSystemFlags; uint oldMode; bool success = Interop.Kernel32.SetThreadErrorMode(Interop.Kernel32.SEM_FAILCRITICALERRORS, out oldMode); try { bool r = Interop.Kernel32.GetVolumeInformation(Name, volumeName, volNameLen, out serialNumber, out maxFileNameLen, out fileSystemFlags, fileSystemName, fileSystemNameLen); if (!r) { throw Error.GetExceptionForLastWin32DriveError(Name); } } finally { if (success) Interop.Kernel32.SetThreadErrorMode(oldMode, out oldMode); } return fileSystemName.ToString(); } } public long AvailableFreeSpace { [System.Security.SecuritySafeCritical] get { long userBytes, totalBytes, freeBytes; uint oldMode; bool success = Interop.Kernel32.SetThreadErrorMode(Interop.Kernel32.SEM_FAILCRITICALERRORS, out oldMode); try { bool r = Interop.Kernel32.GetDiskFreeSpaceEx(Name, out userBytes, out totalBytes, out freeBytes); if (!r) throw Error.GetExceptionForLastWin32DriveError(Name); } finally { if (success) Interop.Kernel32.SetThreadErrorMode(oldMode, out oldMode); } return userBytes; } } public long TotalFreeSpace { [System.Security.SecuritySafeCritical] // auto-generated get { long userBytes, totalBytes, freeBytes; uint oldMode; bool success = Interop.Kernel32.SetThreadErrorMode(Interop.Kernel32.SEM_FAILCRITICALERRORS, out oldMode); try { bool r = Interop.Kernel32.GetDiskFreeSpaceEx(Name, out userBytes, out totalBytes, out freeBytes); if (!r) throw Error.GetExceptionForLastWin32DriveError(Name); } finally { if (success) Interop.Kernel32.SetThreadErrorMode(oldMode, out oldMode); } return freeBytes; } } public long TotalSize { [System.Security.SecuritySafeCritical] get { // Don't cache this, to handle variable sized floppy drives // or other various removable media drives. long userBytes, totalBytes, freeBytes; uint oldMode; bool success = Interop.Kernel32.SetThreadErrorMode(Interop.Kernel32.SEM_FAILCRITICALERRORS, out oldMode); try { bool r = Interop.Kernel32.GetDiskFreeSpaceEx(Name, out userBytes, out totalBytes, out freeBytes); if (!r) throw Error.GetExceptionForLastWin32DriveError(Name); } finally { Interop.Kernel32.SetThreadErrorMode(oldMode, out oldMode); } return totalBytes; } } public static DriveInfo[] GetDrives() { string[] drives = DriveInfoInternal.GetLogicalDrives(); DriveInfo[] result = new DriveInfo[drives.Length]; for (int i = 0; i < drives.Length; i++) { result[i] = new DriveInfo(drives[i]); } return result; } // Null is a valid volume label. public String VolumeLabel { [System.Security.SecuritySafeCritical] // auto-generated get { // NTFS uses a limit of 32 characters for the volume label, // as of Windows Server 2003. const int volNameLen = 50; StringBuilder volumeName = new StringBuilder(volNameLen); const int fileSystemNameLen = 50; StringBuilder fileSystemName = new StringBuilder(fileSystemNameLen); int serialNumber, maxFileNameLen, fileSystemFlags; uint oldMode; bool success = Interop.Kernel32.SetThreadErrorMode(Interop.Kernel32.SEM_FAILCRITICALERRORS, out oldMode); try { bool r = Interop.Kernel32.GetVolumeInformation(Name, volumeName, volNameLen, out serialNumber, out maxFileNameLen, out fileSystemFlags, fileSystemName, fileSystemNameLen); if (!r) { int errorCode = Marshal.GetLastWin32Error(); // Win9x appears to return ERROR_INVALID_DATA when a // drive doesn't exist. if (errorCode == Interop.Errors.ERROR_INVALID_DATA) errorCode = Interop.Errors.ERROR_INVALID_DRIVE; throw Error.GetExceptionForWin32DriveError(errorCode, Name); } } finally { if (success) Interop.Kernel32.SetThreadErrorMode(oldMode, out oldMode); } return volumeName.ToString(); } [System.Security.SecuritySafeCritical] // auto-generated set { uint oldMode; bool success = Interop.Kernel32.SetThreadErrorMode(Interop.Kernel32.SEM_FAILCRITICALERRORS, out oldMode); try { bool r = Interop.Kernel32.SetVolumeLabel(Name, value); if (!r) { int errorCode = Marshal.GetLastWin32Error(); // Provide better message if (errorCode == Interop.Errors.ERROR_ACCESS_DENIED) throw new UnauthorizedAccessException(SR.InvalidOperation_SetVolumeLabelFailed); throw Error.GetExceptionForWin32DriveError(errorCode, Name); } } finally { if (success) Interop.Kernel32.SetThreadErrorMode(oldMode, out oldMode); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; using Internal.Runtime.CompilerServices; namespace System.Runtime.CompilerServices { /// <summary> /// Provides a builder for asynchronous methods that return <see cref="System.Threading.Tasks.Task{TResult}"/>. /// This type is intended for compiler use only. /// </summary> /// <remarks> /// AsyncTaskMethodBuilder{TResult} is a value type, and thus it is copied by value. /// Prior to being copied, one of its Task, SetResult, or SetException members must be accessed, /// or else the copies may end up building distinct Task instances. /// </remarks> public struct AsyncTaskMethodBuilder<TResult> { /// <summary>A cached task for default(TResult).</summary> internal static readonly Task<TResult> s_defaultResultTask = AsyncTaskCache.CreateCacheableTask<TResult>(default); /// <summary>The lazily-initialized built task.</summary> private Task<TResult>? m_task; // Debugger depends on the exact name of this field. /// <summary>Initializes a new <see cref="AsyncTaskMethodBuilder"/>.</summary> /// <returns>The initialized <see cref="AsyncTaskMethodBuilder"/>.</returns> public static AsyncTaskMethodBuilder<TResult> Create() => default; /// <summary>Initiates the builder's execution with the associated state machine.</summary> /// <typeparam name="TStateMachine">Specifies the type of the state machine.</typeparam> /// <param name="stateMachine">The state machine instance, passed by reference.</param> [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine => AsyncMethodBuilderCore.Start(ref stateMachine); /// <summary>Associates the builder with the state machine it represents.</summary> /// <param name="stateMachine">The heap-allocated state machine object.</param> /// <exception cref="System.ArgumentNullException">The <paramref name="stateMachine"/> argument was null (Nothing in Visual Basic).</exception> /// <exception cref="System.InvalidOperationException">The builder is incorrectly initialized.</exception> public void SetStateMachine(IAsyncStateMachine stateMachine) => AsyncMethodBuilderCore.SetStateMachine(stateMachine, m_task); /// <summary> /// Schedules the specified state machine to be pushed forward when the specified awaiter completes. /// </summary> /// <typeparam name="TAwaiter">Specifies the type of the awaiter.</typeparam> /// <typeparam name="TStateMachine">Specifies the type of the state machine.</typeparam> /// <param name="awaiter">The awaiter.</param> /// <param name="stateMachine">The state machine.</param> public void AwaitOnCompleted<TAwaiter, TStateMachine>( ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine => AwaitOnCompleted(ref awaiter, ref stateMachine, ref m_task); internal static void AwaitOnCompleted<TAwaiter, TStateMachine>( ref TAwaiter awaiter, ref TStateMachine stateMachine, [NotNull] ref Task<TResult>? taskField) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine { try { awaiter.OnCompleted(GetStateMachineBox(ref stateMachine, ref taskField).MoveNextAction); } catch (Exception e) { System.Threading.Tasks.Task.ThrowAsync(e, targetContext: null); } } /// <summary> /// Schedules the specified state machine to be pushed forward when the specified awaiter completes. /// </summary> /// <typeparam name="TAwaiter">Specifies the type of the awaiter.</typeparam> /// <typeparam name="TStateMachine">Specifies the type of the state machine.</typeparam> /// <param name="awaiter">The awaiter.</param> /// <param name="stateMachine">The state machine.</param> [MethodImpl(MethodImplOptions.AggressiveInlining)] public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>( ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine => AwaitUnsafeOnCompleted(ref awaiter, ref stateMachine, ref m_task); [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>( ref TAwaiter awaiter, ref TStateMachine stateMachine, [NotNull] ref Task<TResult>? taskField) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine { IAsyncStateMachineBox box = GetStateMachineBox(ref stateMachine, ref taskField); AwaitUnsafeOnCompleted(ref awaiter, box); } [MethodImpl(MethodImplOptions.AggressiveOptimization)] // workaround boxing allocations in Tier0: https://github.com/dotnet/coreclr/issues/14474 internal static void AwaitUnsafeOnCompleted<TAwaiter>( ref TAwaiter awaiter, IAsyncStateMachineBox box) where TAwaiter : ICriticalNotifyCompletion { // The null tests here ensure that the jit can optimize away the interface // tests when TAwaiter is a ref type. if ((null != (object)default(TAwaiter)!) && (awaiter is ITaskAwaiter)) // TODO-NULLABLE: default(T) == null warning (https://github.com/dotnet/roslyn/issues/34757) { ref TaskAwaiter ta = ref Unsafe.As<TAwaiter, TaskAwaiter>(ref awaiter); // relies on TaskAwaiter/TaskAwaiter<T> having the same layout TaskAwaiter.UnsafeOnCompletedInternal(ta.m_task, box, continueOnCapturedContext: true); } else if ((null != (object)default(TAwaiter)!) && (awaiter is IConfiguredTaskAwaiter)) // TODO-NULLABLE: default(T) == null warning (https://github.com/dotnet/roslyn/issues/34757) { ref ConfiguredTaskAwaitable.ConfiguredTaskAwaiter ta = ref Unsafe.As<TAwaiter, ConfiguredTaskAwaitable.ConfiguredTaskAwaiter>(ref awaiter); TaskAwaiter.UnsafeOnCompletedInternal(ta.m_task, box, ta.m_continueOnCapturedContext); } else if ((null != (object)default(TAwaiter)!) && (awaiter is IStateMachineBoxAwareAwaiter)) // TODO-NULLABLE: default(T) == null warning (https://github.com/dotnet/roslyn/issues/34757) { try { ((IStateMachineBoxAwareAwaiter)awaiter).AwaitUnsafeOnCompleted(box); } catch (Exception e) { // Whereas with Task the code that hooks up and invokes the continuation is all local to corelib, // with ValueTaskAwaiter we may be calling out to an arbitrary implementation of IValueTaskSource // wrapped in the ValueTask, and as such we protect against errant exceptions that may emerge. // We don't want such exceptions propagating back into the async method, which can't handle // exceptions well at that location in the state machine, especially if the exception may occur // after the ValueTaskAwaiter already successfully hooked up the callback, in which case it's possible // two different flows of execution could end up happening in the same async method call. System.Threading.Tasks.Task.ThrowAsync(e, targetContext: null); } } else { // The awaiter isn't specially known. Fall back to doing a normal await. try { awaiter.UnsafeOnCompleted(box.MoveNextAction); } catch (Exception e) { System.Threading.Tasks.Task.ThrowAsync(e, targetContext: null); } } } /// <summary>Gets the "boxed" state machine object.</summary> /// <typeparam name="TStateMachine">Specifies the type of the async state machine.</typeparam> /// <param name="stateMachine">The state machine.</param> /// <returns>The "boxed" state machine.</returns> private static IAsyncStateMachineBox GetStateMachineBox<TStateMachine>( ref TStateMachine stateMachine, [NotNull] ref Task<TResult>? taskField) where TStateMachine : IAsyncStateMachine { ExecutionContext? currentContext = ExecutionContext.Capture(); // Check first for the most common case: not the first yield in an async method. // In this case, the first yield will have already "boxed" the state machine in // a strongly-typed manner into an AsyncStateMachineBox. It will already contain // the state machine as well as a MoveNextDelegate and a context. The only thing // we might need to do is update the context if that's changed since it was stored. if (taskField is AsyncStateMachineBox<TStateMachine> stronglyTypedBox) { if (stronglyTypedBox.Context != currentContext) { stronglyTypedBox.Context = currentContext; } return stronglyTypedBox; } // The least common case: we have a weakly-typed boxed. This results if the debugger // or some other use of reflection accesses a property like ObjectIdForDebugger or a // method like SetNotificationForWaitCompletion prior to the first await happening. In // such situations, we need to get an object to represent the builder, but we don't yet // know the type of the state machine, and thus can't use TStateMachine. Instead, we // use the IAsyncStateMachine interface, which all TStateMachines implement. This will // result in a boxing allocation when storing the TStateMachine if it's a struct, but // this only happens in active debugging scenarios where such performance impact doesn't // matter. if (taskField is AsyncStateMachineBox<IAsyncStateMachine> weaklyTypedBox) { // If this is the first await, we won't yet have a state machine, so store it. if (weaklyTypedBox.StateMachine == null) { Debugger.NotifyOfCrossThreadDependency(); // same explanation as with usage below weaklyTypedBox.StateMachine = stateMachine; } // Update the context. This only happens with a debugger, so no need to spend // extra IL checking for equality before doing the assignment. weaklyTypedBox.Context = currentContext; return weaklyTypedBox; } // Alert a listening debugger that we can't make forward progress unless it slips threads. // If we don't do this, and a method that uses "await foo;" is invoked through funceval, // we could end up hooking up a callback to push forward the async method's state machine, // the debugger would then abort the funceval after it takes too long, and then continuing // execution could result in another callback being hooked up. At that point we have // multiple callbacks registered to push the state machine, which could result in bad behavior. Debugger.NotifyOfCrossThreadDependency(); // At this point, taskField should really be null, in which case we want to create the box. // However, in a variety of debugger-related (erroneous) situations, it might be non-null, // e.g. if the Task property is examined in a Watch window, forcing it to be lazily-intialized // as a Task<TResult> rather than as an AsyncStateMachineBox. The worst that happens in such // cases is we lose the ability to properly step in the debugger, as the debugger uses that // object's identity to track this specific builder/state machine. As such, we proceed to // overwrite whatever's there anyway, even if it's non-null. #if CORERT // DebugFinalizableAsyncStateMachineBox looks like a small type, but it actually is not because // it will have a copy of all the slots from its parent. It will add another hundred(s) bytes // per each async method in CoreRT / ProjectN binaries without adding much value. Avoid // generating this extra code until a better solution is implemented. var box = new AsyncStateMachineBox<TStateMachine>(); #else AsyncStateMachineBox<TStateMachine> box = AsyncMethodBuilderCore.TrackAsyncMethodCompletion ? CreateDebugFinalizableAsyncStateMachineBox<TStateMachine>() : new AsyncStateMachineBox<TStateMachine>(); #endif taskField = box; // important: this must be done before storing stateMachine into box.StateMachine! box.StateMachine = stateMachine; box.Context = currentContext; // Log the creation of the state machine box object / task for this async method. if (AsyncCausalityTracer.LoggingOn) { AsyncCausalityTracer.TraceOperationCreation(box, "Async: " + stateMachine.GetType().Name); } // And if async debugging is enabled, track the task. if (System.Threading.Tasks.Task.s_asyncDebuggingEnabled) { System.Threading.Tasks.Task.AddToActiveTasks(box); } return box; } #if !CORERT // Avoid forcing the JIT to build DebugFinalizableAsyncStateMachineBox<TStateMachine> unless it's actually needed. [MethodImpl(MethodImplOptions.NoInlining)] private static AsyncStateMachineBox<TStateMachine> CreateDebugFinalizableAsyncStateMachineBox<TStateMachine>() where TStateMachine : IAsyncStateMachine => new DebugFinalizableAsyncStateMachineBox<TStateMachine>(); /// <summary> /// Provides an async state machine box with a finalizer that will fire an EventSource /// event about the state machine if it's being finalized without having been completed. /// </summary> /// <typeparam name="TStateMachine">Specifies the type of the state machine.</typeparam> private sealed class DebugFinalizableAsyncStateMachineBox<TStateMachine> : // SOS DumpAsync command depends on this name AsyncStateMachineBox<TStateMachine> where TStateMachine : IAsyncStateMachine { ~DebugFinalizableAsyncStateMachineBox() { // If the state machine is being finalized, something went wrong during its processing, // e.g. it awaited something that got collected without itself having been completed. // Fire an event with details about the state machine to help with debugging. if (!IsCompleted) // double-check it's not completed, just to help minimize false positives { TplEventSource.Log.IncompleteAsyncMethod(this); } } } #endif /// <summary>A strongly-typed box for Task-based async state machines.</summary> /// <typeparam name="TStateMachine">Specifies the type of the state machine.</typeparam> private class AsyncStateMachineBox<TStateMachine> : // SOS DumpAsync command depends on this name Task<TResult>, IAsyncStateMachineBox where TStateMachine : IAsyncStateMachine { /// <summary>Delegate used to invoke on an ExecutionContext when passed an instance of this box type.</summary> private static readonly ContextCallback s_callback = ExecutionContextCallback; // Used to initialize s_callback above. We don't use a lambda for this on purpose: a lambda would // introduce a new generic type behind the scenes that comes with a hefty size penalty in AOT builds. private static void ExecutionContextCallback(object? s) { Debug.Assert(s is AsyncStateMachineBox<TStateMachine>); // Only used privately to pass directly to EC.Run Unsafe.As<AsyncStateMachineBox<TStateMachine>>(s).StateMachine!.MoveNext(); } /// <summary>A delegate to the <see cref="MoveNext()"/> method.</summary> private Action? _moveNextAction; /// <summary>The state machine itself.</summary> [AllowNull, MaybeNull] public TStateMachine StateMachine = default; // mutable struct; do not make this readonly. SOS DumpAsync command depends on this name. /// <summary>Captured ExecutionContext with which to invoke <see cref="MoveNextAction"/>; may be null.</summary> public ExecutionContext? Context; /// <summary>A delegate to the <see cref="MoveNext()"/> method.</summary> public Action MoveNextAction => _moveNextAction ??= new Action(MoveNext); internal sealed override void ExecuteFromThreadPool(Thread threadPoolThread) => MoveNext(threadPoolThread); /// <summary>Calls MoveNext on <see cref="StateMachine"/></summary> public void MoveNext() => MoveNext(threadPoolThread: null); private void MoveNext(Thread? threadPoolThread) { Debug.Assert(!IsCompleted); bool loggingOn = AsyncCausalityTracer.LoggingOn; if (loggingOn) { AsyncCausalityTracer.TraceSynchronousWorkStart(this, CausalitySynchronousWork.Execution); } ExecutionContext? context = Context; if (context == null) { Debug.Assert(StateMachine != null); StateMachine.MoveNext(); } else { if (threadPoolThread is null) { ExecutionContext.RunInternal(context, s_callback, this); } else { ExecutionContext.RunFromThreadPoolDispatchLoop(threadPoolThread, context, s_callback, this); } } if (IsCompleted) { // If async debugging is enabled, remove the task from tracking. if (System.Threading.Tasks.Task.s_asyncDebuggingEnabled) { System.Threading.Tasks.Task.RemoveFromActiveTasks(this); } // Clear out state now that the async method has completed. // This avoids keeping arbitrary state referenced by lifted locals // if this Task / state machine box is held onto. StateMachine = default; Context = default; #if !CORERT // In case this is a state machine box with a finalizer, suppress its finalization // as it's now complete. We only need the finalizer to run if the box is collected // without having been completed. if (AsyncMethodBuilderCore.TrackAsyncMethodCompletion) { GC.SuppressFinalize(this); } #endif } if (loggingOn) { AsyncCausalityTracer.TraceSynchronousWorkCompletion(CausalitySynchronousWork.Execution); } } /// <summary>Gets the state machine as a boxed object. This should only be used for debugging purposes.</summary> IAsyncStateMachine IAsyncStateMachineBox.GetStateMachineObject() => StateMachine!; // likely boxes, only use for debugging } /// <summary>Gets the <see cref="System.Threading.Tasks.Task{TResult}"/> for this builder.</summary> /// <returns>The <see cref="System.Threading.Tasks.Task{TResult}"/> representing the builder's asynchronous operation.</returns> public Task<TResult> Task { [MethodImpl(MethodImplOptions.AggressiveInlining)] get => m_task ?? InitializeTaskAsPromise(); } /// <summary> /// Initializes the task, which must not yet be initialized. Used only when the Task is being forced into /// existence when no state machine is needed, e.g. when the builder is being synchronously completed with /// an exception, when the builder is being used out of the context of an async method, etc. /// </summary> [MethodImpl(MethodImplOptions.NoInlining)] private Task<TResult> InitializeTaskAsPromise() { Debug.Assert(m_task == null); return m_task = new Task<TResult>(); } internal static Task<TResult> CreateWeaklyTypedStateMachineBox() { #if CORERT // DebugFinalizableAsyncStateMachineBox looks like a small type, but it actually is not because // it will have a copy of all the slots from its parent. It will add another hundred(s) bytes // per each async method in CoreRT / ProjectN binaries without adding much value. Avoid // generating this extra code until a better solution is implemented. return new AsyncStateMachineBox<IAsyncStateMachine>(); #else return AsyncMethodBuilderCore.TrackAsyncMethodCompletion ? CreateDebugFinalizableAsyncStateMachineBox<IAsyncStateMachine>() : new AsyncStateMachineBox<IAsyncStateMachine>(); #endif } /// <summary> /// Completes the <see cref="System.Threading.Tasks.Task{TResult}"/> in the /// <see cref="System.Threading.Tasks.TaskStatus">RanToCompletion</see> state with the specified result. /// </summary> /// <param name="result">The result to use to complete the task.</param> /// <exception cref="System.InvalidOperationException">The task has already completed.</exception> public void SetResult(TResult result) { // Get the currently stored task, which will be non-null if get_Task has already been accessed. // If there isn't one, get a task and store it. if (m_task is null) { m_task = GetTaskForResult(result); Debug.Assert(m_task != null, $"{nameof(GetTaskForResult)} should never return null"); } else { // Slow path: complete the existing task. SetExistingTaskResult(m_task, result); } } /// <summary>Completes the already initialized task with the specified result.</summary> /// <param name="result">The result to use to complete the task.</param> internal static void SetExistingTaskResult(Task<TResult> taskField, [AllowNull] TResult result) { Debug.Assert(taskField != null, "Expected non-null task"); if (AsyncCausalityTracer.LoggingOn) { AsyncCausalityTracer.TraceOperationCompletion(taskField, AsyncCausalityStatus.Completed); } if (!taskField.TrySetResult(result)) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.TaskT_TransitionToFinal_AlreadyCompleted); } } /// <summary> /// Completes the <see cref="System.Threading.Tasks.Task{TResult}"/> in the /// <see cref="System.Threading.Tasks.TaskStatus">Faulted</see> state with the specified exception. /// </summary> /// <param name="exception">The <see cref="System.Exception"/> to use to fault the task.</param> /// <exception cref="System.ArgumentNullException">The <paramref name="exception"/> argument is null (Nothing in Visual Basic).</exception> /// <exception cref="System.InvalidOperationException">The task has already completed.</exception> public void SetException(Exception exception) => SetException(exception, ref m_task); internal static void SetException(Exception exception, ref Task<TResult>? taskField) { if (exception == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.exception); } // Get the task, forcing initialization if it hasn't already been initialized. Task<TResult> task = (taskField ??= new Task<TResult>()); // If the exception represents cancellation, cancel the task. Otherwise, fault the task. bool successfullySet = exception is OperationCanceledException oce ? task.TrySetCanceled(oce.CancellationToken, oce) : task.TrySetException(exception); // Unlike with TaskCompletionSource, we do not need to spin here until _taskAndStateMachine is completed, // since AsyncTaskMethodBuilder.SetException should not be immediately followed by any code // that depends on the task having completely completed. Moreover, with correct usage, // SetResult or SetException should only be called once, so the Try* methods should always // return true, so no spinning would be necessary anyway (the spinning in TCS is only relevant // if another thread completes the task first). if (!successfullySet) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.TaskT_TransitionToFinal_AlreadyCompleted); } } /// <summary> /// Called by the debugger to request notification when the first wait operation /// (await, Wait, Result, etc.) on this builder's task completes. /// </summary> /// <param name="enabled"> /// true to enable notification; false to disable a previously set notification. /// </param> /// <remarks> /// This should only be invoked from within an asynchronous method, /// and only by the debugger. /// </remarks> internal void SetNotificationForWaitCompletion(bool enabled) => SetNotificationForWaitCompletion(enabled, ref m_task); internal static void SetNotificationForWaitCompletion(bool enabled, [NotNull] ref Task<TResult>? taskField) { // Get the task (forcing initialization if not already initialized), and set debug notification (taskField ??= CreateWeaklyTypedStateMachineBox()).SetNotificationForWaitCompletion(enabled); // NOTE: It's important that the debugger use builder.SetNotificationForWaitCompletion // rather than builder.Task.SetNotificationForWaitCompletion. Even though the latter will // lazily-initialize the task as well, it'll initialize it to a Task<T> (which is important // to minimize size for cases where an ATMB is used directly by user code to avoid the // allocation overhead of a TaskCompletionSource). If that's done prior to the first await, // the GetMoveNextDelegate code, which needs an AsyncStateMachineBox, will end up creating // a new box and overwriting the previously created task. That'll change the object identity // of the task being used for wait completion notification, and no notification will // ever arrive, breaking step-out behavior when stepping out before the first yielding await. } /// <summary> /// Gets an object that may be used to uniquely identify this builder to the debugger. /// </summary> /// <remarks> /// This property lazily instantiates the ID in a non-thread-safe manner. /// It must only be used by the debugger and tracing purposes, and only in a single-threaded manner /// when no other threads are in the middle of accessing this or other members that lazily initialize the task. /// </remarks> internal object ObjectIdForDebugger => m_task ??= CreateWeaklyTypedStateMachineBox(); /// <summary> /// Gets a task for the specified result. This will either /// be a cached or new task, never null. /// </summary> /// <param name="result">The result for which we need a task.</param> /// <returns>The completed task containing the result.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] // method looks long, but for a given TResult it results in a relatively small amount of asm internal static Task<TResult> GetTaskForResult(TResult result) { // The goal of this function is to be give back a cached task if possible, // or to otherwise give back a new task. To give back a cached task, // we need to be able to evaluate the incoming result value, and we need // to avoid as much overhead as possible when doing so, as this function // is invoked as part of the return path from every async method. // Most tasks won't be cached, and thus we need the checks for those that are // to be as close to free as possible. This requires some trickiness given the // lack of generic specialization in .NET. // // Be very careful when modifying this code. It has been tuned // to comply with patterns recognized by both 32-bit and 64-bit JITs. // If changes are made here, be sure to look at the generated assembly, as // small tweaks can have big consequences for what does and doesn't get optimized away. // // Note that this code only ever accesses a static field when it knows it'll // find a cached value, since static fields (even if readonly and integral types) // require special access helpers in this NGEN'd and domain-neutral. if (null != (object)default(TResult)!) // help the JIT avoid the value type branches for ref types // TODO-NULLABLE: default(T) == null warning (https://github.com/dotnet/roslyn/issues/34757) { // Special case simple value types: // - Boolean // - Byte, SByte // - Char // - Int32, UInt32 // - Int64, UInt64 // - Int16, UInt16 // - IntPtr, UIntPtr // As of .NET 4.5, the (Type)(object)result pattern used below // is recognized and optimized by both 32-bit and 64-bit JITs. // For Boolean, we cache all possible values. if (typeof(TResult) == typeof(bool)) // only the relevant branches are kept for each value-type generic instantiation { bool value = (bool)(object)result!; Task<bool> task = value ? AsyncTaskCache.s_trueTask : AsyncTaskCache.s_falseTask; return Unsafe.As<Task<TResult>>(task); // UnsafeCast avoids type check we know will succeed } // For Int32, we cache a range of common values, e.g. [-1,9). else if (typeof(TResult) == typeof(int)) { // Compare to constants to avoid static field access if outside of cached range. // We compare to the upper bound first, as we're more likely to cache miss on the upper side than on the // lower side, due to positive values being more common than negative as return values. int value = (int)(object)result!; if (value < AsyncTaskCache.ExclusiveInt32Max && value >= AsyncTaskCache.InclusiveInt32Min) { Task<int> task = AsyncTaskCache.s_int32Tasks[value - AsyncTaskCache.InclusiveInt32Min]; return Unsafe.As<Task<TResult>>(task); // UnsafeCast avoids a type check we know will succeed } } // For other known value types, we only special-case 0 / default(TResult). else if ( (typeof(TResult) == typeof(uint) && default == (uint)(object)result!) || (typeof(TResult) == typeof(byte) && default(byte) == (byte)(object)result!) || (typeof(TResult) == typeof(sbyte) && default(sbyte) == (sbyte)(object)result!) || (typeof(TResult) == typeof(char) && default(char) == (char)(object)result!) || (typeof(TResult) == typeof(long) && default == (long)(object)result!) || (typeof(TResult) == typeof(ulong) && default == (ulong)(object)result!) || (typeof(TResult) == typeof(short) && default(short) == (short)(object)result!) || (typeof(TResult) == typeof(ushort) && default(ushort) == (ushort)(object)result!) || (typeof(TResult) == typeof(IntPtr) && default == (IntPtr)(object)result!) || (typeof(TResult) == typeof(UIntPtr) && default == (UIntPtr)(object)result!)) { return s_defaultResultTask; } } else if (result == null) // optimized away for value types { return s_defaultResultTask; } // No cached task is available. Manufacture a new one for this result. return new Task<TResult>(result); } } }
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 WebDemo.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; } } }
namespace Blog.Migrations { using System; using System.Collections.Generic; using System.Data.Entity.Infrastructure.Annotations; using System.Data.Entity.Migrations; public partial class InitialData : DbMigration { public override void Up() { CreateTable( "dbo.AbpAuditLogs", c => new { Id = c.Long(nullable: false, identity: true), TenantId = c.Int(), UserId = c.Long(), ServiceName = c.String(maxLength: 256), MethodName = c.String(maxLength: 256), Parameters = c.String(maxLength: 1024), ExecutionTime = c.DateTime(nullable: false), ExecutionDuration = c.Int(nullable: false), ClientIpAddress = c.String(maxLength: 64), ClientName = c.String(maxLength: 128), BrowserInfo = c.String(maxLength: 256), Exception = c.String(maxLength: 2000), ImpersonatorUserId = c.Long(), ImpersonatorTenantId = c.Int(), CustomData = c.String(maxLength: 2000), }, annotations: new Dictionary<string, object> { { "DynamicFilter_AuditLog_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }) .PrimaryKey(t => t.Id); CreateTable( "dbo.AbpBackgroundJobs", c => new { Id = c.Long(nullable: false, identity: true), JobType = c.String(nullable: false, maxLength: 512), JobArgs = c.String(nullable: false), TryCount = c.Short(nullable: false), NextTryTime = c.DateTime(nullable: false), LastTryTime = c.DateTime(), IsAbandoned = c.Boolean(nullable: false), Priority = c.Byte(nullable: false), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), }) .PrimaryKey(t => t.Id) .Index(t => new { t.IsAbandoned, t.NextTryTime }); CreateTable( "dbo.AbpFeatures", c => new { Id = c.Long(nullable: false, identity: true), Name = c.String(nullable: false, maxLength: 128), Value = c.String(nullable: false, maxLength: 2000), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), EditionId = c.Int(), TenantId = c.Int(), Discriminator = c.String(nullable: false, maxLength: 128), }, annotations: new Dictionary<string, object> { { "DynamicFilter_TenantFeatureSetting_MustHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.AbpEditions", t => t.EditionId, cascadeDelete: true) .Index(t => t.EditionId); CreateTable( "dbo.AbpEditions", c => new { Id = c.Int(nullable: false, identity: true), Name = c.String(nullable: false, maxLength: 32), DisplayName = c.String(nullable: false, maxLength: 64), IsDeleted = c.Boolean(nullable: false), DeleterUserId = c.Long(), DeletionTime = c.DateTime(), LastModificationTime = c.DateTime(), LastModifierUserId = c.Long(), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), }, annotations: new Dictionary<string, object> { { "DynamicFilter_Edition_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }) .PrimaryKey(t => t.Id); CreateTable( "dbo.AbpLanguages", c => new { Id = c.Int(nullable: false, identity: true), TenantId = c.Int(), Name = c.String(nullable: false, maxLength: 10), DisplayName = c.String(nullable: false, maxLength: 64), Icon = c.String(maxLength: 128), IsDeleted = c.Boolean(nullable: false), DeleterUserId = c.Long(), DeletionTime = c.DateTime(), LastModificationTime = c.DateTime(), LastModifierUserId = c.Long(), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), }, annotations: new Dictionary<string, object> { { "DynamicFilter_ApplicationLanguage_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, { "DynamicFilter_ApplicationLanguage_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }) .PrimaryKey(t => t.Id); CreateTable( "dbo.AbpLanguageTexts", c => new { Id = c.Long(nullable: false, identity: true), TenantId = c.Int(), LanguageName = c.String(nullable: false, maxLength: 10), Source = c.String(nullable: false, maxLength: 128), Key = c.String(nullable: false, maxLength: 256), Value = c.String(nullable: false), LastModificationTime = c.DateTime(), LastModifierUserId = c.Long(), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), }, annotations: new Dictionary<string, object> { { "DynamicFilter_ApplicationLanguageText_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }) .PrimaryKey(t => t.Id); CreateTable( "dbo.AbpNotifications", c => new { Id = c.Guid(nullable: false), NotificationName = c.String(nullable: false, maxLength: 96), Data = c.String(), DataTypeName = c.String(maxLength: 512), EntityTypeName = c.String(maxLength: 250), EntityTypeAssemblyQualifiedName = c.String(maxLength: 512), EntityId = c.String(maxLength: 96), Severity = c.Byte(nullable: false), UserIds = c.String(), ExcludedUserIds = c.String(), TenantIds = c.String(), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), }) .PrimaryKey(t => t.Id); CreateTable( "dbo.AbpNotificationSubscriptions", c => new { Id = c.Guid(nullable: false), TenantId = c.Int(), UserId = c.Long(nullable: false), NotificationName = c.String(maxLength: 96), EntityTypeName = c.String(maxLength: 250), EntityTypeAssemblyQualifiedName = c.String(maxLength: 512), EntityId = c.String(maxLength: 96), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), }, annotations: new Dictionary<string, object> { { "DynamicFilter_NotificationSubscriptionInfo_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }) .PrimaryKey(t => t.Id) .Index(t => new { t.NotificationName, t.EntityTypeName, t.EntityId, t.UserId }); CreateTable( "dbo.AbpOrganizationUnits", c => new { Id = c.Long(nullable: false, identity: true), TenantId = c.Int(), ParentId = c.Long(), Code = c.String(nullable: false, maxLength: 95), DisplayName = c.String(nullable: false, maxLength: 128), IsDeleted = c.Boolean(nullable: false), DeleterUserId = c.Long(), DeletionTime = c.DateTime(), LastModificationTime = c.DateTime(), LastModifierUserId = c.Long(), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), }, annotations: new Dictionary<string, object> { { "DynamicFilter_OrganizationUnit_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, { "DynamicFilter_OrganizationUnit_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.AbpOrganizationUnits", t => t.ParentId) .Index(t => t.ParentId); CreateTable( "dbo.AbpPermissions", c => new { Id = c.Long(nullable: false, identity: true), TenantId = c.Int(), Name = c.String(nullable: false, maxLength: 128), IsGranted = c.Boolean(nullable: false), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), RoleId = c.Int(), UserId = c.Long(), Discriminator = c.String(nullable: false, maxLength: 128), }, annotations: new Dictionary<string, object> { { "DynamicFilter_PermissionSetting_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, { "DynamicFilter_RolePermissionSetting_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, { "DynamicFilter_UserPermissionSetting_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.AbpUsers", t => t.UserId, cascadeDelete: true) .ForeignKey("dbo.AbpRoles", t => t.RoleId, cascadeDelete: true) .Index(t => t.RoleId) .Index(t => t.UserId); CreateTable( "dbo.AbpRoles", c => new { Id = c.Int(nullable: false, identity: true), DisplayName = c.String(nullable: false, maxLength: 64), IsStatic = c.Boolean(nullable: false), IsDefault = c.Boolean(nullable: false), TenantId = c.Int(), Name = c.String(nullable: false, maxLength: 32), IsDeleted = c.Boolean(nullable: false), DeleterUserId = c.Long(), DeletionTime = c.DateTime(), LastModificationTime = c.DateTime(), LastModifierUserId = c.Long(), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), }, annotations: new Dictionary<string, object> { { "DynamicFilter_Role_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, { "DynamicFilter_Role_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.AbpUsers", t => t.CreatorUserId) .ForeignKey("dbo.AbpUsers", t => t.DeleterUserId) .ForeignKey("dbo.AbpUsers", t => t.LastModifierUserId) .Index(t => t.DeleterUserId) .Index(t => t.LastModifierUserId) .Index(t => t.CreatorUserId); CreateTable( "dbo.AbpUsers", c => new { Id = c.Long(nullable: false, identity: true), AuthenticationSource = c.String(maxLength: 64), Name = c.String(nullable: false, maxLength: 32), Surname = c.String(nullable: false, maxLength: 32), Password = c.String(nullable: false, maxLength: 128), IsEmailConfirmed = c.Boolean(nullable: false), EmailConfirmationCode = c.String(maxLength: 328), PasswordResetCode = c.String(maxLength: 328), LockoutEndDateUtc = c.DateTime(), AccessFailedCount = c.Int(nullable: false), IsLockoutEnabled = c.Boolean(nullable: false), PhoneNumber = c.String(), IsPhoneNumberConfirmed = c.Boolean(nullable: false), SecurityStamp = c.String(), IsTwoFactorEnabled = c.Boolean(nullable: false), IsActive = c.Boolean(nullable: false), UserName = c.String(nullable: false, maxLength: 32), TenantId = c.Int(), EmailAddress = c.String(nullable: false, maxLength: 256), LastLoginTime = c.DateTime(), IsDeleted = c.Boolean(nullable: false), DeleterUserId = c.Long(), DeletionTime = c.DateTime(), LastModificationTime = c.DateTime(), LastModifierUserId = c.Long(), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), }, annotations: new Dictionary<string, object> { { "DynamicFilter_User_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, { "DynamicFilter_User_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.AbpUsers", t => t.CreatorUserId) .ForeignKey("dbo.AbpUsers", t => t.DeleterUserId) .ForeignKey("dbo.AbpUsers", t => t.LastModifierUserId) .Index(t => t.DeleterUserId) .Index(t => t.LastModifierUserId) .Index(t => t.CreatorUserId); CreateTable( "dbo.AbpUserClaims", c => new { Id = c.Long(nullable: false, identity: true), TenantId = c.Int(), UserId = c.Long(nullable: false), ClaimType = c.String(), ClaimValue = c.String(), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), }, annotations: new Dictionary<string, object> { { "DynamicFilter_UserClaim_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.AbpUsers", t => t.UserId, cascadeDelete: true) .Index(t => t.UserId); CreateTable( "dbo.AbpUserLogins", c => new { Id = c.Long(nullable: false, identity: true), TenantId = c.Int(), UserId = c.Long(nullable: false), LoginProvider = c.String(nullable: false, maxLength: 128), ProviderKey = c.String(nullable: false, maxLength: 256), }, annotations: new Dictionary<string, object> { { "DynamicFilter_UserLogin_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.AbpUsers", t => t.UserId, cascadeDelete: true) .Index(t => t.UserId); CreateTable( "dbo.AbpUserRoles", c => new { Id = c.Long(nullable: false, identity: true), TenantId = c.Int(), UserId = c.Long(nullable: false), RoleId = c.Int(nullable: false), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), }, annotations: new Dictionary<string, object> { { "DynamicFilter_UserRole_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.AbpUsers", t => t.UserId, cascadeDelete: true) .Index(t => t.UserId); CreateTable( "dbo.AbpSettings", c => new { Id = c.Long(nullable: false, identity: true), TenantId = c.Int(), UserId = c.Long(), Name = c.String(nullable: false, maxLength: 256), Value = c.String(maxLength: 2000), LastModificationTime = c.DateTime(), LastModifierUserId = c.Long(), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), }, annotations: new Dictionary<string, object> { { "DynamicFilter_Setting_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.AbpUsers", t => t.UserId) .Index(t => t.UserId); CreateTable( "dbo.AbpTenantNotifications", c => new { Id = c.Guid(nullable: false), TenantId = c.Int(), NotificationName = c.String(nullable: false, maxLength: 96), Data = c.String(), DataTypeName = c.String(maxLength: 512), EntityTypeName = c.String(maxLength: 250), EntityTypeAssemblyQualifiedName = c.String(maxLength: 512), EntityId = c.String(maxLength: 96), Severity = c.Byte(nullable: false), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), }, annotations: new Dictionary<string, object> { { "DynamicFilter_TenantNotificationInfo_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }) .PrimaryKey(t => t.Id); CreateTable( "dbo.AbpTenants", c => new { Id = c.Int(nullable: false, identity: true), EditionId = c.Int(), Name = c.String(nullable: false, maxLength: 128), IsActive = c.Boolean(nullable: false), TenancyName = c.String(nullable: false, maxLength: 64), ConnectionString = c.String(maxLength: 1024), IsDeleted = c.Boolean(nullable: false), DeleterUserId = c.Long(), DeletionTime = c.DateTime(), LastModificationTime = c.DateTime(), LastModifierUserId = c.Long(), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), }, annotations: new Dictionary<string, object> { { "DynamicFilter_Tenant_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.AbpUsers", t => t.CreatorUserId) .ForeignKey("dbo.AbpUsers", t => t.DeleterUserId) .ForeignKey("dbo.AbpEditions", t => t.EditionId) .ForeignKey("dbo.AbpUsers", t => t.LastModifierUserId) .Index(t => t.EditionId) .Index(t => t.DeleterUserId) .Index(t => t.LastModifierUserId) .Index(t => t.CreatorUserId); CreateTable( "dbo.AbpUserAccounts", c => new { Id = c.Long(nullable: false, identity: true), TenantId = c.Int(), UserId = c.Long(nullable: false), UserLinkId = c.Long(), UserName = c.String(), EmailAddress = c.String(), LastLoginTime = c.DateTime(), IsDeleted = c.Boolean(nullable: false), DeleterUserId = c.Long(), DeletionTime = c.DateTime(), LastModificationTime = c.DateTime(), LastModifierUserId = c.Long(), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), }, annotations: new Dictionary<string, object> { { "DynamicFilter_UserAccount_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }) .PrimaryKey(t => t.Id); CreateTable( "dbo.AbpUserLoginAttempts", c => new { Id = c.Long(nullable: false, identity: true), TenantId = c.Int(), TenancyName = c.String(maxLength: 64), UserId = c.Long(), UserNameOrEmailAddress = c.String(maxLength: 255), ClientIpAddress = c.String(maxLength: 64), ClientName = c.String(maxLength: 128), BrowserInfo = c.String(maxLength: 256), Result = c.Byte(nullable: false), CreationTime = c.DateTime(nullable: false), }, annotations: new Dictionary<string, object> { { "DynamicFilter_UserLoginAttempt_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }) .PrimaryKey(t => t.Id) .Index(t => new { t.UserId, t.TenantId }) .Index(t => new { t.TenancyName, t.UserNameOrEmailAddress, t.Result }); CreateTable( "dbo.AbpUserNotifications", c => new { Id = c.Guid(nullable: false), TenantId = c.Int(), UserId = c.Long(nullable: false), TenantNotificationId = c.Guid(nullable: false), State = c.Int(nullable: false), CreationTime = c.DateTime(nullable: false), }, annotations: new Dictionary<string, object> { { "DynamicFilter_UserNotificationInfo_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }) .PrimaryKey(t => t.Id) .Index(t => new { t.UserId, t.State, t.CreationTime }); CreateTable( "dbo.AbpUserOrganizationUnits", c => new { Id = c.Long(nullable: false, identity: true), TenantId = c.Int(), UserId = c.Long(nullable: false), OrganizationUnitId = c.Long(nullable: false), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), }, annotations: new Dictionary<string, object> { { "DynamicFilter_UserOrganizationUnit_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }) .PrimaryKey(t => t.Id); } public override void Down() { DropForeignKey("dbo.AbpTenants", "LastModifierUserId", "dbo.AbpUsers"); DropForeignKey("dbo.AbpTenants", "EditionId", "dbo.AbpEditions"); DropForeignKey("dbo.AbpTenants", "DeleterUserId", "dbo.AbpUsers"); DropForeignKey("dbo.AbpTenants", "CreatorUserId", "dbo.AbpUsers"); DropForeignKey("dbo.AbpPermissions", "RoleId", "dbo.AbpRoles"); DropForeignKey("dbo.AbpRoles", "LastModifierUserId", "dbo.AbpUsers"); DropForeignKey("dbo.AbpRoles", "DeleterUserId", "dbo.AbpUsers"); DropForeignKey("dbo.AbpRoles", "CreatorUserId", "dbo.AbpUsers"); DropForeignKey("dbo.AbpSettings", "UserId", "dbo.AbpUsers"); DropForeignKey("dbo.AbpUserRoles", "UserId", "dbo.AbpUsers"); DropForeignKey("dbo.AbpPermissions", "UserId", "dbo.AbpUsers"); DropForeignKey("dbo.AbpUserLogins", "UserId", "dbo.AbpUsers"); DropForeignKey("dbo.AbpUsers", "LastModifierUserId", "dbo.AbpUsers"); DropForeignKey("dbo.AbpUsers", "DeleterUserId", "dbo.AbpUsers"); DropForeignKey("dbo.AbpUsers", "CreatorUserId", "dbo.AbpUsers"); DropForeignKey("dbo.AbpUserClaims", "UserId", "dbo.AbpUsers"); DropForeignKey("dbo.AbpOrganizationUnits", "ParentId", "dbo.AbpOrganizationUnits"); DropForeignKey("dbo.AbpFeatures", "EditionId", "dbo.AbpEditions"); DropIndex("dbo.AbpUserNotifications", new[] { "UserId", "State", "CreationTime" }); DropIndex("dbo.AbpUserLoginAttempts", new[] { "TenancyName", "UserNameOrEmailAddress", "Result" }); DropIndex("dbo.AbpUserLoginAttempts", new[] { "UserId", "TenantId" }); DropIndex("dbo.AbpTenants", new[] { "CreatorUserId" }); DropIndex("dbo.AbpTenants", new[] { "LastModifierUserId" }); DropIndex("dbo.AbpTenants", new[] { "DeleterUserId" }); DropIndex("dbo.AbpTenants", new[] { "EditionId" }); DropIndex("dbo.AbpSettings", new[] { "UserId" }); DropIndex("dbo.AbpUserRoles", new[] { "UserId" }); DropIndex("dbo.AbpUserLogins", new[] { "UserId" }); DropIndex("dbo.AbpUserClaims", new[] { "UserId" }); DropIndex("dbo.AbpUsers", new[] { "CreatorUserId" }); DropIndex("dbo.AbpUsers", new[] { "LastModifierUserId" }); DropIndex("dbo.AbpUsers", new[] { "DeleterUserId" }); DropIndex("dbo.AbpRoles", new[] { "CreatorUserId" }); DropIndex("dbo.AbpRoles", new[] { "LastModifierUserId" }); DropIndex("dbo.AbpRoles", new[] { "DeleterUserId" }); DropIndex("dbo.AbpPermissions", new[] { "UserId" }); DropIndex("dbo.AbpPermissions", new[] { "RoleId" }); DropIndex("dbo.AbpOrganizationUnits", new[] { "ParentId" }); DropIndex("dbo.AbpNotificationSubscriptions", new[] { "NotificationName", "EntityTypeName", "EntityId", "UserId" }); DropIndex("dbo.AbpFeatures", new[] { "EditionId" }); DropIndex("dbo.AbpBackgroundJobs", new[] { "IsAbandoned", "NextTryTime" }); DropTable("dbo.AbpUserOrganizationUnits", removedAnnotations: new Dictionary<string, object> { { "DynamicFilter_UserOrganizationUnit_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }); DropTable("dbo.AbpUserNotifications", removedAnnotations: new Dictionary<string, object> { { "DynamicFilter_UserNotificationInfo_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }); DropTable("dbo.AbpUserLoginAttempts", removedAnnotations: new Dictionary<string, object> { { "DynamicFilter_UserLoginAttempt_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }); DropTable("dbo.AbpUserAccounts", removedAnnotations: new Dictionary<string, object> { { "DynamicFilter_UserAccount_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }); DropTable("dbo.AbpTenants", removedAnnotations: new Dictionary<string, object> { { "DynamicFilter_Tenant_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }); DropTable("dbo.AbpTenantNotifications", removedAnnotations: new Dictionary<string, object> { { "DynamicFilter_TenantNotificationInfo_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }); DropTable("dbo.AbpSettings", removedAnnotations: new Dictionary<string, object> { { "DynamicFilter_Setting_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }); DropTable("dbo.AbpUserRoles", removedAnnotations: new Dictionary<string, object> { { "DynamicFilter_UserRole_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }); DropTable("dbo.AbpUserLogins", removedAnnotations: new Dictionary<string, object> { { "DynamicFilter_UserLogin_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }); DropTable("dbo.AbpUserClaims", removedAnnotations: new Dictionary<string, object> { { "DynamicFilter_UserClaim_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }); DropTable("dbo.AbpUsers", removedAnnotations: new Dictionary<string, object> { { "DynamicFilter_User_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, { "DynamicFilter_User_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }); DropTable("dbo.AbpRoles", removedAnnotations: new Dictionary<string, object> { { "DynamicFilter_Role_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, { "DynamicFilter_Role_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }); DropTable("dbo.AbpPermissions", removedAnnotations: new Dictionary<string, object> { { "DynamicFilter_PermissionSetting_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, { "DynamicFilter_RolePermissionSetting_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, { "DynamicFilter_UserPermissionSetting_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }); DropTable("dbo.AbpOrganizationUnits", removedAnnotations: new Dictionary<string, object> { { "DynamicFilter_OrganizationUnit_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, { "DynamicFilter_OrganizationUnit_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }); DropTable("dbo.AbpNotificationSubscriptions", removedAnnotations: new Dictionary<string, object> { { "DynamicFilter_NotificationSubscriptionInfo_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }); DropTable("dbo.AbpNotifications"); DropTable("dbo.AbpLanguageTexts", removedAnnotations: new Dictionary<string, object> { { "DynamicFilter_ApplicationLanguageText_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }); DropTable("dbo.AbpLanguages", removedAnnotations: new Dictionary<string, object> { { "DynamicFilter_ApplicationLanguage_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, { "DynamicFilter_ApplicationLanguage_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }); DropTable("dbo.AbpEditions", removedAnnotations: new Dictionary<string, object> { { "DynamicFilter_Edition_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }); DropTable("dbo.AbpFeatures", removedAnnotations: new Dictionary<string, object> { { "DynamicFilter_TenantFeatureSetting_MustHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }); DropTable("dbo.AbpBackgroundJobs"); DropTable("dbo.AbpAuditLogs", removedAnnotations: new Dictionary<string, object> { { "DynamicFilter_AuditLog_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }); } } }
using System; using System.Collections.Generic; using System.Text; using System.Diagnostics; namespace ExtraLayers.LZ4 { /// <summary> /// Class for compressing a byte array into an LZ4 byte array. /// </summary> public unsafe class LZ4Compressor64 : ILZ4Compressor { //************************************** // Tuning parameters //************************************** // COMPRESSIONLEVEL : // Increasing this value improves compression ratio // Lowering this value reduces memory usage // Reduced memory usage typically improves speed, due to cache effect (ex : L1 32KB for Intel, L1 64KB for AMD) // Memory usage formula : N->2^(N+2) Bytes (examples : 12 -> 16KB ; 17 -> 512KB) const int COMPRESSIONLEVEL = 12; // NOTCOMPRESSIBLE_CONFIRMATION : // Decreasing this value will make the algorithm skip faster data segments considered "incompressible" // This may decrease compression ratio dramatically, but will be faster on incompressible data // Increasing this value will make the algorithm search more before declaring a segment "incompressible" // This could improve compression a bit, but will be slower on incompressible data // The default value (6) is recommended // 2 is the minimum value. const int NOTCOMPRESSIBLE_CONFIRMATION = 6; //************************************** // Constants //************************************** const int HASH_LOG = COMPRESSIONLEVEL; const int MAXD_LOG = 16; const int MAX_DISTANCE = ((1 << MAXD_LOG) - 1); const int MINMATCH = 4; const int MFLIMIT = (LZ4Util.COPYLENGTH + MINMATCH); const int MINLENGTH = (MFLIMIT + 1); const uint LZ4_64KLIMIT = ((1U << 16) + (MFLIMIT - 1)); const int HASHLOG64K = (HASH_LOG + 1); const int HASHTABLESIZE = (1 << HASH_LOG); const int HASH_MASK = (HASHTABLESIZE - 1); const int LASTLITERALS = 5; const int SKIPSTRENGTH = (NOTCOMPRESSIBLE_CONFIRMATION > 2 ? NOTCOMPRESSIBLE_CONFIRMATION : 2); const int SIZE_OF_LONG_TIMES_TWO_SHIFT = 4; const int STEPSIZE = 8; static byte[] DeBruijnBytePos = new byte[64] { 0, 0, 0, 0, 0, 1, 1, 2, 0, 3, 1, 3, 1, 4, 2, 7, 0, 2, 3, 6, 1, 5, 3, 5, 1, 3, 4, 4, 2, 5, 6, 7, 7, 0, 1, 2, 3, 3, 4, 6, 2, 6, 5, 5, 3, 4, 5, 6, 7, 1, 2, 4, 6, 4, 4, 5, 7, 2, 6, 5, 7, 6, 7, 7 }; //************************************** // Macros //************************************** byte[] m_HashTable; public LZ4Compressor64() { m_HashTable = new byte[HASHTABLESIZE * IntPtr.Size]; if (m_HashTable.Length % 16 != 0) throw new Exception("Hash table size must be divisible by 16"); } public byte[] Compress(byte[] source) { int maxCompressedSize = CalculateMaxCompressedLength(source.Length); byte[] dst = new byte[maxCompressedSize]; int length = Compress(source, dst); byte[] dest = new byte[length]; Buffer.BlockCopy(dst, 0, dest, 0, length); return dest; } /// <summary> /// Calculate the max compressed byte[] size given the size of the uncompressed byte[] /// </summary> /// <param name="uncompressedLength">Length of the uncompressed data</param> /// <returns>The maximum required size in bytes of the compressed data</returns> public int CalculateMaxCompressedLength(int uncompressedLength) { return uncompressedLength + (uncompressedLength / 255) + 16; } /// <summary> /// Compress source into dest returning compressed length /// </summary> /// <param name="source">uncompressed data</param> /// <param name="dest">array into which source will be compressed</param> /// <returns>compressed length</returns> public int Compress(byte[] source, byte[] dest) { fixed (byte* s = source) fixed (byte* d = dest) { if (source.Length < (int)LZ4_64KLIMIT) return Compress64K(s, d, source.Length, dest.Length); return Compress(s, d, source.Length, dest.Length); } } /// <summary> /// Compress source into dest returning compressed length /// </summary> /// <param name="source">uncompressed data</param> /// <param name="srcOffset">offset in source array where reading will start</param> /// <param name="count">count of bytes in source array to compress</param> /// <param name="dest">array into which source will be compressed</param> /// <param name="dstOffset">start index in dest array where writing will start</param> /// <returns>compressed length</returns> public int Compress(byte[] source, int srcOffset, int count, byte[] dest, int dstOffset) { fixed (byte* s = &source[srcOffset]) fixed (byte* d = &dest[dstOffset]) { if (source.Length < (int)LZ4_64KLIMIT) return Compress64K(s, d, count, dest.Length - dstOffset); return Compress(s, d, count, dest.Length - dstOffset); } } int Compress(byte* source, byte* dest, int isize, int maxOutputSize) { fixed (byte* hashTablePtr = m_HashTable) fixed (byte* deBruijnBytePos = DeBruijnBytePos) { Clear(hashTablePtr, sizeof(byte*) * HASHTABLESIZE); byte** hashTable = (byte**)hashTablePtr; byte* ip = (byte*)source; long basePtr = (long)ip; byte* anchor = ip; byte* iend = ip + isize; byte* mflimit = iend - MFLIMIT; byte* matchlimit = (iend - LASTLITERALS); byte* oend = dest + maxOutputSize; byte* op = (byte*)dest; int len, length; const int skipStrength = SKIPSTRENGTH; uint forwardH; // Init if (isize < MINLENGTH) goto _last_literals; // First Byte hashTable[(((*(uint*)ip) * 2654435761U) >> ((MINMATCH * 8) - HASH_LOG))] = ip - basePtr; ip++; forwardH = (((*(uint*)ip) * 2654435761U) >> ((MINMATCH * 8) - HASH_LOG)); // Main Loop for (; ; ) { uint findMatchAttempts = (1U << skipStrength) + 3; byte* forwardIp = ip; byte* r; byte* token; // Find a match do { uint h = forwardH; uint step = findMatchAttempts++ >> skipStrength; ip = forwardIp; forwardIp = ip + step; if (forwardIp > mflimit) { goto _last_literals; } // LZ4_HASH_VALUE forwardH = (((*(uint*)forwardIp) * 2654435761U) >> ((MINMATCH * 8) - HASH_LOG)); r = hashTable[h] + basePtr; hashTable[h] = ip - basePtr; } while ((r < ip - MAX_DISTANCE) || (*(uint*)r != *(uint*)ip)); // Catch up while ((ip > anchor) && (r > (byte*)source) && (ip[-1] == r[-1])) { ip--; r--; } // Encode Literal Length length = (int)(ip - anchor); token = op++; if (length >= (int)LZ4Util.RUN_MASK) { *token = (byte)(LZ4Util.RUN_MASK << LZ4Util.ML_BITS); len = (int)(length - LZ4Util.RUN_MASK); for (; len > 254; len -= 255) *op++ = 255; *op++ = (byte)len; } else *token = (byte)(length << LZ4Util.ML_BITS); //Copy Literals { byte* e = (op) + length; do { *(ulong*)op = *(ulong*)anchor; op += 8; anchor += 8; } while (op < e);; op = e; }; _next_match: // Encode Offset *(ushort*)op = (ushort)(ip - r); op += 2; // Start Counting ip += MINMATCH; r += MINMATCH; // MinMatch verified anchor = ip; // while (*(uint *)r == *(uint *)ip) // { // ip+=4; r+=4; // if (ip>matchlimit-4) { r -= ip - (matchlimit-3); ip = matchlimit-3; break; } // } // if (*(ushort *)r == *(ushort *)ip) { ip+=2; r+=2; } // if (*r == *ip) ip++; while (ip < matchlimit - (STEPSIZE - 1)) { long diff = (long)(*(long*)(r) ^ *(long*)(ip)); if (diff == 0) { ip += STEPSIZE; r += STEPSIZE; continue; } ip += DeBruijnBytePos[((ulong)((diff & -diff) * 0x0218A392CDABBD3F)) >> 58]; ; goto _endCount; } if ((ip < (matchlimit - 3)) && (*(uint*)r == *(uint*)ip)) { ip += 4; r += 4; } if ((ip < (matchlimit - 1)) && (*(ushort*)(r) == *(ushort*)(ip))) { ip += 2; r += 2; } if ((ip < matchlimit) && (*r == *ip)) ip++; _endCount: len = (int)(ip - anchor); if (op + (1 + LASTLITERALS) + (len >> 8) >= oend) return 0; // Check output limit // Encode MatchLength if (len >= (int)LZ4Util.ML_MASK) { *token += (byte)LZ4Util.ML_MASK; len -= (byte)LZ4Util.ML_MASK; for (; len > 509; len -= 510) { *op++ = 255; *op++ = 255; } if (len > 254) { len -= 255; *op++ = 255; } *op++ = (byte)len; } else *token += (byte)len; // Test end of chunk if (ip > mflimit) { anchor = ip; break; } // Fill table hashTable[(((*(uint*)ip - 2) * 2654435761U) >> ((MINMATCH * 8) - HASH_LOG))] = ip - 2 - basePtr; // Test next position r = basePtr + hashTable[(((*(uint*)ip) * 2654435761U) >> ((MINMATCH * 8) - HASH_LOG))]; hashTable[(((*(uint*)ip) * 2654435761U) >> ((MINMATCH * 8) - HASH_LOG))] = ip - basePtr; if ((r > ip - (MAX_DISTANCE + 1)) && (*(uint*)r == *(uint*)ip)) { token = op++; *token = 0; goto _next_match; } // Prepare next loop anchor = ip++; forwardH = (((*(uint*)ip) * 2654435761U) >> ((MINMATCH * 8) - HASH_LOG)); } _last_literals: // Encode Last Literals { int lastRun = (int)(iend - anchor); if (((byte*)op - dest) + lastRun + 1 + ((lastRun - 15) / 255) >= maxOutputSize) return 0; if (lastRun >= (int)LZ4Util.RUN_MASK) { *op++ = (byte)(LZ4Util.RUN_MASK << LZ4Util.ML_BITS); lastRun -= (byte)LZ4Util.RUN_MASK; for (; lastRun > 254; lastRun -= 255) *op++ = 255; *op++ = (byte)lastRun; } else *op++ = (byte)(lastRun << LZ4Util.ML_BITS); LZ4Util.CopyMemory(op, anchor, iend - anchor); op += iend - anchor; } // End return (int)(((byte*)op) - dest); } } // Note : this function is valid only if isize < LZ4_64KLIMIT int Compress64K(byte* source, byte* dest, int isize, int maxOutputSize) { fixed (byte* hashTablePtr = m_HashTable) fixed (byte* deBruijnBytePos = DeBruijnBytePos) { Clear(hashTablePtr, sizeof(ushort) * HASHTABLESIZE * 2); ushort* hashTable = (ushort*)hashTablePtr; byte* ip = (byte*)source; byte* anchor = ip; byte* basep = ip; byte* iend = ip + isize; byte* mflimit = iend - MFLIMIT; byte* matchlimit = (iend - LASTLITERALS); byte* op = (byte*)dest; byte* oend = dest + maxOutputSize; int len, length; const int skipStrength = SKIPSTRENGTH; uint forwardH; // Init if (isize < MINLENGTH) goto _last_literals; // First Byte ip++; forwardH = (((*(uint*)ip) * 2654435761U) >> ((MINMATCH * 8) - (HASH_LOG + 1))); // Main Loop for (; ; ) { int findMatchAttempts = (int)(1U << skipStrength) + 3; byte* forwardIp = ip; byte* r; byte* token; // Find a match do { uint h = forwardH; int step = findMatchAttempts++ >> skipStrength; ip = forwardIp; forwardIp = ip + step; if (forwardIp > mflimit) { goto _last_literals; } forwardH = (((*(uint*)forwardIp) * 2654435761U) >> ((MINMATCH * 8) - (HASH_LOG + 1))); r = basep + hashTable[h]; hashTable[h] = (ushort)(ip - basep); } while (*(uint*)r != *(uint*)ip); // Catch up while ((ip > anchor) && (r > (byte*)source) && (ip[-1] == r[-1])) { ip--; r--; } // Encode Literal Length length = (int)(ip - anchor); token = op++; if (op + length + (2 + 1 + LASTLITERALS) + (length >> 8) >= oend) return 0; // Check output limit if (length >= (int)LZ4Util.RUN_MASK) { *token = (byte)(LZ4Util.RUN_MASK << LZ4Util.ML_BITS); len = (int)(length - LZ4Util.RUN_MASK); for (; len > 254; len -= 255) *op++ = 255; *op++ = (byte)len; } else *token = (byte)(length << LZ4Util.ML_BITS); // Copy Literals { byte* e = (op) + length; do { *(ulong*)op = *(ulong*)anchor; op += 8; anchor += 8; } while (op < e);; op = e; }; _next_match: // Encode Offset *(ushort*)op = (ushort)(ip - r); op += 2; // Start Counting ip += MINMATCH; r += MINMATCH; // MinMatch verified anchor = ip; // while (ip<matchlimit-3) // { // if (*(uint *)r == *(uint *)ip) { ip+=4; r+=4; continue; } // if (*(ushort *)r == *(ushort *)ip) { ip+=2; r+=2; } // if (*r == *ip) ip++; while (ip < matchlimit - (STEPSIZE - 1)) { long diff = (long)(*(long*)(r) ^ *(long*)(ip)); if (diff == 0) { ip += STEPSIZE; r += STEPSIZE; continue; } ip += DeBruijnBytePos[((ulong)((diff & -diff) * 0x0218A392CDABBD3F)) >> 58]; ; goto _endCount; } if ((ip < (matchlimit - 3)) && (*(uint*)r == *(uint*)ip)) { ip += 4; r += 4; } if ((ip < (matchlimit - 1)) && (*(ushort*)r == *(ushort*)ip)) { ip += 2; r += 2; } if ((ip < matchlimit) && (*r == *ip)) ip++; _endCount: len = (int)(ip - anchor); //Encode MatchLength if (len >= (int)LZ4Util.ML_MASK) { *token = (byte)(*token + LZ4Util.ML_MASK); len = (int)(len - LZ4Util.ML_MASK); for (; len > 509; len -= 510) { *op++ = 255; *op++ = 255; } if (len > 254) { len -= 255; *op++ = 255; } *op++ = (byte)len; } else *token = (byte)(*token + len); // Test end of chunk if (ip > mflimit) { anchor = ip; break; } // Fill table hashTable[(((*(uint*)ip - 2) * 2654435761U) >> ((MINMATCH * 8) - (HASH_LOG + 1)))] = (ushort)(ip - 2 - basep); // Test next position r = basep + hashTable[(((*(uint*)ip) * 2654435761U) >> ((MINMATCH * 8) - (HASH_LOG + 1)))]; hashTable[(((*(uint*)ip) * 2654435761U) >> ((MINMATCH * 8) - (HASH_LOG + 1)))] = (ushort)(ip - basep); if (*(uint*)r == *(uint*)ip) { token = op++; *token = 0; goto _next_match; } // Prepare next loop anchor = ip++; forwardH = (((*(uint*)ip) * 2654435761U) >> ((MINMATCH * 8) - (HASH_LOG + 1))); } _last_literals: { int lastRun = (int)(iend - anchor); if (((byte*)op - dest) + lastRun + 1 + ((lastRun) >> 8) >= maxOutputSize) return 0; if (lastRun >= (int)LZ4Util.RUN_MASK) { *op++ = (byte)(LZ4Util.RUN_MASK << LZ4Util.ML_BITS); lastRun -= (byte)LZ4Util.RUN_MASK; for (; lastRun > 254; lastRun -= 255) *op++ = 255; *op++ = (byte)lastRun; } else *op++ = (byte)(lastRun << LZ4Util.ML_BITS); LZ4Util.CopyMemory(op, anchor, iend - anchor); op += iend - anchor; } return (int)(((byte*)op) - dest); } } /// <summary> /// TODO: test if this is faster or slower than Array.Clear. /// </summary> /// <param name="array"></param> /// <param name="count"></param> static void Clear(byte* ptr, int count) { long* p = (long*)ptr; int longCount = count >> SIZE_OF_LONG_TIMES_TWO_SHIFT; // count / sizeof(long) * 2; while (longCount-- != 0) { *p++ = 0L; *p++ = 0L; } Debug.Assert(count % 16 == 0, "HashTable size must be divisible by 16"); //for (int i = longCount << 4 ; i < count; i++) // ptr[i] = 0; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Xml; using System.Reflection; using System.Reflection.Emit; using System.IO; using System.Security; using System.Diagnostics; #if !uapaot namespace System.Runtime.Serialization { internal class CodeGenerator { private static MethodInfo s_getTypeFromHandle; private static MethodInfo GetTypeFromHandle { get { if (s_getTypeFromHandle == null) { s_getTypeFromHandle = typeof(Type).GetMethod("GetTypeFromHandle"); Debug.Assert(s_getTypeFromHandle != null); } return s_getTypeFromHandle; } } private static MethodInfo s_objectEquals; private static MethodInfo ObjectEquals { get { if (s_objectEquals == null) { s_objectEquals = Globals.TypeOfObject.GetMethod("Equals", BindingFlags.Public | BindingFlags.Static); Debug.Assert(s_objectEquals != null); } return s_objectEquals; } } private static MethodInfo s_arraySetValue; private static MethodInfo ArraySetValue { get { if (s_arraySetValue == null) { s_arraySetValue = typeof(Array).GetMethod("SetValue", new Type[] { typeof(object), typeof(int) }); Debug.Assert(s_arraySetValue != null); } return s_arraySetValue; } } #if !uapaot private static MethodInfo s_objectToString; private static MethodInfo ObjectToString { get { if (s_objectToString == null) { s_objectToString = typeof(object).GetMethod("ToString", Array.Empty<Type>()); Debug.Assert(s_objectToString != null); } return s_objectToString; } } private static MethodInfo s_stringFormat; private static MethodInfo StringFormat { get { if (s_stringFormat == null) { s_stringFormat = typeof(string).GetMethod("Format", new Type[] { typeof(string), typeof(object[]) }); Debug.Assert(s_stringFormat != null); } return s_stringFormat; } } #endif private Type _delegateType; #if USE_REFEMIT AssemblyBuilder assemblyBuilder; ModuleBuilder moduleBuilder; TypeBuilder typeBuilder; static int typeCounter; MethodBuilder methodBuilder; #else private static Module s_serializationModule; private static Module SerializationModule { get { if (s_serializationModule == null) { s_serializationModule = typeof(CodeGenerator).Module; // could to be replaced by different dll that has SkipVerification set to false } return s_serializationModule; } } private DynamicMethod _dynamicMethod; #endif private ILGenerator _ilGen; private List<ArgBuilder> _argList; private Stack<object> _blockStack; private Label _methodEndLabel; private Dictionary<LocalBuilder, string> _localNames = new Dictionary<LocalBuilder, string>(); private enum CodeGenTrace { None, Save, Tron }; private CodeGenTrace _codeGenTrace; #if !uapaot private LocalBuilder _stringFormatArray; #endif internal CodeGenerator() { //Defaulting to None as thats the default value in WCF _codeGenTrace = CodeGenTrace.None; } #if !USE_REFEMIT internal void BeginMethod(DynamicMethod dynamicMethod, Type delegateType, string methodName, Type[] argTypes, bool allowPrivateMemberAccess) { _dynamicMethod = dynamicMethod; _ilGen = _dynamicMethod.GetILGenerator(); _delegateType = delegateType; InitILGeneration(methodName, argTypes); } #endif internal void BeginMethod(string methodName, Type delegateType, bool allowPrivateMemberAccess) { MethodInfo signature = delegateType.GetMethod("Invoke"); ParameterInfo[] parameters = signature.GetParameters(); Type[] paramTypes = new Type[parameters.Length]; for (int i = 0; i < parameters.Length; i++) paramTypes[i] = parameters[i].ParameterType; BeginMethod(signature.ReturnType, methodName, paramTypes, allowPrivateMemberAccess); _delegateType = delegateType; } private void BeginMethod(Type returnType, string methodName, Type[] argTypes, bool allowPrivateMemberAccess) { #if USE_REFEMIT string typeName = "Type" + (typeCounter++); InitAssemblyBuilder(typeName + "." + methodName); this.typeBuilder = moduleBuilder.DefineType(typeName, TypeAttributes.Public); this.methodBuilder = typeBuilder.DefineMethod(methodName, MethodAttributes.Public|MethodAttributes.Static, returnType, argTypes); this.ilGen = this.methodBuilder.GetILGenerator(); #else _dynamicMethod = new DynamicMethod(methodName, returnType, argTypes, SerializationModule, allowPrivateMemberAccess); _ilGen = _dynamicMethod.GetILGenerator(); #endif InitILGeneration(methodName, argTypes); } private void InitILGeneration(string methodName, Type[] argTypes) { _methodEndLabel = _ilGen.DefineLabel(); _blockStack = new Stack<object>(); _argList = new List<ArgBuilder>(); for (int i = 0; i < argTypes.Length; i++) _argList.Add(new ArgBuilder(i, argTypes[i])); if (_codeGenTrace != CodeGenTrace.None) EmitSourceLabel("Begin method " + methodName + " {"); } internal Delegate EndMethod() { MarkLabel(_methodEndLabel); if (_codeGenTrace != CodeGenTrace.None) EmitSourceLabel("} End method"); Ret(); Delegate retVal = null; #if USE_REFEMIT Type type = typeBuilder.CreateType(); MethodInfo method = type.GetMethod(methodBuilder.Name); retVal = Delegate.CreateDelegate(delegateType, method); methodBuilder = null; #else retVal = _dynamicMethod.CreateDelegate(_delegateType); _dynamicMethod = null; #endif _delegateType = null; _ilGen = null; _blockStack = null; _argList = null; return retVal; } internal MethodInfo CurrentMethod { get { #if USE_REFEMIT return methodBuilder; #else return _dynamicMethod; #endif } } internal ArgBuilder GetArg(int index) { return (ArgBuilder)_argList[index]; } internal Type GetVariableType(object var) { if (var is ArgBuilder) return ((ArgBuilder)var).ArgType; else if (var is LocalBuilder) return ((LocalBuilder)var).LocalType; else return var.GetType(); } internal LocalBuilder DeclareLocal(Type type, string name, object initialValue) { LocalBuilder local = DeclareLocal(type, name); Load(initialValue); Store(local); return local; } internal LocalBuilder DeclareLocal(Type type, string name) { return DeclareLocal(type, name, false); } internal LocalBuilder DeclareLocal(Type type, string name, bool isPinned) { LocalBuilder local = _ilGen.DeclareLocal(type, isPinned); if (_codeGenTrace != CodeGenTrace.None) { _localNames[local] = name; EmitSourceComment("Declare local '" + name + "' of type " + type); } return local; } internal void Set(LocalBuilder local, object value) { Load(value); Store(local); } internal object For(LocalBuilder local, object start, object end) { ForState forState = new ForState(local, DefineLabel(), DefineLabel(), end); if (forState.Index != null) { Load(start); Stloc(forState.Index); Br(forState.TestLabel); } MarkLabel(forState.BeginLabel); _blockStack.Push(forState); return forState; } internal void EndFor() { object stackTop = _blockStack.Pop(); ForState forState = stackTop as ForState; if (forState == null) ThrowMismatchException(stackTop); if (forState.Index != null) { Ldloc(forState.Index); Ldc(1); Add(); Stloc(forState.Index); MarkLabel(forState.TestLabel); Ldloc(forState.Index); Load(forState.End); if (GetVariableType(forState.End).IsArray) Ldlen(); Blt(forState.BeginLabel); } else Br(forState.BeginLabel); if (forState.RequiresEndLabel) MarkLabel(forState.EndLabel); } internal void Break(object forState) { InternalBreakFor(forState, OpCodes.Br); } internal void IfFalseBreak(object forState) { InternalBreakFor(forState, OpCodes.Brfalse); } internal void InternalBreakFor(object userForState, OpCode branchInstruction) { foreach (object block in _blockStack) { ForState forState = block as ForState; if (forState != null && (object)forState == userForState) { if (!forState.RequiresEndLabel) { forState.EndLabel = DefineLabel(); forState.RequiresEndLabel = true; } if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction(branchInstruction + " " + forState.EndLabel.GetHashCode()); _ilGen.Emit(branchInstruction, forState.EndLabel); break; } } } internal void ForEach(LocalBuilder local, Type elementType, Type enumeratorType, LocalBuilder enumerator, MethodInfo getCurrentMethod) { ForState forState = new ForState(local, DefineLabel(), DefineLabel(), enumerator); Br(forState.TestLabel); MarkLabel(forState.BeginLabel); Call(enumerator, getCurrentMethod); ConvertValue(elementType, GetVariableType(local)); Stloc(local); _blockStack.Push(forState); } internal void EndForEach(MethodInfo moveNextMethod) { object stackTop = _blockStack.Pop(); ForState forState = stackTop as ForState; if (forState == null) ThrowMismatchException(stackTop); MarkLabel(forState.TestLabel); object enumerator = forState.End; Call(enumerator, moveNextMethod); Brtrue(forState.BeginLabel); if (forState.RequiresEndLabel) MarkLabel(forState.EndLabel); } internal void IfNotDefaultValue(object value) { Type type = GetVariableType(value); TypeCode typeCode = type.GetTypeCode(); if ((typeCode == TypeCode.Object && type.IsValueType) || typeCode == TypeCode.DateTime || typeCode == TypeCode.Decimal) { LoadDefaultValue(type); ConvertValue(type, Globals.TypeOfObject); Load(value); ConvertValue(type, Globals.TypeOfObject); Call(ObjectEquals); IfNot(); } else { LoadDefaultValue(type); Load(value); If(Cmp.NotEqualTo); } } internal void If() { InternalIf(false); } internal void IfNot() { InternalIf(true); } private OpCode GetBranchCode(Cmp cmp) { switch (cmp) { case Cmp.LessThan: return OpCodes.Bge; case Cmp.EqualTo: return OpCodes.Bne_Un; case Cmp.LessThanOrEqualTo: return OpCodes.Bgt; case Cmp.GreaterThan: return OpCodes.Ble; case Cmp.NotEqualTo: return OpCodes.Beq; default: DiagnosticUtility.DebugAssert(cmp == Cmp.GreaterThanOrEqualTo, "Unexpected cmp"); return OpCodes.Blt; } } internal void If(Cmp cmpOp) { IfState ifState = new IfState(); ifState.EndIf = DefineLabel(); ifState.ElseBegin = DefineLabel(); _ilGen.Emit(GetBranchCode(cmpOp), ifState.ElseBegin); _blockStack.Push(ifState); } internal void If(object value1, Cmp cmpOp, object value2) { Load(value1); Load(value2); If(cmpOp); } internal void Else() { IfState ifState = PopIfState(); Br(ifState.EndIf); MarkLabel(ifState.ElseBegin); ifState.ElseBegin = ifState.EndIf; _blockStack.Push(ifState); } internal void ElseIf(object value1, Cmp cmpOp, object value2) { IfState ifState = (IfState)_blockStack.Pop(); Br(ifState.EndIf); MarkLabel(ifState.ElseBegin); Load(value1); Load(value2); ifState.ElseBegin = DefineLabel(); _ilGen.Emit(GetBranchCode(cmpOp), ifState.ElseBegin); _blockStack.Push(ifState); } internal void EndIf() { IfState ifState = PopIfState(); if (!ifState.ElseBegin.Equals(ifState.EndIf)) MarkLabel(ifState.ElseBegin); MarkLabel(ifState.EndIf); } internal void VerifyParameterCount(MethodInfo methodInfo, int expectedCount) { if (methodInfo.GetParameters().Length != expectedCount) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.ParameterCountMismatch, methodInfo.Name, methodInfo.GetParameters().Length, expectedCount))); } internal void Call(object thisObj, MethodInfo methodInfo) { VerifyParameterCount(methodInfo, 0); LoadThis(thisObj, methodInfo); Call(methodInfo); } internal void Call(object thisObj, MethodInfo methodInfo, object param1) { VerifyParameterCount(methodInfo, 1); LoadThis(thisObj, methodInfo); LoadParam(param1, 1, methodInfo); Call(methodInfo); } internal void Call(object thisObj, MethodInfo methodInfo, object param1, object param2) { VerifyParameterCount(methodInfo, 2); LoadThis(thisObj, methodInfo); LoadParam(param1, 1, methodInfo); LoadParam(param2, 2, methodInfo); Call(methodInfo); } internal void Call(object thisObj, MethodInfo methodInfo, object param1, object param2, object param3) { VerifyParameterCount(methodInfo, 3); LoadThis(thisObj, methodInfo); LoadParam(param1, 1, methodInfo); LoadParam(param2, 2, methodInfo); LoadParam(param3, 3, methodInfo); Call(methodInfo); } internal void Call(object thisObj, MethodInfo methodInfo, object param1, object param2, object param3, object param4) { VerifyParameterCount(methodInfo, 4); LoadThis(thisObj, methodInfo); LoadParam(param1, 1, methodInfo); LoadParam(param2, 2, methodInfo); LoadParam(param3, 3, methodInfo); LoadParam(param4, 4, methodInfo); Call(methodInfo); } internal void Call(object thisObj, MethodInfo methodInfo, object param1, object param2, object param3, object param4, object param5) { VerifyParameterCount(methodInfo, 5); LoadThis(thisObj, methodInfo); LoadParam(param1, 1, methodInfo); LoadParam(param2, 2, methodInfo); LoadParam(param3, 3, methodInfo); LoadParam(param4, 4, methodInfo); LoadParam(param5, 5, methodInfo); Call(methodInfo); } internal void Call(object thisObj, MethodInfo methodInfo, object param1, object param2, object param3, object param4, object param5, object param6) { VerifyParameterCount(methodInfo, 6); LoadThis(thisObj, methodInfo); LoadParam(param1, 1, methodInfo); LoadParam(param2, 2, methodInfo); LoadParam(param3, 3, methodInfo); LoadParam(param4, 4, methodInfo); LoadParam(param5, 5, methodInfo); LoadParam(param6, 6, methodInfo); Call(methodInfo); } internal void Call(MethodInfo methodInfo) { if (methodInfo.IsVirtual && !methodInfo.DeclaringType.IsValueType) { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Callvirt " + methodInfo.ToString() + " on type " + methodInfo.DeclaringType.ToString()); _ilGen.Emit(OpCodes.Callvirt, methodInfo); } else if (methodInfo.IsStatic) { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Static Call " + methodInfo.ToString() + " on type " + methodInfo.DeclaringType.ToString()); _ilGen.Emit(OpCodes.Call, methodInfo); } else { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Call " + methodInfo.ToString() + " on type " + methodInfo.DeclaringType.ToString()); _ilGen.Emit(OpCodes.Call, methodInfo); } } internal void Call(ConstructorInfo ctor) { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Call " + ctor.ToString() + " on type " + ctor.DeclaringType.ToString()); _ilGen.Emit(OpCodes.Call, ctor); } internal void New(ConstructorInfo constructorInfo) { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Newobj " + constructorInfo.ToString() + " on type " + constructorInfo.DeclaringType.ToString()); _ilGen.Emit(OpCodes.Newobj, constructorInfo); } internal void InitObj(Type valueType) { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Initobj " + valueType); _ilGen.Emit(OpCodes.Initobj, valueType); } internal void NewArray(Type elementType, object len) { Load(len); if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Newarr " + elementType); _ilGen.Emit(OpCodes.Newarr, elementType); } internal void LoadArrayElement(object obj, object arrayIndex) { Type objType = GetVariableType(obj).GetElementType(); Load(obj); Load(arrayIndex); if (IsStruct(objType)) { Ldelema(objType); Ldobj(objType); } else Ldelem(objType); } internal void StoreArrayElement(object obj, object arrayIndex, object value) { Type arrayType = GetVariableType(obj); if (arrayType == Globals.TypeOfArray) { Call(obj, ArraySetValue, value, arrayIndex); } else { Type objType = arrayType.GetElementType(); Load(obj); Load(arrayIndex); if (IsStruct(objType)) Ldelema(objType); Load(value); ConvertValue(GetVariableType(value), objType); if (IsStruct(objType)) Stobj(objType); else Stelem(objType); } } private static bool IsStruct(Type objType) { return objType.IsValueType && !objType.IsPrimitive; } internal Type LoadMember(MemberInfo memberInfo) { Type memberType = null; if (memberInfo is FieldInfo) { FieldInfo fieldInfo = (FieldInfo)memberInfo; memberType = fieldInfo.FieldType; if (fieldInfo.IsStatic) { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Ldsfld " + fieldInfo + " on type " + fieldInfo.DeclaringType); _ilGen.Emit(OpCodes.Ldsfld, fieldInfo); } else { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Ldfld " + fieldInfo + " on type " + fieldInfo.DeclaringType); _ilGen.Emit(OpCodes.Ldfld, fieldInfo); } } else if (memberInfo is PropertyInfo) { PropertyInfo property = memberInfo as PropertyInfo; memberType = property.PropertyType; if (property != null) { MethodInfo getMethod = property.GetMethod; if (getMethod == null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.NoGetMethodForProperty, property.DeclaringType, property))); Call(getMethod); } } else if (memberInfo is MethodInfo) { MethodInfo method = (MethodInfo)memberInfo; memberType = method.ReturnType; Call(method); } else throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.CannotLoadMemberType, "Unknown", memberInfo.DeclaringType, memberInfo.Name))); EmitStackTop(memberType); return memberType; } internal void StoreMember(MemberInfo memberInfo) { if (memberInfo is FieldInfo) { FieldInfo fieldInfo = (FieldInfo)memberInfo; if (fieldInfo.IsStatic) { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Stsfld " + fieldInfo + " on type " + fieldInfo.DeclaringType); _ilGen.Emit(OpCodes.Stsfld, fieldInfo); } else { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Stfld " + fieldInfo + " on type " + fieldInfo.DeclaringType); _ilGen.Emit(OpCodes.Stfld, fieldInfo); } } else if (memberInfo is PropertyInfo) { PropertyInfo property = memberInfo as PropertyInfo; if (property != null) { MethodInfo setMethod = property.SetMethod; if (setMethod == null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.NoSetMethodForProperty, property.DeclaringType, property))); Call(setMethod); } } else if (memberInfo is MethodInfo) Call((MethodInfo)memberInfo); else throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.CannotLoadMemberType, "Unknown"))); } internal void LoadDefaultValue(Type type) { if (type.IsValueType) { switch (type.GetTypeCode()) { case TypeCode.Boolean: Ldc(false); break; case TypeCode.Char: case TypeCode.SByte: case TypeCode.Byte: case TypeCode.Int16: case TypeCode.UInt16: case TypeCode.Int32: case TypeCode.UInt32: Ldc(0); break; case TypeCode.Int64: case TypeCode.UInt64: Ldc(0L); break; case TypeCode.Single: Ldc(0.0F); break; case TypeCode.Double: Ldc(0.0); break; case TypeCode.Decimal: case TypeCode.DateTime: default: LocalBuilder zero = DeclareLocal(type, "zero"); LoadAddress(zero); InitObj(type); Load(zero); break; } } else Load(null); } internal void Load(object obj) { if (obj == null) { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Ldnull"); _ilGen.Emit(OpCodes.Ldnull); } else if (obj is ArgBuilder) Ldarg((ArgBuilder)obj); else if (obj is LocalBuilder) Ldloc((LocalBuilder)obj); else Ldc(obj); } internal void Store(object var) { if (var is ArgBuilder) Starg((ArgBuilder)var); else if (var is LocalBuilder) Stloc((LocalBuilder)var); else { DiagnosticUtility.DebugAssert("Data can only be stored into ArgBuilder or LocalBuilder."); throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.CanOnlyStoreIntoArgOrLocGot0, DataContract.GetClrTypeFullName(var.GetType())))); } } internal void Dec(object var) { Load(var); Load(1); Subtract(); Store(var); } internal void LoadAddress(object obj) { if (obj is ArgBuilder) LdargAddress((ArgBuilder)obj); else if (obj is LocalBuilder) LdlocAddress((LocalBuilder)obj); else Load(obj); } internal void ConvertAddress(Type source, Type target) { InternalConvert(source, target, true); } internal void ConvertValue(Type source, Type target) { InternalConvert(source, target, false); } internal void Castclass(Type target) { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Castclass " + target); _ilGen.Emit(OpCodes.Castclass, target); } internal void Box(Type type) { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Box " + type); _ilGen.Emit(OpCodes.Box, type); } internal void Unbox(Type type) { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Unbox " + type); _ilGen.Emit(OpCodes.Unbox, type); } private OpCode GetLdindOpCode(TypeCode typeCode) { switch (typeCode) { case TypeCode.Boolean: return OpCodes.Ldind_I1; // TypeCode.Boolean: case TypeCode.Char: return OpCodes.Ldind_I2; // TypeCode.Char: case TypeCode.SByte: return OpCodes.Ldind_I1; // TypeCode.SByte: case TypeCode.Byte: return OpCodes.Ldind_U1; // TypeCode.Byte: case TypeCode.Int16: return OpCodes.Ldind_I2; // TypeCode.Int16: case TypeCode.UInt16: return OpCodes.Ldind_U2; // TypeCode.UInt16: case TypeCode.Int32: return OpCodes.Ldind_I4; // TypeCode.Int32: case TypeCode.UInt32: return OpCodes.Ldind_U4; // TypeCode.UInt32: case TypeCode.Int64: return OpCodes.Ldind_I8; // TypeCode.Int64: case TypeCode.UInt64: return OpCodes.Ldind_I8; // TypeCode.UInt64: case TypeCode.Single: return OpCodes.Ldind_R4; // TypeCode.Single: case TypeCode.Double: return OpCodes.Ldind_R8; // TypeCode.Double: case TypeCode.String: return OpCodes.Ldind_Ref; // TypeCode.String: default: return OpCodes.Nop; } } internal void Ldobj(Type type) { OpCode opCode = GetLdindOpCode(type.GetTypeCode()); if (!opCode.Equals(OpCodes.Nop)) { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction(opCode.ToString()); _ilGen.Emit(opCode); } else { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Ldobj " + type); _ilGen.Emit(OpCodes.Ldobj, type); } } internal void Stobj(Type type) { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Stobj " + type); _ilGen.Emit(OpCodes.Stobj, type); } internal void Ceq() { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Ceq"); _ilGen.Emit(OpCodes.Ceq); } internal void Throw() { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Throw"); _ilGen.Emit(OpCodes.Throw); } internal void Ldtoken(Type t) { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Ldtoken " + t); _ilGen.Emit(OpCodes.Ldtoken, t); } internal void Ldc(object o) { Type valueType = o.GetType(); if (o is Type) { Ldtoken((Type)o); Call(GetTypeFromHandle); } else if (valueType.IsEnum) { if (_codeGenTrace != CodeGenTrace.None) EmitSourceComment("Ldc " + o.GetType() + "." + o); Ldc(Convert.ChangeType(o, Enum.GetUnderlyingType(valueType), null)); } else { switch (valueType.GetTypeCode()) { case TypeCode.Boolean: Ldc((bool)o); break; case TypeCode.Char: DiagnosticUtility.DebugAssert("Char is not a valid schema primitive and should be treated as int in DataContract"); throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.Format(SR.CharIsInvalidPrimitive))); case TypeCode.SByte: case TypeCode.Byte: case TypeCode.Int16: case TypeCode.UInt16: Ldc(Convert.ToInt32(o, CultureInfo.InvariantCulture)); break; case TypeCode.Int32: Ldc((int)o); break; case TypeCode.UInt32: Ldc((int)(uint)o); break; case TypeCode.UInt64: Ldc((long)(ulong)o); break; case TypeCode.Int64: Ldc((long)o); break; case TypeCode.Single: Ldc((float)o); break; case TypeCode.Double: Ldc((double)o); break; case TypeCode.String: Ldstr((string)o); break; case TypeCode.Object: case TypeCode.Decimal: case TypeCode.DateTime: case TypeCode.Empty: default: throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.UnknownConstantType, DataContract.GetClrTypeFullName(valueType)))); } } } internal void Ldc(bool boolVar) { if (boolVar) { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Ldc.i4 1"); _ilGen.Emit(OpCodes.Ldc_I4_1); } else { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Ldc.i4 0"); _ilGen.Emit(OpCodes.Ldc_I4_0); } } internal void Ldc(int intVar) { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Ldc.i4 " + intVar); switch (intVar) { case -1: _ilGen.Emit(OpCodes.Ldc_I4_M1); break; case 0: _ilGen.Emit(OpCodes.Ldc_I4_0); break; case 1: _ilGen.Emit(OpCodes.Ldc_I4_1); break; case 2: _ilGen.Emit(OpCodes.Ldc_I4_2); break; case 3: _ilGen.Emit(OpCodes.Ldc_I4_3); break; case 4: _ilGen.Emit(OpCodes.Ldc_I4_4); break; case 5: _ilGen.Emit(OpCodes.Ldc_I4_5); break; case 6: _ilGen.Emit(OpCodes.Ldc_I4_6); break; case 7: _ilGen.Emit(OpCodes.Ldc_I4_7); break; case 8: _ilGen.Emit(OpCodes.Ldc_I4_8); break; default: _ilGen.Emit(OpCodes.Ldc_I4, intVar); break; } } internal void Ldc(long l) { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Ldc.i8 " + l); _ilGen.Emit(OpCodes.Ldc_I8, l); } internal void Ldc(float f) { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Ldc.r4 " + f); _ilGen.Emit(OpCodes.Ldc_R4, f); } internal void Ldc(double d) { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Ldc.r8 " + d); _ilGen.Emit(OpCodes.Ldc_R8, d); } internal void Ldstr(string strVar) { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Ldstr " + strVar); _ilGen.Emit(OpCodes.Ldstr, strVar); } internal void LdlocAddress(LocalBuilder localBuilder) { if (localBuilder.LocalType.IsValueType) Ldloca(localBuilder); else Ldloc(localBuilder); } internal void Ldloc(LocalBuilder localBuilder) { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Ldloc " + _localNames[localBuilder]); _ilGen.Emit(OpCodes.Ldloc, localBuilder); EmitStackTop(localBuilder.LocalType); } internal void Stloc(LocalBuilder local) { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Stloc " + _localNames[local]); EmitStackTop(local.LocalType); _ilGen.Emit(OpCodes.Stloc, local); } internal void Ldloca(LocalBuilder localBuilder) { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Ldloca " + _localNames[localBuilder]); _ilGen.Emit(OpCodes.Ldloca, localBuilder); EmitStackTop(localBuilder.LocalType); } internal void LdargAddress(ArgBuilder argBuilder) { if (argBuilder.ArgType.IsValueType) Ldarga(argBuilder); else Ldarg(argBuilder); } internal void Ldarg(ArgBuilder arg) { Ldarg(arg.Index); } internal void Starg(ArgBuilder arg) { Starg(arg.Index); } internal void Ldarg(int slot) { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Ldarg " + slot); switch (slot) { case 0: _ilGen.Emit(OpCodes.Ldarg_0); break; case 1: _ilGen.Emit(OpCodes.Ldarg_1); break; case 2: _ilGen.Emit(OpCodes.Ldarg_2); break; case 3: _ilGen.Emit(OpCodes.Ldarg_3); break; default: if (slot <= 255) _ilGen.Emit(OpCodes.Ldarg_S, slot); else _ilGen.Emit(OpCodes.Ldarg, slot); break; } } internal void Starg(int slot) { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Starg " + slot); if (slot <= 255) _ilGen.Emit(OpCodes.Starg_S, slot); else _ilGen.Emit(OpCodes.Starg, slot); } internal void Ldarga(ArgBuilder argBuilder) { Ldarga(argBuilder.Index); } internal void Ldarga(int slot) { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Ldarga " + slot); if (slot <= 255) _ilGen.Emit(OpCodes.Ldarga_S, slot); else _ilGen.Emit(OpCodes.Ldarga, slot); } internal void Ldlen() { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Ldlen"); _ilGen.Emit(OpCodes.Ldlen); if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Conv.i4"); _ilGen.Emit(OpCodes.Conv_I4); } private OpCode GetLdelemOpCode(TypeCode typeCode) { switch (typeCode) { case TypeCode.Object: return OpCodes.Ldelem_Ref;// TypeCode.Object: case TypeCode.Boolean: return OpCodes.Ldelem_I1;// TypeCode.Boolean: case TypeCode.Char: return OpCodes.Ldelem_I2;// TypeCode.Char: case TypeCode.SByte: return OpCodes.Ldelem_I1;// TypeCode.SByte: case TypeCode.Byte: return OpCodes.Ldelem_U1;// TypeCode.Byte: case TypeCode.Int16: return OpCodes.Ldelem_I2;// TypeCode.Int16: case TypeCode.UInt16: return OpCodes.Ldelem_U2;// TypeCode.UInt16: case TypeCode.Int32: return OpCodes.Ldelem_I4;// TypeCode.Int32: case TypeCode.UInt32: return OpCodes.Ldelem_U4;// TypeCode.UInt32: case TypeCode.Int64: return OpCodes.Ldelem_I8;// TypeCode.Int64: case TypeCode.UInt64: return OpCodes.Ldelem_I8;// TypeCode.UInt64: case TypeCode.Single: return OpCodes.Ldelem_R4;// TypeCode.Single: case TypeCode.Double: return OpCodes.Ldelem_R8;// TypeCode.Double: case TypeCode.String: return OpCodes.Ldelem_Ref;// TypeCode.String: default: return OpCodes.Nop; } } internal void Ldelem(Type arrayElementType) { if (arrayElementType.IsEnum) { Ldelem(Enum.GetUnderlyingType(arrayElementType)); } else { OpCode opCode = GetLdelemOpCode(arrayElementType.GetTypeCode()); if (opCode.Equals(OpCodes.Nop)) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.ArrayTypeIsNotSupported, DataContract.GetClrTypeFullName(arrayElementType)))); if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction(opCode.ToString()); _ilGen.Emit(opCode); EmitStackTop(arrayElementType); } } internal void Ldelema(Type arrayElementType) { OpCode opCode = OpCodes.Ldelema; if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction(opCode.ToString()); _ilGen.Emit(opCode, arrayElementType); EmitStackTop(arrayElementType); } private OpCode GetStelemOpCode(TypeCode typeCode) { switch (typeCode) { case TypeCode.Object: return OpCodes.Stelem_Ref;// TypeCode.Object: case TypeCode.Boolean: return OpCodes.Stelem_I1;// TypeCode.Boolean: case TypeCode.Char: return OpCodes.Stelem_I2;// TypeCode.Char: case TypeCode.SByte: return OpCodes.Stelem_I1;// TypeCode.SByte: case TypeCode.Byte: return OpCodes.Stelem_I1;// TypeCode.Byte: case TypeCode.Int16: return OpCodes.Stelem_I2;// TypeCode.Int16: case TypeCode.UInt16: return OpCodes.Stelem_I2;// TypeCode.UInt16: case TypeCode.Int32: return OpCodes.Stelem_I4;// TypeCode.Int32: case TypeCode.UInt32: return OpCodes.Stelem_I4;// TypeCode.UInt32: case TypeCode.Int64: return OpCodes.Stelem_I8;// TypeCode.Int64: case TypeCode.UInt64: return OpCodes.Stelem_I8;// TypeCode.UInt64: case TypeCode.Single: return OpCodes.Stelem_R4;// TypeCode.Single: case TypeCode.Double: return OpCodes.Stelem_R8;// TypeCode.Double: case TypeCode.String: return OpCodes.Stelem_Ref;// TypeCode.String: default: return OpCodes.Nop; } } internal void Stelem(Type arrayElementType) { if (arrayElementType.IsEnum) Stelem(Enum.GetUnderlyingType(arrayElementType)); else { OpCode opCode = GetStelemOpCode(arrayElementType.GetTypeCode()); if (opCode.Equals(OpCodes.Nop)) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.ArrayTypeIsNotSupported, DataContract.GetClrTypeFullName(arrayElementType)))); if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction(opCode.ToString()); EmitStackTop(arrayElementType); _ilGen.Emit(opCode); } } internal Label DefineLabel() { return _ilGen.DefineLabel(); } internal void MarkLabel(Label label) { _ilGen.MarkLabel(label); if (_codeGenTrace != CodeGenTrace.None) EmitSourceLabel(label.GetHashCode() + ":"); } internal void Add() { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Add"); _ilGen.Emit(OpCodes.Add); } internal void Subtract() { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Sub"); _ilGen.Emit(OpCodes.Sub); } internal void And() { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("And"); _ilGen.Emit(OpCodes.And); } internal void Or() { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Or"); _ilGen.Emit(OpCodes.Or); } internal void Not() { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Not"); _ilGen.Emit(OpCodes.Not); } internal void Ret() { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Ret"); _ilGen.Emit(OpCodes.Ret); } internal void Br(Label label) { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Br " + label.GetHashCode()); _ilGen.Emit(OpCodes.Br, label); } internal void Blt(Label label) { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Blt " + label.GetHashCode()); _ilGen.Emit(OpCodes.Blt, label); } internal void Brfalse(Label label) { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Brfalse " + label.GetHashCode()); _ilGen.Emit(OpCodes.Brfalse, label); } internal void Brtrue(Label label) { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Brtrue " + label.GetHashCode()); _ilGen.Emit(OpCodes.Brtrue, label); } internal void Pop() { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Pop"); _ilGen.Emit(OpCodes.Pop); } internal void Dup() { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Dup"); _ilGen.Emit(OpCodes.Dup); } private void LoadThis(object thisObj, MethodInfo methodInfo) { if (thisObj != null && !methodInfo.IsStatic) { LoadAddress(thisObj); ConvertAddress(GetVariableType(thisObj), methodInfo.DeclaringType); } } private void LoadParam(object arg, int oneBasedArgIndex, MethodBase methodInfo) { Load(arg); if (arg != null) ConvertValue(GetVariableType(arg), methodInfo.GetParameters()[oneBasedArgIndex - 1].ParameterType); } private void InternalIf(bool negate) { IfState ifState = new IfState(); ifState.EndIf = DefineLabel(); ifState.ElseBegin = DefineLabel(); if (negate) Brtrue(ifState.ElseBegin); else Brfalse(ifState.ElseBegin); _blockStack.Push(ifState); } private OpCode GetConvOpCode(TypeCode typeCode) { switch (typeCode) { case TypeCode.Boolean: return OpCodes.Conv_I1;// TypeCode.Boolean: case TypeCode.Char: return OpCodes.Conv_I2;// TypeCode.Char: case TypeCode.SByte: return OpCodes.Conv_I1;// TypeCode.SByte: case TypeCode.Byte: return OpCodes.Conv_U1;// TypeCode.Byte: case TypeCode.Int16: return OpCodes.Conv_I2;// TypeCode.Int16: case TypeCode.UInt16: return OpCodes.Conv_U2;// TypeCode.UInt16: case TypeCode.Int32: return OpCodes.Conv_I4;// TypeCode.Int32: case TypeCode.UInt32: return OpCodes.Conv_U4;// TypeCode.UInt32: case TypeCode.Int64: return OpCodes.Conv_I8;// TypeCode.Int64: case TypeCode.UInt64: return OpCodes.Conv_I8;// TypeCode.UInt64: case TypeCode.Single: return OpCodes.Conv_R4;// TypeCode.Single: case TypeCode.Double: return OpCodes.Conv_R8;// TypeCode.Double: default: return OpCodes.Nop; } } private void InternalConvert(Type source, Type target, bool isAddress) { if (target == source) return; if (target.IsValueType) { if (source.IsValueType) { OpCode opCode = GetConvOpCode(target.GetTypeCode()); if (opCode.Equals(OpCodes.Nop)) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.NoConversionPossibleTo, DataContract.GetClrTypeFullName(target)))); else { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction(opCode.ToString()); _ilGen.Emit(opCode); } } else if (source.IsAssignableFrom(target)) { Unbox(target); if (!isAddress) Ldobj(target); } else throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.IsNotAssignableFrom, DataContract.GetClrTypeFullName(target), DataContract.GetClrTypeFullName(source)))); } else if (target.IsAssignableFrom(source)) { if (source.IsValueType) { if (isAddress) Ldobj(source); Box(source); } } else if (source.IsAssignableFrom(target)) { Castclass(target); } else if (target.IsInterface || source.IsInterface) { Castclass(target); } else throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.IsNotAssignableFrom, DataContract.GetClrTypeFullName(target), DataContract.GetClrTypeFullName(source)))); } private IfState PopIfState() { object stackTop = _blockStack.Pop(); IfState ifState = stackTop as IfState; if (ifState == null) ThrowMismatchException(stackTop); return ifState; } #if USE_REFEMIT void InitAssemblyBuilder(string methodName) { AssemblyName name = new AssemblyName(); name.Name = "Microsoft.GeneratedCode."+methodName; //Add SecurityCritical and SecurityTreatAsSafe attributes to the generated method assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(name, AssemblyBuilderAccess.Run); moduleBuilder = assemblyBuilder.DefineDynamicModule(name.Name + ".dll", false); } #endif private void ThrowMismatchException(object expected) { throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.ExpectingEnd, expected.ToString()))); } [Conditional("NOT_SILVERLIGHT")] internal void EmitSourceInstruction(string line) { } [Conditional("NOT_SILVERLIGHT")] internal void EmitSourceLabel(string line) { } [Conditional("NOT_SILVERLIGHT")] internal void EmitSourceComment(string comment) { } internal void EmitStackTop(Type stackTopType) { if (_codeGenTrace != CodeGenTrace.Tron) return; } internal Label[] Switch(int labelCount) { SwitchState switchState = new SwitchState(DefineLabel(), DefineLabel()); Label[] caseLabels = new Label[labelCount]; for (int i = 0; i < caseLabels.Length; i++) caseLabels[i] = DefineLabel(); _ilGen.Emit(OpCodes.Switch, caseLabels); Br(switchState.DefaultLabel); _blockStack.Push(switchState); return caseLabels; } internal void Case(Label caseLabel1, string caseLabelName) { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("case " + caseLabelName + "{"); MarkLabel(caseLabel1); } internal void EndCase() { object stackTop = _blockStack.Peek(); SwitchState switchState = stackTop as SwitchState; if (switchState == null) ThrowMismatchException(stackTop); Br(switchState.EndOfSwitchLabel); if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("} //end case "); } internal void EndSwitch() { object stackTop = _blockStack.Pop(); SwitchState switchState = stackTop as SwitchState; if (switchState == null) ThrowMismatchException(stackTop); if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("} //end switch"); if (!switchState.DefaultDefined) MarkLabel(switchState.DefaultLabel); MarkLabel(switchState.EndOfSwitchLabel); } private static MethodInfo s_stringLength = typeof(string).GetProperty("Length").GetMethod; internal void ElseIfIsEmptyString(LocalBuilder strLocal) { IfState ifState = (IfState)_blockStack.Pop(); Br(ifState.EndIf); MarkLabel(ifState.ElseBegin); Load(strLocal); Call(s_stringLength); Load(0); ifState.ElseBegin = DefineLabel(); _ilGen.Emit(GetBranchCode(Cmp.EqualTo), ifState.ElseBegin); _blockStack.Push(ifState); } internal void IfNotIsEmptyString(LocalBuilder strLocal) { Load(strLocal); Call(s_stringLength); Load(0); If(Cmp.NotEqualTo); } #if !uapaot internal void BeginWhileCondition() { Label startWhile = DefineLabel(); MarkLabel(startWhile); _blockStack.Push(startWhile); } internal void BeginWhileBody(Cmp cmpOp) { Label startWhile = (Label)_blockStack.Pop(); If(cmpOp); _blockStack.Push(startWhile); } internal void EndWhile() { Label startWhile = (Label)_blockStack.Pop(); Br(startWhile); EndIf(); } internal void CallStringFormat(string msg, params object[] values) { NewArray(typeof(object), values.Length); if (_stringFormatArray == null) _stringFormatArray = DeclareLocal(typeof(object[]), "stringFormatArray"); Stloc(_stringFormatArray); for (int i = 0; i < values.Length; i++) StoreArrayElement(_stringFormatArray, i, values[i]); Load(msg); Load(_stringFormatArray); Call(StringFormat); } internal void ToString(Type type) { if (type != Globals.TypeOfString) { if (type.IsValueType) { Box(type); } Call(ObjectToString); } } #endif } internal class ArgBuilder { internal int Index; internal Type ArgType; internal ArgBuilder(int index, Type argType) { this.Index = index; this.ArgType = argType; } } internal class ForState { private LocalBuilder _indexVar; private Label _beginLabel; private Label _testLabel; private Label _endLabel; private bool _requiresEndLabel; private object _end; internal ForState(LocalBuilder indexVar, Label beginLabel, Label testLabel, object end) { _indexVar = indexVar; _beginLabel = beginLabel; _testLabel = testLabel; _end = end; } internal LocalBuilder Index { get { return _indexVar; } } internal Label BeginLabel { get { return _beginLabel; } } internal Label TestLabel { get { return _testLabel; } } internal Label EndLabel { get { return _endLabel; } set { _endLabel = value; } } internal bool RequiresEndLabel { get { return _requiresEndLabel; } set { _requiresEndLabel = value; } } internal object End { get { return _end; } } } internal enum Cmp { LessThan, EqualTo, LessThanOrEqualTo, GreaterThan, NotEqualTo, GreaterThanOrEqualTo } internal class IfState { private Label _elseBegin; private Label _endIf; internal Label EndIf { get { return _endIf; } set { _endIf = value; } } internal Label ElseBegin { get { return _elseBegin; } set { _elseBegin = value; } } } internal class SwitchState { private Label _defaultLabel; private Label _endOfSwitchLabel; private bool _defaultDefined; internal SwitchState(Label defaultLabel, Label endOfSwitchLabel) { _defaultLabel = defaultLabel; _endOfSwitchLabel = endOfSwitchLabel; _defaultDefined = false; } internal Label DefaultLabel { get { return _defaultLabel; } } internal Label EndOfSwitchLabel { get { return _endOfSwitchLabel; } } internal bool DefaultDefined { get { return _defaultDefined; } set { _defaultDefined = value; } } } } #endif
/* **************************************************************************** * * Copyright (c) Microsoft Corporation. * * This source code is subject to terms and conditions of the Apache License, Version 2.0. A * copy of the license can be found in the License.html file at the root of this distribution. If * you cannot locate the Apache License, Version 2.0, please send an email to * ironpy@microsoft.com. By using this source code in any fashion, you are agreeing to be bound * by the terms of the Apache License, Version 2.0. * * You must not remove this notice, or any other, from this software. * * ***************************************************************************/ using System; using System.Diagnostics; using System.Globalization; using System.IO; using System.Runtime.InteropServices; using System.Security.Permissions; using System.Text; using Microsoft.VisualStudio; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using OleConstants = Microsoft.VisualStudio.OLE.Interop.Constants; using VsCommands2K = Microsoft.VisualStudio.VSConstants.VSStd2KCmdID; namespace Microsoft.VisualStudio.Project { [CLSCompliant(false), ComVisible(true)] public abstract class ReferenceNode : HierarchyNode { protected delegate void CannotAddReferenceErrorMessage(); #region ctors /// <summary> /// constructor for the ReferenceNode /// </summary> protected ReferenceNode(ProjectNode root, ProjectElement element) : base(root, element) { this.ExcludeNodeFromScc = true; } /// <summary> /// constructor for the ReferenceNode /// </summary> protected ReferenceNode(ProjectNode root) : base(root) { this.ExcludeNodeFromScc = true; } #endregion #region overridden properties public override int MenuCommandId { get { return VsMenus.IDM_VS_CTXT_REFERENCE; } } public override Guid ItemTypeGuid { get { return Guid.Empty; } } public override string Url { get { return String.Empty; } } public override string Caption { get { return String.Empty; } } #endregion #region overridden methods protected override NodeProperties CreatePropertiesObject() { return new ReferenceNodeProperties(this); } /// <summary> /// Get an instance of the automation object for ReferenceNode /// </summary> /// <returns>An instance of Automation.OAReferenceItem type if succeeded</returns> public override object GetAutomationObject() { if(this.ProjectMgr == null || this.ProjectMgr.IsClosed) { return null; } return new Automation.OAReferenceItem(this.ProjectMgr.GetAutomationObject() as Automation.OAProject, this); } /// <summary> /// Disable inline editing of Caption of a ReferendeNode /// </summary> /// <returns>null</returns> public override string GetEditLabel() { return null; } public override object GetIconHandle(bool open) { int offset = (this.CanShowDefaultIcon() ? (int)ProjectNode.ImageName.Reference : (int)ProjectNode.ImageName.DanglingReference); return this.ProjectMgr.ImageHandler.GetIconHandle(offset); } /// <summary> /// This method is called by the interface method GetMkDocument to specify the item moniker. /// </summary> /// <returns>The moniker for this item</returns> public override string GetMkDocument() { return this.Url; } /// <summary> /// Not supported. /// </summary> protected override int ExcludeFromProject() { return (int)OleConstants.OLECMDERR_E_NOTSUPPORTED; } /// <summary> /// References node cannot be dragged. /// </summary> /// <returns>A stringbuilder.</returns> protected internal override StringBuilder PrepareSelectedNodesForClipBoard() { return null; } protected override int QueryStatusOnNode(Guid cmdGroup, uint cmd, IntPtr pCmdText, ref QueryStatusResult result) { if(cmdGroup == VsMenus.guidStandardCommandSet2K) { if((VsCommands2K)cmd == VsCommands2K.QUICKOBJECTSEARCH) { result |= QueryStatusResult.SUPPORTED | QueryStatusResult.ENABLED; return VSConstants.S_OK; } } else { return (int)OleConstants.OLECMDERR_E_UNKNOWNGROUP; } return base.QueryStatusOnNode(cmdGroup, cmd, pCmdText, ref result); } protected override int ExecCommandOnNode(Guid cmdGroup, uint cmd, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut) { if(cmdGroup == VsMenus.guidStandardCommandSet2K) { if((VsCommands2K)cmd == VsCommands2K.QUICKOBJECTSEARCH) { return this.ShowObjectBrowser(); } } return base.ExecCommandOnNode(cmdGroup, cmd, nCmdexecopt, pvaIn, pvaOut); } #endregion #region methods /// <summary> /// Links a reference node to the project and hierarchy. /// </summary> public virtual void AddReference() { ReferenceContainerNode referencesFolder = this.ProjectMgr.FindChild(ReferenceContainerNode.ReferencesNodeVirtualName) as ReferenceContainerNode; Debug.Assert(referencesFolder != null, "Could not find the References node"); CannotAddReferenceErrorMessage referenceErrorMessageHandler = null; if(!this.CanAddReference(out referenceErrorMessageHandler)) { if(referenceErrorMessageHandler != null) { referenceErrorMessageHandler.DynamicInvoke(new object[] { }); } return; } // Link the node to the project file. this.BindReferenceData(); // At this point force the item to be refreshed this.ItemNode.RefreshProperties(); referencesFolder.AddChild(this); return; } /// <summary> /// Refreshes a reference by re-resolving it and redrawing the icon. /// </summary> internal virtual void RefreshReference() { this.ResolveReference(); this.ReDraw(UIHierarchyElement.Icon); } /// <summary> /// Resolves references. /// </summary> protected virtual void ResolveReference() { } /// <summary> /// Validates that a reference can be added. /// </summary> /// <param name="errorHandler">A CannotAddReferenceErrorMessage delegate to show the error message.</param> /// <returns>true if the reference can be added.</returns> protected virtual bool CanAddReference(out CannotAddReferenceErrorMessage errorHandler) { // When this method is called this refererence has not yet been added to the hierarchy, only instantiated. errorHandler = null; if(this.IsAlreadyAdded()) { return false; } return true; } /// <summary> /// Checks if a reference is already added. The method parses all references and compares the Url. /// </summary> /// <returns>true if the assembly has already been added.</returns> protected virtual bool IsAlreadyAdded() { ReferenceContainerNode referencesFolder = this.ProjectMgr.FindChild(ReferenceContainerNode.ReferencesNodeVirtualName) as ReferenceContainerNode; Debug.Assert(referencesFolder != null, "Could not find the References node"); for(HierarchyNode n = referencesFolder.FirstChild; n != null; n = n.NextSibling) { ReferenceNode refererenceNode = n as ReferenceNode; if(null != refererenceNode) { // We check if the Url of the assemblies is the same. if(NativeMethods.IsSamePath(refererenceNode.Url, this.Url)) { return true; } } } return false; } /// <summary> /// Shows the Object Browser /// </summary> /// <returns></returns> protected virtual int ShowObjectBrowser() { if(String.IsNullOrEmpty(this.Url) || !File.Exists(this.Url)) { return (int)OleConstants.OLECMDERR_E_NOTSUPPORTED; } // Request unmanaged code permission in order to be able to creaet the unmanaged memory representing the guid. new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Demand(); Guid guid = VSConstants.guidCOMPLUSLibrary; IntPtr ptr = System.Runtime.InteropServices.Marshal.AllocCoTaskMem(guid.ToByteArray().Length); System.Runtime.InteropServices.Marshal.StructureToPtr(guid, ptr, false); int returnValue = VSConstants.S_OK; try { VSOBJECTINFO[] objInfo = new VSOBJECTINFO[1]; objInfo[0].pguidLib = ptr; objInfo[0].pszLibName = this.Url; IVsObjBrowser objBrowser = this.ProjectMgr.Site.GetService(typeof(SVsObjBrowser)) as IVsObjBrowser; ErrorHandler.ThrowOnFailure(objBrowser.NavigateTo(objInfo, 0)); } catch(COMException e) { Trace.WriteLine("Exception" + e.ErrorCode); returnValue = e.ErrorCode; } finally { if(ptr != IntPtr.Zero) { System.Runtime.InteropServices.Marshal.FreeCoTaskMem(ptr); } } return returnValue; } protected override bool CanDeleteItem(__VSDELETEITEMOPERATION deleteOperation) { if(deleteOperation == __VSDELETEITEMOPERATION.DELITEMOP_RemoveFromProject) { return true; } return false; } protected abstract void BindReferenceData(); #endregion } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; namespace System.Linq.Expressions { /// <summary> /// Strongly-typed and parameterized exception factory. /// </summary> internal static partial class Error { /// <summary> /// ArgumentException with message like "reducible nodes must override Expression.Reduce()" /// </summary> internal static Exception ReducibleMustOverrideReduce() { return new ArgumentException(Strings.ReducibleMustOverrideReduce); } /// <summary> /// ArgumentException with message like "node cannot reduce to itself or null" /// </summary> internal static Exception MustReduceToDifferent() { return new ArgumentException(Strings.MustReduceToDifferent); } /// <summary> /// ArgumentException with message like "cannot assign from the reduced node type to the original node type" /// </summary> internal static Exception ReducedNotCompatible() { return new ArgumentException(Strings.ReducedNotCompatible); } /// <summary> /// ArgumentException with message like "Setter must have parameters." /// </summary> internal static Exception SetterHasNoParams() { return new ArgumentException(Strings.SetterHasNoParams); } /// <summary> /// ArgumentException with message like "Property cannot have a managed pointer type." /// </summary> internal static Exception PropertyCannotHaveRefType() { return new ArgumentException(Strings.PropertyCannotHaveRefType); } /// <summary> /// ArgumentException with message like "Indexing parameters of getter and setter must match." /// </summary> internal static Exception IndexesOfSetGetMustMatch() { return new ArgumentException(Strings.IndexesOfSetGetMustMatch); } /// <summary> /// ArgumentException with message like "Accessor method should not have VarArgs." /// </summary> internal static Exception AccessorsCannotHaveVarArgs() { return new ArgumentException(Strings.AccessorsCannotHaveVarArgs); } /// <summary> /// ArgumentException with message like "Accessor indexes cannot be passed ByRef." /// </summary> internal static Exception AccessorsCannotHaveByRefArgs() { return new ArgumentException(Strings.AccessorsCannotHaveByRefArgs); } /// <summary> /// ArgumentException with message like "Bounds count cannot be less than 1" /// </summary> internal static Exception BoundsCannotBeLessThanOne() { return new ArgumentException(Strings.BoundsCannotBeLessThanOne); } /// <summary> /// ArgumentException with message like "type must not be ByRef" /// </summary> internal static Exception TypeMustNotBeByRef() { return new ArgumentException(Strings.TypeMustNotBeByRef); } /// <summary> /// ArgumentException with message like "Type doesn't have constructor with a given signature" /// </summary> internal static Exception TypeDoesNotHaveConstructorForTheSignature() { return new ArgumentException(Strings.TypeDoesNotHaveConstructorForTheSignature); } /// <summary> /// ArgumentException with message like "Count must be non-negative." /// </summary> internal static Exception CountCannotBeNegative() { return new ArgumentException(Strings.CountCannotBeNegative); } /// <summary> /// ArgumentException with message like "arrayType must be an array type" /// </summary> internal static Exception ArrayTypeMustBeArray() { return new ArgumentException(Strings.ArrayTypeMustBeArray); } /// <summary> /// ArgumentException with message like "Setter should have void type." /// </summary> internal static Exception SetterMustBeVoid() { return new ArgumentException(Strings.SetterMustBeVoid); } /// <summary> /// ArgumentException with message like "Property type must match the value type of setter" /// </summary> internal static Exception PropertyTyepMustMatchSetter() { return new ArgumentException(Strings.PropertyTyepMustMatchSetter); } /// <summary> /// ArgumentException with message like "Both accessors must be static." /// </summary> internal static Exception BothAccessorsMustBeStatic() { return new ArgumentException(Strings.BothAccessorsMustBeStatic); } /// <summary> /// ArgumentException with message like "Static method requires null instance, non-static method requires non-null instance." /// </summary> internal static Exception OnlyStaticMethodsHaveNullInstance() { return new ArgumentException(Strings.OnlyStaticMethodsHaveNullInstance); } /// <summary> /// ArgumentException with message like "Property cannot have a void type." /// </summary> internal static Exception PropertyTypeCannotBeVoid() { return new ArgumentException(Strings.PropertyTypeCannotBeVoid); } /// <summary> /// ArgumentException with message like "Can only unbox from an object or interface type to a value type." /// </summary> internal static Exception InvalidUnboxType() { return new ArgumentException(Strings.InvalidUnboxType); } /// <summary> /// ArgumentException with message like "Argument must not have a value type." /// </summary> internal static Exception ArgumentMustNotHaveValueType() { return new ArgumentException(Strings.ArgumentMustNotHaveValueType); } /// <summary> /// ArgumentException with message like "must be reducible node" /// </summary> internal static Exception MustBeReducible() { return new ArgumentException(Strings.MustBeReducible); } /// <summary> /// ArgumentException with message like "Default body must be supplied if case bodies are not System.Void." /// </summary> internal static Exception DefaultBodyMustBeSupplied() { return new ArgumentException(Strings.DefaultBodyMustBeSupplied); } /// <summary> /// ArgumentException with message like "MethodBuilder does not have a valid TypeBuilder" /// </summary> internal static Exception MethodBuilderDoesNotHaveTypeBuilder() { return new ArgumentException(Strings.MethodBuilderDoesNotHaveTypeBuilder); } /// <summary> /// ArgumentException with message like "Label type must be System.Void if an expression is not supplied" /// </summary> internal static Exception LabelMustBeVoidOrHaveExpression() { return new ArgumentException(Strings.LabelMustBeVoidOrHaveExpression); } /// <summary> /// ArgumentException with message like "Type must be System.Void for this label argument" /// </summary> internal static Exception LabelTypeMustBeVoid() { return new ArgumentException(Strings.LabelTypeMustBeVoid); } /// <summary> /// ArgumentException with message like "Quoted expression must be a lambda" /// </summary> internal static Exception QuotedExpressionMustBeLambda() { return new ArgumentException(Strings.QuotedExpressionMustBeLambda); } /// <summary> /// ArgumentException with message like "Variable '{0}' uses unsupported type '{1}'. Reference types are not supported for variables." /// </summary> internal static Exception VariableMustNotBeByRef(object p0, object p1) { return new ArgumentException(Strings.VariableMustNotBeByRef(p0, p1)); } /// <summary> /// ArgumentException with message like "Found duplicate parameter '{0}'. Each ParameterExpression in the list must be a unique object." /// </summary> internal static Exception DuplicateVariable(object p0) { return new ArgumentException(Strings.DuplicateVariable(p0)); } /// <summary> /// ArgumentException with message like "Start and End must be well ordered" /// </summary> internal static Exception StartEndMustBeOrdered() { return new ArgumentException(Strings.StartEndMustBeOrdered); } /// <summary> /// ArgumentException with message like "fault cannot be used with catch or finally clauses" /// </summary> internal static Exception FaultCannotHaveCatchOrFinally() { return new ArgumentException(Strings.FaultCannotHaveCatchOrFinally); } /// <summary> /// ArgumentException with message like "try must have at least one catch, finally, or fault clause" /// </summary> internal static Exception TryMustHaveCatchFinallyOrFault() { return new ArgumentException(Strings.TryMustHaveCatchFinallyOrFault); } /// <summary> /// ArgumentException with message like "Body of catch must have the same type as body of try." /// </summary> internal static Exception BodyOfCatchMustHaveSameTypeAsBodyOfTry() { return new ArgumentException(Strings.BodyOfCatchMustHaveSameTypeAsBodyOfTry); } /// <summary> /// InvalidOperationException with message like "Extension node must override the property {0}." /// </summary> internal static Exception ExtensionNodeMustOverrideProperty(object p0) { return new InvalidOperationException(Strings.ExtensionNodeMustOverrideProperty(p0)); } /// <summary> /// ArgumentException with message like "User-defined operator method '{0}' must be static." /// </summary> internal static Exception UserDefinedOperatorMustBeStatic(object p0) { return new ArgumentException(Strings.UserDefinedOperatorMustBeStatic(p0)); } /// <summary> /// ArgumentException with message like "User-defined operator method '{0}' must not be void." /// </summary> internal static Exception UserDefinedOperatorMustNotBeVoid(object p0) { return new ArgumentException(Strings.UserDefinedOperatorMustNotBeVoid(p0)); } /// <summary> /// InvalidOperationException with message like "No coercion operator is defined between types '{0}' and '{1}'." /// </summary> internal static Exception CoercionOperatorNotDefined(object p0, object p1) { return new InvalidOperationException(Strings.CoercionOperatorNotDefined(p0, p1)); } /// <summary> /// InvalidOperationException with message like "The unary operator {0} is not defined for the type '{1}'." /// </summary> internal static Exception UnaryOperatorNotDefined(object p0, object p1) { return new InvalidOperationException(Strings.UnaryOperatorNotDefined(p0, p1)); } /// <summary> /// InvalidOperationException with message like "The binary operator {0} is not defined for the types '{1}' and '{2}'." /// </summary> internal static Exception BinaryOperatorNotDefined(object p0, object p1, object p2) { return new InvalidOperationException(Strings.BinaryOperatorNotDefined(p0, p1, p2)); } /// <summary> /// InvalidOperationException with message like "Reference equality is not defined for the types '{0}' and '{1}'." /// </summary> internal static Exception ReferenceEqualityNotDefined(object p0, object p1) { return new InvalidOperationException(Strings.ReferenceEqualityNotDefined(p0, p1)); } /// <summary> /// InvalidOperationException with message like "The operands for operator '{0}' do not match the parameters of method '{1}'." /// </summary> internal static Exception OperandTypesDoNotMatchParameters(object p0, object p1) { return new InvalidOperationException(Strings.OperandTypesDoNotMatchParameters(p0, p1)); } /// <summary> /// InvalidOperationException with message like "The return type of overload method for operator '{0}' does not match the parameter type of conversion method '{1}'." /// </summary> internal static Exception OverloadOperatorTypeDoesNotMatchConversionType(object p0, object p1) { return new InvalidOperationException(Strings.OverloadOperatorTypeDoesNotMatchConversionType(p0, p1)); } /// <summary> /// InvalidOperationException with message like "Conversion is not supported for arithmetic types without operator overloading." /// </summary> internal static Exception ConversionIsNotSupportedForArithmeticTypes() { return new InvalidOperationException(Strings.ConversionIsNotSupportedForArithmeticTypes); } /// <summary> /// ArgumentException with message like "Argument must be array" /// </summary> internal static Exception ArgumentMustBeArray() { return new ArgumentException(Strings.ArgumentMustBeArray); } /// <summary> /// ArgumentException with message like "Argument must be boolean" /// </summary> internal static Exception ArgumentMustBeBoolean() { return new ArgumentException(Strings.ArgumentMustBeBoolean); } /// <summary> /// ArgumentException with message like "The user-defined equality method '{0}' must return a boolean value." /// </summary> internal static Exception EqualityMustReturnBoolean(object p0) { return new ArgumentException(Strings.EqualityMustReturnBoolean(p0)); } /// <summary> /// ArgumentException with message like "Argument must be either a FieldInfo or PropertyInfo" /// </summary> internal static Exception ArgumentMustBeFieldInfoOrPropertInfo() { return new ArgumentException(Strings.ArgumentMustBeFieldInfoOrPropertInfo); } /// <summary> /// ArgumentException with message like "Argument must be either a FieldInfo, PropertyInfo or MethodInfo" /// </summary> internal static Exception ArgumentMustBeFieldInfoOrPropertInfoOrMethod() { return new ArgumentException(Strings.ArgumentMustBeFieldInfoOrPropertInfoOrMethod); } /// <summary> /// ArgumentException with message like "Argument must be an instance member" /// </summary> internal static Exception ArgumentMustBeInstanceMember() { return new ArgumentException(Strings.ArgumentMustBeInstanceMember); } /// <summary> /// ArgumentException with message like "Argument must be of an integer type" /// </summary> internal static Exception ArgumentMustBeInteger() { return new ArgumentException(Strings.ArgumentMustBeInteger); } /// <summary> /// ArgumentException with message like "Argument for array index must be of type Int32" /// </summary> internal static Exception ArgumentMustBeArrayIndexType() { return new ArgumentException(Strings.ArgumentMustBeArrayIndexType); } /// <summary> /// ArgumentException with message like "Argument must be single dimensional array type" /// </summary> internal static Exception ArgumentMustBeSingleDimensionalArrayType() { return new ArgumentException(Strings.ArgumentMustBeSingleDimensionalArrayType); } /// <summary> /// ArgumentException with message like "Argument types do not match" /// </summary> internal static Exception ArgumentTypesMustMatch() { return new ArgumentException(Strings.ArgumentTypesMustMatch); } /// <summary> /// InvalidOperationException with message like "Cannot auto initialize elements of value type through property '{0}', use assignment instead" /// </summary> internal static Exception CannotAutoInitializeValueTypeElementThroughProperty(object p0) { return new InvalidOperationException(Strings.CannotAutoInitializeValueTypeElementThroughProperty(p0)); } /// <summary> /// InvalidOperationException with message like "Cannot auto initialize members of value type through property '{0}', use assignment instead" /// </summary> internal static Exception CannotAutoInitializeValueTypeMemberThroughProperty(object p0) { return new InvalidOperationException(Strings.CannotAutoInitializeValueTypeMemberThroughProperty(p0)); } /// <summary> /// ArgumentException with message like "The type used in TypeAs Expression must be of reference or nullable type, {0} is neither" /// </summary> internal static Exception IncorrectTypeForTypeAs(object p0) { return new ArgumentException(Strings.IncorrectTypeForTypeAs(p0)); } /// <summary> /// InvalidOperationException with message like "Coalesce used with type that cannot be null" /// </summary> internal static Exception CoalesceUsedOnNonNullType() { return new InvalidOperationException(Strings.CoalesceUsedOnNonNullType); } /// <summary> /// InvalidOperationException with message like "An expression of type '{0}' cannot be used to initialize an array of type '{1}'" /// </summary> internal static Exception ExpressionTypeCannotInitializeArrayType(object p0, object p1) { return new InvalidOperationException(Strings.ExpressionTypeCannotInitializeArrayType(p0, p1)); } /// <summary> /// ArgumentException with message like "Expression of type '{0}' cannot be used for constructor parameter of type '{1}'" /// </summary> internal static Exception ExpressionTypeDoesNotMatchConstructorParameter(object p0, object p1) { return Dynamic.Utils.Error.ExpressionTypeDoesNotMatchConstructorParameter(p0, p1); } /// <summary> /// ArgumentException with message like " Argument type '{0}' does not match the corresponding member type '{1}'" /// </summary> internal static Exception ArgumentTypeDoesNotMatchMember(object p0, object p1) { return new ArgumentException(Strings.ArgumentTypeDoesNotMatchMember(p0, p1)); } /// <summary> /// ArgumentException with message like " The member '{0}' is not declared on type '{1}' being created" /// </summary> internal static Exception ArgumentMemberNotDeclOnType(object p0, object p1) { return new ArgumentException(Strings.ArgumentMemberNotDeclOnType(p0, p1)); } /// <summary> /// ArgumentException with message like "Expression of type '{0}' cannot be used for parameter of type '{1}' of method '{2}'" /// </summary> internal static Exception ExpressionTypeDoesNotMatchMethodParameter(object p0, object p1, object p2) { return Dynamic.Utils.Error.ExpressionTypeDoesNotMatchMethodParameter(p0, p1, p2); } /// <summary> /// ArgumentException with message like "Expression of type '{0}' cannot be used for parameter of type '{1}'" /// </summary> internal static Exception ExpressionTypeDoesNotMatchParameter(object p0, object p1) { return Dynamic.Utils.Error.ExpressionTypeDoesNotMatchParameter(p0, p1); } /// <summary> /// ArgumentException with message like "Expression of type '{0}' cannot be used for return type '{1}'" /// </summary> internal static Exception ExpressionTypeDoesNotMatchReturn(object p0, object p1) { return new ArgumentException(Strings.ExpressionTypeDoesNotMatchReturn(p0, p1)); } /// <summary> /// ArgumentException with message like "Expression of type '{0}' cannot be used for assignment to type '{1}'" /// </summary> internal static Exception ExpressionTypeDoesNotMatchAssignment(object p0, object p1) { return new ArgumentException(Strings.ExpressionTypeDoesNotMatchAssignment(p0, p1)); } /// <summary> /// ArgumentException with message like "Expression of type '{0}' cannot be used for label of type '{1}'" /// </summary> internal static Exception ExpressionTypeDoesNotMatchLabel(object p0, object p1) { return new ArgumentException(Strings.ExpressionTypeDoesNotMatchLabel(p0, p1)); } /// <summary> /// ArgumentException with message like "Expression of type '{0}' cannot be invoked" /// </summary> internal static Exception ExpressionTypeNotInvocable(object p0) { return new ArgumentException(Strings.ExpressionTypeNotInvocable(p0)); } /// <summary> /// ArgumentException with message like "Field '{0}' is not defined for type '{1}'" /// </summary> internal static Exception FieldNotDefinedForType(object p0, object p1) { return new ArgumentException(Strings.FieldNotDefinedForType(p0, p1)); } /// <summary> /// ArgumentException with message like "Instance field '{0}' is not defined for type '{1}'" /// </summary> internal static Exception InstanceFieldNotDefinedForType(object p0, object p1) { return new ArgumentException(Strings.InstanceFieldNotDefinedForType(p0, p1)); } /// <summary> /// ArgumentException with message like "Field '{0}.{1}' is not defined for type '{2}'" /// </summary> internal static Exception FieldInfoNotDefinedForType(object p0, object p1, object p2) { return new ArgumentException(Strings.FieldInfoNotDefinedForType(p0, p1, p2)); } /// <summary> /// ArgumentException with message like "Incorrect number of indexes" /// </summary> internal static Exception IncorrectNumberOfIndexes() { return new ArgumentException(Strings.IncorrectNumberOfIndexes); } /// <summary> /// InvalidOperationException with message like "Incorrect number of arguments supplied for lambda invocation" /// </summary> internal static Exception IncorrectNumberOfLambdaArguments() { return Dynamic.Utils.Error.IncorrectNumberOfLambdaArguments(); } /// <summary> /// ArgumentException with message like "Incorrect number of parameters supplied for lambda declaration" /// </summary> internal static Exception IncorrectNumberOfLambdaDeclarationParameters() { return new ArgumentException(Strings.IncorrectNumberOfLambdaDeclarationParameters); } /// <summary> /// ArgumentException with message like "Incorrect number of arguments supplied for call to method '{0}'" /// </summary> internal static Exception IncorrectNumberOfMethodCallArguments(object p0) { return Dynamic.Utils.Error.IncorrectNumberOfMethodCallArguments(p0); } /// <summary> /// ArgumentException with message like "Incorrect number of arguments for constructor" /// </summary> internal static Exception IncorrectNumberOfConstructorArguments() { return Dynamic.Utils.Error.IncorrectNumberOfConstructorArguments(); } /// <summary> /// ArgumentException with message like " Incorrect number of members for constructor" /// </summary> internal static Exception IncorrectNumberOfMembersForGivenConstructor() { return new ArgumentException(Strings.IncorrectNumberOfMembersForGivenConstructor); } /// <summary> /// ArgumentException with message like "Incorrect number of arguments for the given members " /// </summary> internal static Exception IncorrectNumberOfArgumentsForMembers() { return new ArgumentException(Strings.IncorrectNumberOfArgumentsForMembers); } /// <summary> /// ArgumentException with message like "Lambda type parameter must be derived from System.Delegate" /// </summary> internal static Exception LambdaTypeMustBeDerivedFromSystemDelegate() { return new ArgumentException(Strings.LambdaTypeMustBeDerivedFromSystemDelegate); } /// <summary> /// ArgumentException with message like "Member '{0}' not field or property" /// </summary> internal static Exception MemberNotFieldOrProperty(object p0) { return new ArgumentException(Strings.MemberNotFieldOrProperty(p0)); } /// <summary> /// ArgumentException with message like "Method {0} contains generic parameters" /// </summary> internal static Exception MethodContainsGenericParameters(object p0) { return new ArgumentException(Strings.MethodContainsGenericParameters(p0)); } /// <summary> /// ArgumentException with message like "Method {0} is a generic method definition" /// </summary> internal static Exception MethodIsGeneric(object p0) { return new ArgumentException(Strings.MethodIsGeneric(p0)); } /// <summary> /// ArgumentException with message like "The method '{0}.{1}' is not a property accessor" /// </summary> internal static Exception MethodNotPropertyAccessor(object p0, object p1) { return new ArgumentException(Strings.MethodNotPropertyAccessor(p0, p1)); } /// <summary> /// ArgumentException with message like "The property '{0}' has no 'get' accessor" /// </summary> internal static Exception PropertyDoesNotHaveGetter(object p0) { return new ArgumentException(Strings.PropertyDoesNotHaveGetter(p0)); } /// <summary> /// ArgumentException with message like "The property '{0}' has no 'set' accessor" /// </summary> internal static Exception PropertyDoesNotHaveSetter(object p0) { return new ArgumentException(Strings.PropertyDoesNotHaveSetter(p0)); } /// <summary> /// ArgumentException with message like "The property '{0}' has no 'get' or 'set' accessors" /// </summary> internal static Exception PropertyDoesNotHaveAccessor(object p0) { return new ArgumentException(Strings.PropertyDoesNotHaveAccessor(p0)); } /// <summary> /// ArgumentException with message like "'{0}' is not a member of type '{1}'" /// </summary> internal static Exception NotAMemberOfType(object p0, object p1) { return new ArgumentException(Strings.NotAMemberOfType(p0, p1)); } /// <summary> /// PlatformNotSupportedException with message like "The instruction '{0}' is not supported for type '{1}'" /// </summary> internal static Exception ExpressionNotSupportedForType(object p0, object p1) { return new PlatformNotSupportedException(Strings.ExpressionNotSupportedForType(p0, p1)); } /// <summary> /// PlatformNotSupportedException with message like "The instruction '{0}' is not supported for nullable type '{1}'" /// </summary> internal static Exception ExpressionNotSupportedForNullableType(object p0, object p1) { return new PlatformNotSupportedException(Strings.ExpressionNotSupportedForNullableType(p0, p1)); } /// <summary> /// ArgumentException with message like "ParameterExpression of type '{0}' cannot be used for delegate parameter of type '{1}'" /// </summary> internal static Exception ParameterExpressionNotValidAsDelegate(object p0, object p1) { return new ArgumentException(Strings.ParameterExpressionNotValidAsDelegate(p0, p1)); } /// <summary> /// ArgumentException with message like "Property '{0}' is not defined for type '{1}'" /// </summary> internal static Exception PropertyNotDefinedForType(object p0, object p1) { return new ArgumentException(Strings.PropertyNotDefinedForType(p0, p1)); } /// <summary> /// ArgumentException with message like "Instance property '{0}' is not defined for type '{1}'" /// </summary> internal static Exception InstancePropertyNotDefinedForType(object p0, object p1) { return new ArgumentException(Strings.InstancePropertyNotDefinedForType(p0, p1)); } /// <summary> /// ArgumentException with message like "Instance property '{0}' that takes no argument is not defined for type '{1}'" /// </summary> internal static Exception InstancePropertyWithoutParameterNotDefinedForType(object p0, object p1) { return new ArgumentException(Strings.InstancePropertyWithoutParameterNotDefinedForType(p0, p1)); } /// <summary> /// ArgumentException with message like "Instance property '{0}{1}' is not defined for type '{2}'" /// </summary> internal static Exception InstancePropertyWithSpecifiedParametersNotDefinedForType(object p0, object p1, object p2) { return new ArgumentException(Strings.InstancePropertyWithSpecifiedParametersNotDefinedForType(p0, p1, p2)); } /// <summary> /// ArgumentException with message like "Method '{0}' declared on type '{1}' cannot be called with instance of type '{2}'" /// </summary> internal static Exception InstanceAndMethodTypeMismatch(object p0, object p1, object p2) { return new ArgumentException(Strings.InstanceAndMethodTypeMismatch(p0, p1, p2)); } /// <summary> /// ArgumentException with message like "Type '{0}' does not have a default constructor" /// </summary> internal static Exception TypeMissingDefaultConstructor(object p0) { return new ArgumentException(Strings.TypeMissingDefaultConstructor(p0)); } /// <summary> /// ArgumentException with message like "List initializers must contain at least one initializer" /// </summary> internal static Exception ListInitializerWithZeroMembers() { return new ArgumentException(Strings.ListInitializerWithZeroMembers); } /// <summary> /// ArgumentException with message like "Element initializer method must be named 'Add'" /// </summary> internal static Exception ElementInitializerMethodNotAdd() { return new ArgumentException(Strings.ElementInitializerMethodNotAdd); } /// <summary> /// ArgumentException with message like "Parameter '{0}' of element initializer method '{1}' must not be a pass by reference parameter" /// </summary> internal static Exception ElementInitializerMethodNoRefOutParam(object p0, object p1) { return new ArgumentException(Strings.ElementInitializerMethodNoRefOutParam(p0, p1)); } /// <summary> /// ArgumentException with message like "Element initializer method must have at least 1 parameter" /// </summary> internal static Exception ElementInitializerMethodWithZeroArgs() { return new ArgumentException(Strings.ElementInitializerMethodWithZeroArgs); } /// <summary> /// ArgumentException with message like "Element initializer method must be an instance method" /// </summary> internal static Exception ElementInitializerMethodStatic() { return new ArgumentException(Strings.ElementInitializerMethodStatic); } /// <summary> /// ArgumentException with message like "Type '{0}' is not IEnumerable" /// </summary> internal static Exception TypeNotIEnumerable(object p0) { return new ArgumentException(Strings.TypeNotIEnumerable(p0)); } /// <summary> /// InvalidOperationException with message like "Unexpected coalesce operator." /// </summary> internal static Exception UnexpectedCoalesceOperator() { return new InvalidOperationException(Strings.UnexpectedCoalesceOperator); } /// <summary> /// InvalidOperationException with message like "Cannot cast from type '{0}' to type '{1}" /// </summary> internal static Exception InvalidCast(object p0, object p1) { return new InvalidOperationException(Strings.InvalidCast(p0, p1)); } /// <summary> /// ArgumentException with message like "Unhandled binary: {0}" /// </summary> internal static Exception UnhandledBinary(object p0) { return new ArgumentException(Strings.UnhandledBinary(p0)); } /// <summary> /// ArgumentException with message like "Unhandled binding " /// </summary> internal static Exception UnhandledBinding() { return new ArgumentException(Strings.UnhandledBinding); } /// <summary> /// ArgumentException with message like "Unhandled Binding Type: {0}" /// </summary> internal static Exception UnhandledBindingType(object p0) { return new ArgumentException(Strings.UnhandledBindingType(p0)); } /// <summary> /// ArgumentException with message like "Unhandled convert: {0}" /// </summary> internal static Exception UnhandledConvert(object p0) { return new ArgumentException(Strings.UnhandledConvert(p0)); } /// <summary> /// ArgumentException with message like "Unhandled Expression Type: {0}" /// </summary> internal static Exception UnhandledExpressionType(object p0) { return new ArgumentException(Strings.UnhandledExpressionType(p0)); } /// <summary> /// ArgumentException with message like "Unhandled unary: {0}" /// </summary> internal static Exception UnhandledUnary(object p0) { return new ArgumentException(Strings.UnhandledUnary(p0)); } /// <summary> /// ArgumentException with message like "Unknown binding type" /// </summary> internal static Exception UnknownBindingType() { return new ArgumentException(Strings.UnknownBindingType); } /// <summary> /// ArgumentException with message like "The user-defined operator method '{1}' for operator '{0}' must have identical parameter and return types." /// </summary> internal static Exception UserDefinedOpMustHaveConsistentTypes(object p0, object p1) { return new ArgumentException(Strings.UserDefinedOpMustHaveConsistentTypes(p0, p1)); } /// <summary> /// ArgumentException with message like "The user-defined operator method '{1}' for operator '{0}' must return the same type as its parameter or a derived type." /// </summary> internal static Exception UserDefinedOpMustHaveValidReturnType(object p0, object p1) { return new ArgumentException(Strings.UserDefinedOpMustHaveValidReturnType(p0, p1)); } /// <summary> /// ArgumentException with message like "The user-defined operator method '{1}' for operator '{0}' must have associated boolean True and False operators." /// </summary> internal static Exception LogicalOperatorMustHaveBooleanOperators(object p0, object p1) { return new ArgumentException(Strings.LogicalOperatorMustHaveBooleanOperators(p0, p1)); } /// <summary> /// InvalidOperationException with message like "No method '{0}' exists on type '{1}'." /// </summary> internal static Exception MethodDoesNotExistOnType(object p0, object p1) { return new InvalidOperationException(Strings.MethodDoesNotExistOnType(p0, p1)); } /// <summary> /// InvalidOperationException with message like "No method '{0}' on type '{1}' is compatible with the supplied arguments." /// </summary> internal static Exception MethodWithArgsDoesNotExistOnType(object p0, object p1) { return new InvalidOperationException(Strings.MethodWithArgsDoesNotExistOnType(p0, p1)); } /// <summary> /// InvalidOperationException with message like "No generic method '{0}' on type '{1}' is compatible with the supplied type arguments and arguments. No type arguments should be provided if the method is non-generic. " /// </summary> internal static Exception GenericMethodWithArgsDoesNotExistOnType(object p0, object p1) { return new InvalidOperationException(Strings.GenericMethodWithArgsDoesNotExistOnType(p0, p1)); } /// <summary> /// InvalidOperationException with message like "More than one method '{0}' on type '{1}' is compatible with the supplied arguments." /// </summary> internal static Exception MethodWithMoreThanOneMatch(object p0, object p1) { return new InvalidOperationException(Strings.MethodWithMoreThanOneMatch(p0, p1)); } /// <summary> /// InvalidOperationException with message like "More than one property '{0}' on type '{1}' is compatible with the supplied arguments." /// </summary> internal static Exception PropertyWithMoreThanOneMatch(object p0, object p1) { return new InvalidOperationException(Strings.PropertyWithMoreThanOneMatch(p0, p1)); } /// <summary> /// ArgumentException with message like "An incorrect number of type args were specified for the declaration of a Func type." /// </summary> internal static Exception IncorrectNumberOfTypeArgsForFunc() { return new ArgumentException(Strings.IncorrectNumberOfTypeArgsForFunc); } /// <summary> /// ArgumentException with message like "An incorrect number of type args were specified for the declaration of an Action type." /// </summary> internal static Exception IncorrectNumberOfTypeArgsForAction() { return new ArgumentException(Strings.IncorrectNumberOfTypeArgsForAction); } /// <summary> /// ArgumentException with message like "Argument type cannot be System.Void." /// </summary> internal static Exception ArgumentCannotBeOfTypeVoid() { return new ArgumentException(Strings.ArgumentCannotBeOfTypeVoid); } /// <summary> /// ArgumentException with message like "Invalid operation: '{0}'" /// </summary> internal static Exception InvalidOperation(object p0) { return new ArgumentException(Strings.InvalidOperation(p0)); } /// <summary> /// ArgumentOutOfRangeException with message like "{0} must be greater than or equal to {1}" /// </summary> internal static Exception OutOfRange(object p0, object p1) { return new ArgumentOutOfRangeException(Strings.OutOfRange(p0, p1)); } /// <summary> /// InvalidOperationException with message like "Queue empty." /// </summary> internal static Exception QueueEmpty() { return new InvalidOperationException(Strings.QueueEmpty); } /// <summary> /// InvalidOperationException with message like "Cannot redefine label '{0}' in an inner block." /// </summary> internal static Exception LabelTargetAlreadyDefined(object p0) { return new InvalidOperationException(Strings.LabelTargetAlreadyDefined(p0)); } /// <summary> /// InvalidOperationException with message like "Cannot jump to undefined label '{0}'." /// </summary> internal static Exception LabelTargetUndefined(object p0) { return new InvalidOperationException(Strings.LabelTargetUndefined(p0)); } /// <summary> /// InvalidOperationException with message like "Control cannot leave a finally block." /// </summary> internal static Exception ControlCannotLeaveFinally() { return new InvalidOperationException(Strings.ControlCannotLeaveFinally); } /// <summary> /// InvalidOperationException with message like "Control cannot leave a filter test." /// </summary> internal static Exception ControlCannotLeaveFilterTest() { return new InvalidOperationException(Strings.ControlCannotLeaveFilterTest); } /// <summary> /// InvalidOperationException with message like "Cannot jump to ambiguous label '{0}'." /// </summary> internal static Exception AmbiguousJump(object p0) { return new InvalidOperationException(Strings.AmbiguousJump(p0)); } /// <summary> /// InvalidOperationException with message like "Control cannot enter a try block." /// </summary> internal static Exception ControlCannotEnterTry() { return new InvalidOperationException(Strings.ControlCannotEnterTry); } /// <summary> /// InvalidOperationException with message like "Control cannot enter an expression--only statements can be jumped into." /// </summary> internal static Exception ControlCannotEnterExpression() { return new InvalidOperationException(Strings.ControlCannotEnterExpression); } /// <summary> /// InvalidOperationException with message like "Cannot jump to non-local label '{0}' with a value. Only jumps to labels defined in outer blocks can pass values." /// </summary> internal static Exception NonLocalJumpWithValue(object p0) { return new InvalidOperationException(Strings.NonLocalJumpWithValue(p0)); } /// <summary> /// InvalidOperationException with message like "Extension should have been reduced." /// </summary> internal static Exception ExtensionNotReduced() { return new InvalidOperationException(Strings.ExtensionNotReduced); } /// <summary> /// InvalidOperationException with message like "CompileToMethod cannot compile constant '{0}' because it is a non-trivial value, such as a live object. Instead, create an expression tree that can construct this value." /// </summary> internal static Exception CannotCompileConstant(object p0) { return new InvalidOperationException(Strings.CannotCompileConstant(p0)); } /// <summary> /// NotSupportedException with message like "Dynamic expressions are not supported by CompileToMethod. Instead, create an expression tree that uses System.Runtime.CompilerServices.CallSite." /// </summary> internal static Exception CannotCompileDynamic() { return new NotSupportedException(Strings.CannotCompileDynamic); } /// <summary> /// InvalidOperationException with message like "Invalid lvalue for assignment: {0}." /// </summary> internal static Exception InvalidLvalue(object p0) { return new InvalidOperationException(Strings.InvalidLvalue(p0)); } /// <summary> /// InvalidOperationException with message like "Invalid member type: {0}." /// </summary> internal static Exception InvalidMemberType(object p0) { return new InvalidOperationException(Strings.InvalidMemberType(p0)); } /// <summary> /// InvalidOperationException with message like "unknown lift type: '{0}'." /// </summary> internal static Exception UnknownLiftType(object p0) { return new InvalidOperationException(Strings.UnknownLiftType(p0)); } /// <summary> /// ArgumentException with message like "Invalid output directory." /// </summary> internal static Exception InvalidOutputDir() { return new ArgumentException(Strings.InvalidOutputDir); } /// <summary> /// ArgumentException with message like "Invalid assembly name or file extension." /// </summary> internal static Exception InvalidAsmNameOrExtension() { return new ArgumentException(Strings.InvalidAsmNameOrExtension); } /// <summary> /// ArgumentException with message like "Cannot create instance of {0} because it contains generic parameters" /// </summary> internal static Exception IllegalNewGenericParams(object p0) { return new ArgumentException(Strings.IllegalNewGenericParams(p0)); } /// <summary> /// InvalidOperationException with message like "variable '{0}' of type '{1}' referenced from scope '{2}', but it is not defined" /// </summary> internal static Exception UndefinedVariable(object p0, object p1, object p2) { return new InvalidOperationException(Strings.UndefinedVariable(p0, p1, p2)); } /// <summary> /// InvalidOperationException with message like "Cannot close over byref parameter '{0}' referenced in lambda '{1}'" /// </summary> internal static Exception CannotCloseOverByRef(object p0, object p1) { return new InvalidOperationException(Strings.CannotCloseOverByRef(p0, p1)); } /// <summary> /// InvalidOperationException with message like "Unexpected VarArgs call to method '{0}'" /// </summary> internal static Exception UnexpectedVarArgsCall(object p0) { return new InvalidOperationException(Strings.UnexpectedVarArgsCall(p0)); } /// <summary> /// InvalidOperationException with message like "Rethrow statement is valid only inside a Catch block." /// </summary> internal static Exception RethrowRequiresCatch() { return new InvalidOperationException(Strings.RethrowRequiresCatch); } /// <summary> /// InvalidOperationException with message like "Try expression is not allowed inside a filter body." /// </summary> internal static Exception TryNotAllowedInFilter() { return new InvalidOperationException(Strings.TryNotAllowedInFilter); } /// <summary> /// InvalidOperationException with message like "When called from '{0}', rewriting a node of type '{1}' must return a non-null value of the same type. Alternatively, override '{2}' and change it to not visit children of this type." /// </summary> internal static Exception MustRewriteToSameNode(object p0, object p1, object p2) { return new InvalidOperationException(Strings.MustRewriteToSameNode(p0, p1, p2)); } /// <summary> /// InvalidOperationException with message like "Rewriting child expression from type '{0}' to type '{1}' is not allowed, because it would change the meaning of the operation. If this is intentional, override '{2}' and change it to allow this rewrite." /// </summary> internal static Exception MustRewriteChildToSameType(object p0, object p1, object p2) { return new InvalidOperationException(Strings.MustRewriteChildToSameType(p0, p1, p2)); } /// <summary> /// InvalidOperationException with message like "Rewritten expression calls operator method '{0}', but the original node had no operator method. If this is is intentional, override '{1}' and change it to allow this rewrite." /// </summary> internal static Exception MustRewriteWithoutMethod(object p0, object p1) { return new InvalidOperationException(Strings.MustRewriteWithoutMethod(p0, p1)); } /// <summary> /// NotSupportedException with message like "TryExpression is not supported as an argument to method '{0}' because it has an argument with by-ref type. Construct the tree so the TryExpression is not nested inside of this expression." /// </summary> internal static Exception TryNotSupportedForMethodsWithRefArgs(object p0) { return new NotSupportedException(Strings.TryNotSupportedForMethodsWithRefArgs(p0)); } /// <summary> /// NotSupportedException with message like "TryExpression is not supported as a child expression when accessing a member on type '{0}' because it is a value type. Construct the tree so the TryExpression is not nested inside of this expression." /// </summary> internal static Exception TryNotSupportedForValueTypeInstances(object p0) { return new NotSupportedException(Strings.TryNotSupportedForValueTypeInstances(p0)); } /// <summary> /// InvalidOperationException with message like "Dynamic operations can only be performed in homogenous AppDomain." /// </summary> internal static Exception HomogenousAppDomainRequired() { return new InvalidOperationException(Strings.HomogenousAppDomainRequired); } /// <summary> /// ArgumentException with message like "Test value of type '{0}' cannot be used for the comparison method parameter of type '{1}'" /// </summary> internal static Exception TestValueTypeDoesNotMatchComparisonMethodParameter(object p0, object p1) { return new ArgumentException(Strings.TestValueTypeDoesNotMatchComparisonMethodParameter(p0, p1)); } /// <summary> /// ArgumentException with message like "Switch value of type '{0}' cannot be used for the comparison method parameter of type '{1}'" /// </summary> internal static Exception SwitchValueTypeDoesNotMatchComparisonMethodParameter(object p0, object p1) { return new ArgumentException(Strings.SwitchValueTypeDoesNotMatchComparisonMethodParameter(p0, p1)); } /// <summary> /// NotSupportedException with message like "DebugInfoGenerator created by CreatePdbGenerator can only be used with LambdaExpression.CompileToMethod." /// </summary> internal static Exception PdbGeneratorNeedsExpressionCompiler() { return new NotSupportedException(Strings.PdbGeneratorNeedsExpressionCompiler); } /// <summary> /// The exception that is thrown when a null reference (Nothing in Visual Basic) is passed to a method that does not accept it as a valid argument. /// </summary> internal static Exception ArgumentNull(string paramName) { return new ArgumentNullException(paramName); } /// <summary> /// The exception that is thrown when the value of an argument is outside the allowable range of values as defined by the invoked method. /// </summary> internal static Exception ArgumentOutOfRange(string paramName) { return new ArgumentOutOfRangeException(paramName); } /// <summary> /// The exception that is thrown when an invoked method is not supported, or when there is an attempt to read, seek, or write to a stream that does not support the invoked functionality. /// </summary> internal static Exception NotSupported() { return new NotSupportedException(); } #if FEATURE_COMPILE /// <summary> /// NotImplementedException with message like "The operator '{0}' is not implemented for type '{1}'" /// </summary> internal static Exception OperatorNotImplementedForType(object p0, object p1) { return NotImplemented.ByDesignWithMessage(Strings.OperatorNotImplementedForType(p0, p1)); } #endif } }
using System; using System.Collections.Generic; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input.Touch; using System.Windows.Media; using System.Windows.Controls.Primitives; namespace System.Windows.Controls { public class MenuButton : RadioButton { public MenuButton () { items = new List<Button>(); this.HorizontalContentAlignment = HorizontalAlignment.Left; this.GroupName = "MenuButton"; this.ItemsPanel = new StackPanel(); this.IsUncheckable = true; } #region Events public event EventHandler ItemClick; #endregion #region Properties public Panel ItemsPanel { get; set; } public static DependencyProperty IsDropDownOpenProperty = DependencyProperty.Register ( "IsDropDownOpen", typeof ( bool ), typeof ( MenuButton ), new PropertyMetadata ( new PropertyChangedCallback ( ( s, e ) => { if ( ( bool ) e.NewValue ) ((MenuButton)s).OpenDropDownList ( ); else ((MenuButton)s).CloseDropDownList ( ); } ) ) ); public bool IsDropDownOpen { get { return ( bool ) GetValue (IsDropDownOpenProperty); } set { SetValue (IsDropDownOpenProperty, value); } } #endregion public override void Invalidate () { window.Left = (int)this.GetAbsoluteLeft() + this.ActualWidth + 2; window.Top = (int)this.GetAbsoluteTop() + this.ActualHeight / 2f - this.ItemsPanel.ActualHeight / 2f; base.Invalidate (); } public override void Initialize () { window = new Window(this); window.IsToolTip = false; window.FontFamily = this.FontFamily; window.BorderThickness = new Thickness (0); window.BorderBrush = Brushes.Transparent; window.Background = Brushes.Transparent;//new SolidColorBrush(new System.Windows.Media.Color ( .2f, .2f, .2f ) * .9f); // new SolidColorBrush(/*new System.Windows.Media.Color ( .8f, .8f, .8f )*/ Colors.CornflowerBlue ); window.Left = (int)this.GetAbsoluteLeft() + this.ActualWidth + 2; window.Top = (int)this.GetAbsoluteTop() + this.ActualHeight / 2f - this.ItemsPanel.ActualHeight / 2f; window.Width = this.ItemsPanel.ActualWidth; window.Height = this.ItemsPanel.ActualHeight; window.LostFocus += delegate { this.IsChecked = false; }; this.ItemsPanel.BorderBrush = null; this.ItemsPanel.BorderThickness = new Thickness(); this.ItemsPanel.Background = new SolidColorBrush(new System.Windows.Media.Color ( .5f, .5f, .5f ) * .95f ); this.ItemsPanel.Parent = window; window.Content = this.ItemsPanel; foreach (var item in items) { this.ItemsPanel.Children.Add(item); } base.Initialize(); } protected override void OnVisibleChanged (bool visible) { base.OnVisibleChanged(visible); if (!visible) window.Close(); } protected override void OnEnabledChanged (bool enabled) { base.OnEnabledChanged(enabled); if (!enabled) window.Close(); } public override void Draw (GameTime gameTime, SpriteBatch batch, float a, Matrix transform) { base.Draw(gameTime, batch, a, transform); batch.Begin ( SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.AnisotropicClamp, DepthStencilState.None, RasterizerState.CullNone, null, transform); var left = GetAbsoluteLeft (); var top = GetAbsoluteTop (); batch.Draw ( WPFLight.Resources.Textures.ArrowDown, new Rectangle ( (int)Math.Floor (left + this.ActualWidth - 15 + 6), (int)Math.Floor (top + this.ActualHeight / 2f), 16, 16), null, Microsoft.Xna.Framework.Color.White * .7f, MathHelper.ToRadians (-90), new Vector2 ( WPFLight.Resources.Textures.ArrowDown.Bounds.Width / 2f, WPFLight.Resources.Textures.ArrowDown.Height / 2f), SpriteEffects.None, 0); batch.End (); } public void AddItem ( string text ) { AddItem (text, null); } public void AddItem (string text, Brush foreground) { var cmd = new Button (); cmd.Parent = this.ItemsPanel; cmd.Content = text; cmd.Height = 60; cmd.Width = 80; cmd.Margin = new Thickness(2); cmd.HorizontalAlignment = HorizontalAlignment.Left; cmd.BorderBrush = new SolidColorBrush(Colors.White * .25f); cmd.BorderThickness = new Thickness (1f); if (foreground != null) cmd.Foreground = foreground; cmd.Tag = text; cmd.Click += (sender, e) => { if (!(sender is ToggleButton)) { window.Close(); this.IsChecked = false; } if ( this.ItemClick != null ) this.ItemClick ( sender, e ); }; if (this.IsInitialized) this.ItemsPanel.Children.Add(cmd); else items.Add(cmd); } public void AddItem (Button cmd) { cmd.Parent = this.ItemsPanel; cmd.BorderBrush = new SolidColorBrush(System.Windows.Media.Colors.White * .25f); cmd.BorderThickness = new Thickness(1); cmd.Height = 60; cmd.Width = 80; cmd.Margin = new Thickness(2); cmd.HorizontalAlignment = HorizontalAlignment.Left; cmd.Click += (sender, e) => { if (!(sender is ToggleButton)) { window.Close(); this.IsChecked = false; } if ( this.ItemClick != null ) this.ItemClick ( sender, e ); }; if (this.IsInitialized) this.ItemsPanel.Children.Add(cmd); else items.Add(cmd); } public void AddItem ( Image img ) { AddItem (img, null); } public void AddItem (Image img, object tag) { var cmd = new Button (); cmd.Content = img; cmd.BorderBrush = new SolidColorBrush(System.Windows.Media.Colors.White * .25f); cmd.BorderThickness = new Thickness(1); cmd.Parent = this.ItemsPanel; cmd.Height = 60; cmd.Width = 80; cmd.Margin = new Thickness(2); cmd.FontSize = this.FontSize; cmd.HorizontalAlignment = HorizontalAlignment.Left; cmd.Tag = tag; cmd.Click += (sender, e) => { if (!(sender is ToggleButton)) { window.Close(); this.IsChecked = false; } if ( this.ItemClick != null ) this.ItemClick ( sender, e ); }; if (this.IsInitialized) this.ItemsPanel.Children.Add(cmd); else items.Add(cmd); } public void AddItem (Texture2D image) { AddItem (image, new Thickness (7)); } public void AddItem ( Texture2D image, Thickness margin ) { AddItem (image, margin, null); } public void AddItem ( Texture2D image, Thickness margin, object tag ) { var cmd = new Button (); cmd.Content = new Image ( image) { Margin = margin }; cmd.BorderBrush = new SolidColorBrush(System.Windows.Media.Colors.White * .25f); cmd.BorderThickness = new Thickness(1); cmd.Parent = this.ItemsPanel; cmd.Height = 60; cmd.Width = 80; cmd.Margin = new Thickness(2); cmd.FontSize = this.FontSize; cmd.HorizontalAlignment = HorizontalAlignment.Left; cmd.Tag = tag; cmd.Click += (sender, e) => { if (!(sender is ToggleButton)) { window.Close(); this.IsChecked = false; } if ( this.ItemClick != null ) this.ItemClick ( sender, e ); }; if (this.IsInitialized) this.ItemsPanel.Children.Add(cmd); else items.Add(cmd); } public override void OnTouchDown (TouchLocation state) { if ( !this.IsDropDownOpen ) base.OnTouchDown (state); } protected override void OnCheckedChanged (bool chk) { base.OnCheckedChanged (chk); this.IsDropDownOpen = this.IsChecked; } void OpenDropDownList ( ) { if (this.IsInitialized) { window.Show (false); } } void CloseDropDownList ( ) { if (this.IsInitialized) { window.Close (); } } private Window window; private List<Button> items; } }
// // Copyright (c) Microsoft. All rights reserved. // // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Windows; using System.Windows.Controls; using System.Windows.Media; namespace PerFrameAnimation { public class MagnitismCanvas : Canvas { public MagnitismCanvas() { // suppress movement in the visual studio designer. if (Process.GetCurrentProcess().ProcessName != "devenv") CompositionTarget.Rendering += UpdateChildren; _timeTracker = new ParticleEffectsTimeTracker(); } private void UpdateChildren(object sender, EventArgs e) { //update time delta _timeTracker.Update(); foreach (UIElement child in LogicalTreeHelper.GetChildren(this)) { var velocity = _childrenVelocities.ContainsKey(child) ? _childrenVelocities[child] : new Vector(0, 0); //compute velocity dampening velocity = velocity*Drag; var truePosition = GetTruePosition(child); var childRect = new Rect(truePosition, child.RenderSize); //accumulate forces var forces = new Vector(0, 0); //add wall repulsion forces.X += BorderForce/Math.Max(1, childRect.Left); forces.X -= BorderForce/Math.Max(1, RenderSize.Width - childRect.Right); forces.Y += BorderForce/Math.Max(1, childRect.Top); forces.Y -= BorderForce/Math.Max(1, RenderSize.Height - childRect.Bottom); //each other child pushes away based on the square distance foreach (UIElement otherchild in LogicalTreeHelper.GetChildren(this)) { //dont push against itself if (otherchild == child) continue; var otherchildtruePosition = GetTruePosition(otherchild); var otherchildRect = new Rect(otherchildtruePosition, otherchild.RenderSize); //make sure rects aren't the same if (otherchildRect == childRect) continue; //ignore children with a size of 0,0 if (otherchildRect.Width == 0 && otherchildRect.Height == 0 || childRect.Width == 0 && childRect.Height == 0) continue; //vector from current other child to current child //are they overlapping? if so, distance is 0 var toChild = AreRectsOverlapping(childRect, otherchildRect) ? new Vector(0, 0) : VectorBetweenRects(childRect, otherchildRect); var length = toChild.Length; if (length < 1) { length = 1; var childCenter = GetCenter(childRect); var otherchildCenter = GetCenter(otherchildRect); //compute toChild from the center of both rects toChild = childCenter - otherchildCenter; } var childpush = ChildForce/length; toChild.Normalize(); forces += toChild*childpush; } //add forces to velocity and store it for next iteration velocity += forces; _childrenVelocities[child] = velocity; //move the object based on it's velocity SetTruePosition(child, truePosition + _timeTracker.DeltaSeconds*velocity); } } private bool AreRectsOverlapping(Rect r1, Rect r2) { if (r1.Bottom < r2.Top) return false; if (r1.Top > r2.Bottom) return false; if (r1.Right < r2.Left) return false; if (r1.Left > r2.Right) return false; return true; } private Point IntersectInsideRect(Rect r, Point raystart, Vector raydir) { var xtop = raystart.X + raydir.X*(r.Top - raystart.Y)/raydir.Y; var xbottom = raystart.X + raydir.X*(r.Bottom - raystart.Y)/raydir.Y; var yleft = raystart.Y + raydir.Y*(r.Left - raystart.X)/raydir.X; var yright = raystart.Y + raydir.Y*(r.Right - raystart.X)/raydir.X; var top = new Point(xtop, r.Top); var bottom = new Point(xbottom, r.Bottom); var left = new Point(r.Left, yleft); var right = new Point(r.Right, yright); var tv = raystart - top; var bv = raystart - bottom; var lv = raystart - left; var rv = raystart - right; //classify ray direction if (raydir.Y < 0) { if (raydir.X < 0) //top left { if (tv.LengthSquared < lv.LengthSquared) return top; return left; } if (tv.LengthSquared < rv.LengthSquared) return top; return right; } if (raydir.X < 0) //bottom left { if (bv.LengthSquared < lv.LengthSquared) return bottom; return left; } if (bv.LengthSquared < rv.LengthSquared) return bottom; return right; } private Vector VectorBetweenRects(Rect r1, Rect r2) { //find the edge points and use these to measure the distance var r1Center = GetCenter(r1); var r2Center = GetCenter(r2); var between = (r1Center - r2Center); between.Normalize(); var edge1 = IntersectInsideRect(r1, r1Center, -between); var edge2 = IntersectInsideRect(r2, r2Center, between); return edge1 - edge2; } private Point GetRenderTransformOffset(UIElement e) { //make sure they object's render transform is a translation var renderTranslation = e.RenderTransform as TranslateTransform; if (renderTranslation == null) { renderTranslation = new TranslateTransform(0, 0); e.RenderTransform = renderTranslation; } return new Point(renderTranslation.X, renderTranslation.Y); } private void SetRenderTransformOffset(UIElement e, Point offset) { //make sure they object's render transform is a translation var renderTranslation = e.RenderTransform as TranslateTransform; if (renderTranslation == null) { renderTranslation = new TranslateTransform(0, 0); e.RenderTransform = renderTranslation; } //set new offset renderTranslation.X = offset.X; renderTranslation.Y = offset.Y; } private Point GetTruePosition(UIElement e) { var renderTranslation = GetRenderTransformOffset(e); return new Point(GetLeft(e) + renderTranslation.X, GetTop(e) + renderTranslation.Y); } private void SetTruePosition(UIElement e, Point p) { var canvasOffset = new Vector(GetLeft(e), GetTop(e)); var renderTranslation = p - canvasOffset; SetRenderTransformOffset(e, renderTranslation); } private Point GetCenter(Rect r) => new Point((r.Left + r.Right) / 2.0, (r.Top + r.Bottom) / 2.0); #region Private Members private readonly ParticleEffectsTimeTracker _timeTracker; private readonly Dictionary<UIElement, Vector> _childrenVelocities = new Dictionary<UIElement, Vector>(); #endregion #region Properties public double BorderForce { get; set; } = 1000.0; public double ChildForce { get; set; } = 200.0; public double Drag { get; set; } = 0.9; #endregion } }
// // MRActivityWidget.cs // // Author: // Steve Jakab <> // // Copyright (c) 2014 Steve Jakab // // 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 UnityEngine; using System; using System.Collections; namespace PortableRealm { public class MRActivityWidget : MonoBehaviour, MRITouchable { #region Properties public MRClearingSelector clearingPrototype; public MRActivity Activity { get{ return mActivity; } set{ if (mActivity != value) { mActivity = value; if (mCamera != null) UpdateWidgetForActivity(); if (mActivity.Activity == MRGame.eActivity.Move && mClearing == null) { // create a clearing selector for the move mClearing = (MRClearingSelector)Instantiate(clearingPrototype); mClearing.transform.parent = transform; mClearing.Activity = this; mClearing.Clearing = ((MRMoveActivity)mActivity).Clearing; } else if (mClearing != null) { // remove the clearing selector Destroy(mClearing.gameObject); mClearing = null; } } } } public int ListPosition { get{ return mListPosition; } set{ if (mListPosition != value) { mListPosition = value; if (mCamera != null) UpdateWidgetForActivity(); } } } public bool Interactive { get{ return mIsInteractive; } set{ mIsInteractive = value; //Debug.Log("Activity " + mListPosition + " interactive set to " + mIsInteractive); } } public bool Visible { get{ return mVisible; } set{ mVisible = value; if (mClearing != null) mClearing.Visible = value; } } public bool Enabled { get{ return mIsEnabled; } set{ if (mIsEnabled != value) { mIsEnabled = value; if (mCamera != null) UpdateWidgetForActivity(); } } } public bool Editing { get{ return mEditingActivity; } set{ mEditingActivity = value; } } public float ActivityPixelSize { get{ return MRGame.TheGame.InspectionArea.ActivityWidthPixels; } } public Camera ActivityCamera { get{ return mCamera; } } public MRClearingSelector Clearing { get{ return mClearing; } } #endregion #region Methods // Use this for initialization void Start () { mVisible = true; mBorder = null; mCanceledBorder = null; foreach (Transform t in gameObject.GetComponentsInChildren<Transform>()) { if (t.gameObject.name == "Border") { mBorder = t.gameObject; } else if (t.gameObject.name == "Canceled Border") { mCanceledBorder = t.gameObject; break; } } if (mBorder == null) { Debug.LogError("No border for activity widget"); Application.Quit(); } if (mCanceledBorder == null) { Debug.LogError("No canceled border for activity widget"); Application.Quit(); } mBorder.GetComponent<Renderer>().enabled = true; mCanceledBorder.GetComponent<Renderer>().enabled = false; Sprite sprite = ((SpriteRenderer)mBorder.GetComponent<Renderer>()).sprite; mBorderSize = sprite.bounds.extents.y; // adjust the camera so it just shows the border area mCamera = gameObject.GetComponentsInChildren<Camera> ()[0]; mCamera.orthographicSize = mBorderSize; mCamera.aspect = 1; foreach (Transform t in gameObject.GetComponentsInChildren<Transform>()) { if (t.gameObject.name == "Activities") { mActivityStrip = t.gameObject; break; } } if (mActivityStrip == null) { Debug.LogError("No actions for activity widget"); Application.Quit(); } mActivityStripWidth = ((SpriteRenderer)mActivityStrip.GetComponent<Renderer>()).sprite.bounds.extents.x * 2.0f; int numActivities = Enum.GetValues(typeof(MRGame.eActivity)).Length; mActivityWidth = mActivityStripWidth / numActivities; mMaxActivityListPos = (mActivityStripWidth / 2) - (0.5f * mActivityWidth); mMinActivityListPos = (mActivityStripWidth / 2) - ((numActivities - 0.5f) * mActivityWidth); UpdateWidgetForActivity(); } // Update is called once per frame void Update () { if (!Visible) { mCamera.enabled = false; return; } mCamera.enabled = true; // show the appropriate border, for the canceled state of the activity mBorder.GetComponent<Renderer>().enabled = (mActivity == null || !mActivity.Canceled); mCanceledBorder.GetComponent<Renderer>().enabled = !mBorder.GetComponent<Renderer>().enabled; if (!mIsInteractive) { // set the action based on the widget's current position mChangingActivity = false; UpdateActivityForWidget(); return; } if (MRGame.TimeOfDay == MRGame.eTimeOfDay.Birdsong && MRGame.JustTouched && MRGame.TheGame.CurrentView == MRGame.eViews.Map) { // if the user starts a touch in our area, let them change the action if (!mChangingActivity) { Vector3 viewportTouch = mCamera.ScreenToViewportPoint(new Vector3(MRGame.LastTouchPos.x, MRGame.LastTouchPos.y, mCamera.nearClipPlane)); if (viewportTouch.x < 0 || viewportTouch.y < 0 || viewportTouch.x > 1 || viewportTouch.y > 1) return; } mChangingActivity = true; } if (mChangingActivity) { if (MRGame.IsTouching) { // change screen space to world space Vector3 lastTouch = mCamera.ScreenToWorldPoint(new Vector3(MRGame.LastTouchPos.x, MRGame.LastTouchPos.y, mCamera.nearClipPlane)); Vector3 thisTouch = mCamera.ScreenToWorldPoint(new Vector3(MRGame.TouchPos.x, MRGame.TouchPos.y, mCamera.nearClipPlane)); mActivityStrip.transform.Translate(new Vector3(thisTouch.x - lastTouch.x, 0, 0)); if (mActivityStrip.transform.position.x < mMinActivityListPos) { Vector3 oldPos = mActivityStrip.transform.position; mActivityStrip.transform.position = new Vector3(mMinActivityListPos, oldPos.y, oldPos.z); } else if (mActivityStrip.transform.position.x > mMaxActivityListPos) { Vector3 oldPos = mActivityStrip.transform.position; mActivityStrip.transform.position = new Vector3(mMaxActivityListPos, oldPos.y, oldPos.z); } } else { mChangingActivity = false; // set the action based on the widget's current position UpdateActivityForWidget(); } } } public bool OnTouched(GameObject touchedObject) { return true; } public bool OnReleased(GameObject touchedObject) { return true; } public bool OnSingleTapped(GameObject touchedObject) { return true; } public bool OnDoubleTapped(GameObject touchedObject) { if (MRGame.TimeOfDay == MRGame.eTimeOfDay.Daylight) { if (!mActivity.Executed) { mActivity.Active = true; } } return true; } public bool OnTouchMove(GameObject touchedObject, float delta_x, float delta_y) { return true; } public bool OnTouchHeld(GameObject touchedObject) { return true; } public bool OnButtonActivate(GameObject touchedObject) { return true; } public bool OnPinchZoom(float pinchDelta) { return true; } // // Change our action for whichever icon is showing the most on screen. // private void UpdateActivityForWidget() { float activity = ((mActivityStripWidth / 2) - mActivityStrip.transform.position.x) / mActivityWidth; MRGame.eActivity activityType = (MRGame.eActivity)activity; if (Activity == null || Activity.Activity != activityType) { Activity = MRActivity.CreateActivity(activityType); } UpdateWidgetForActivity(); } // // Show the correct icon for our action // private void UpdateWidgetForActivity() { Vector3 oldPos = mActivityStrip.transform.position; mActivityStrip.transform.position = new Vector3((mActivityStripWidth / 2) - (((int)mActivity.Activity + 0.5f) * mActivityWidth), oldPos.y, oldPos.z); // adjust our position so we don't overlap another activity gameObject.transform.position = new Vector3(0, mListPosition * mBorderSize * 2.0f, 0); // adjust the camera for the list position Rect newPos = new Rect(); float parentOffset = 0; newPos.x = (parentOffset + MRGame.TheGame.InspectionArea.TabWidthPixels) / Screen.width; newPos.y = (MRGame.TheGame.InspectionArea.InspectionBoundsPixels.yMax - (MRGame.TheGame.InspectionArea.ActivityWidthPixels * mListPosition) - MRGame.TheGame.InspectionArea.ActivityWidthPixels) / Screen.height; newPos.width = MRGame.TheGame.InspectionArea.ActivityWidthPixels / Screen.width; newPos.height = MRGame.TheGame.InspectionArea.ActivityWidthPixels / Screen.height; mCamera.rect = newPos; // if we're not enabled, don't show the activity strip mActivityStrip.GetComponent<Renderer>().enabled = mIsEnabled; } #endregion #region Members private Camera mCamera; private GameObject mActivityStrip = null; private GameObject mBorder = null; private GameObject mCanceledBorder = null; private bool mVisible; private float mBorderSize; private float mActivityStripWidth; private float mActivityWidth; private float mMinActivityListPos; private float mMaxActivityListPos; private bool mChangingActivity = false; private bool mEditingActivity = false; private MRActivity mActivity; private MRClearingSelector mClearing; private int mListPosition; private bool mIsInteractive; private bool mIsEnabled; #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.Diagnostics; using System.IO.PortsTests; using System.Text; using System.Threading; using System.Threading.Tasks; using Legacy.Support; using Xunit; namespace System.IO.Ports.Tests { public class Read_byte_int_int : PortsTest { //The number of random bytes to receive for read method testing private const int numRndBytesToRead = 16; //The number of random bytes to receive for large input buffer testing private const int largeNumRndBytesToRead = 2048; //When we test Read and do not care about actually reading anything we must still //create an byte array to pass into the method the following is the size of the //byte array used in this situation private const int defaultByteArraySize = 1; private const int defaultByteOffset = 0; private const int defaultByteCount = 1; //The maximum buffer size when an exception occurs private const int maxBufferSizeForException = 255; //The maximum buffer size when an exception is not expected private const int maxBufferSize = 8; private enum ReadDataFromEnum { NonBuffered, Buffered, BufferedAndNonBuffered }; #region Test Cases [ConditionalFact(nameof(HasOneSerialPort))] public void Buffer_Null() { VerifyReadException(null, 0, 1, typeof(ArgumentNullException)); } [ConditionalFact(nameof(HasOneSerialPort))] public void Offset_NEG1() { VerifyReadException(new byte[defaultByteArraySize], -1, defaultByteCount, typeof(ArgumentOutOfRangeException)); } [ConditionalFact(nameof(HasOneSerialPort))] public void Offset_NEGRND() { Random rndGen = new Random(); VerifyReadException(new byte[defaultByteArraySize], rndGen.Next(int.MinValue, 0), defaultByteCount, typeof(ArgumentOutOfRangeException)); } [ConditionalFact(nameof(HasOneSerialPort))] public void Offset_MinInt() { VerifyReadException(new byte[defaultByteArraySize], int.MinValue, defaultByteCount, typeof(ArgumentOutOfRangeException)); } [ConditionalFact(nameof(HasOneSerialPort))] public void Count_NEG1() { VerifyReadException(new byte[defaultByteArraySize], defaultByteOffset, -1, typeof(ArgumentOutOfRangeException)); } [ConditionalFact(nameof(HasOneSerialPort))] public void Count_NEGRND() { Random rndGen = new Random(); VerifyReadException(new byte[defaultByteArraySize], defaultByteOffset, rndGen.Next(int.MinValue, 0), typeof(ArgumentOutOfRangeException)); } [ConditionalFact(nameof(HasOneSerialPort))] public void Count_MinInt() { VerifyReadException(new byte[defaultByteArraySize], defaultByteOffset, int.MinValue, typeof(ArgumentOutOfRangeException)); } [ConditionalFact(nameof(HasLoopbackOrNullModem))] public void OffsetCount_EQ_Length_Plus_1() { Random rndGen = new Random(); int bufferLength = rndGen.Next(1, maxBufferSizeForException); int offset = rndGen.Next(0, bufferLength); int count = bufferLength + 1 - offset; Type expectedException = typeof(ArgumentException); VerifyReadException(new byte[bufferLength], offset, count, expectedException); } [ConditionalFact(nameof(HasLoopbackOrNullModem))] public void OffsetCount_GT_Length() { Random rndGen = new Random(); int bufferLength = rndGen.Next(1, maxBufferSizeForException); int offset = rndGen.Next(0, bufferLength); int count = rndGen.Next(bufferLength + 1 - offset, int.MaxValue); Type expectedException = typeof(ArgumentException); VerifyReadException(new byte[bufferLength], offset, count, expectedException); } [ConditionalFact(nameof(HasLoopbackOrNullModem))] public void Offset_GT_Length() { Random rndGen = new Random(); int bufferLength = rndGen.Next(1, maxBufferSizeForException); int offset = rndGen.Next(bufferLength, int.MaxValue); int count = defaultByteCount; Type expectedException = typeof(ArgumentException); VerifyReadException(new byte[bufferLength], offset, count, expectedException); } [ConditionalFact(nameof(HasLoopbackOrNullModem))] public void Count_GT_Length() { Random rndGen = new Random(); int bufferLength = rndGen.Next(1, maxBufferSizeForException); int offset = defaultByteOffset; int count = rndGen.Next(bufferLength + 1, int.MaxValue); Type expectedException = typeof(ArgumentException); VerifyReadException(new byte[bufferLength], offset, count, expectedException); } [ConditionalFact(nameof(HasLoopbackOrNullModem))] public void OffsetCount_EQ_Length() { Random rndGen = new Random(); int bufferLength = rndGen.Next(1, maxBufferSize); int offset = rndGen.Next(0, bufferLength - 1); int count = bufferLength - offset; VerifyRead(new byte[bufferLength], offset, count); } [ConditionalFact(nameof(HasLoopbackOrNullModem))] public void Offset_EQ_Length_Minus_1() { Random rndGen = new Random(); int bufferLength = rndGen.Next(1, maxBufferSize); int offset = bufferLength - 1; int count = 1; VerifyRead(new byte[bufferLength], offset, count); } [ConditionalFact(nameof(HasLoopbackOrNullModem))] public void Count_EQ_Length() { Random rndGen = new Random(); int bufferLength = rndGen.Next(1, maxBufferSize); int offset = 0; int count = bufferLength; VerifyRead(new byte[bufferLength], offset, count); } [ConditionalFact(nameof(HasLoopbackOrNullModem))] public void SerialPort_ReadBufferedData() { int bufferLength = 32 + 8; int offset = 3; int count = 32; VerifyRead(new byte[bufferLength], offset, count, 32, ReadDataFromEnum.Buffered); } [ConditionalFact(nameof(HasLoopbackOrNullModem))] public void SerialPort_IterativeReadBufferedData() { int bufferLength = 8; int offset = 3; int count = 3; VerifyRead(new byte[bufferLength], offset, count, 32, ReadDataFromEnum.Buffered); } [ConditionalFact(nameof(HasLoopbackOrNullModem))] public void SerialPort_ReadBufferedAndNonBufferedData() { int bufferLength = 64 + 8; int offset = 3; int count = 64; VerifyRead(new byte[bufferLength], offset, count, 32, ReadDataFromEnum.BufferedAndNonBuffered); } [ConditionalFact(nameof(HasLoopbackOrNullModem))] public void SerialPort_IterativeReadBufferedAndNonBufferedData() { int bufferLength = 8; int offset = 3; int count = 3; VerifyRead(new byte[bufferLength], offset, count, 32, ReadDataFromEnum.BufferedAndNonBuffered); } [ConditionalFact(nameof(HasLoopbackOrNullModem))] public void GreedyRead() { using (SerialPort com1 = TCSupport.InitFirstSerialPort()) using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1)) { Random rndGen = new Random(); byte[] byteXmitBuffer = new byte[1024]; byte[] expectedBytes = new byte[byteXmitBuffer.Length + 4]; byte[] byteRcvBuffer; char utf32Char = (char)8169; byte[] utf32CharBytes = Encoding.UTF32.GetBytes(new[] { utf32Char }); int numBytesRead; Debug.WriteLine( "Verifying that Read(byte[], int, int) will read everything from internal buffer and drivers buffer"); for (int i = 0; i < utf32CharBytes.Length; i++) { expectedBytes[i] = utf32CharBytes[i]; } for (int i = 0; i < byteXmitBuffer.Length; i++) { byteXmitBuffer[i] = (byte)rndGen.Next(0, 256); expectedBytes[i + 4] = byteXmitBuffer[i]; } //Put the first byte of the utf32 encoder char in the last byte of this buffer //when we read this later the buffer will have to be resized byteXmitBuffer[byteXmitBuffer.Length - 1] = utf32CharBytes[0]; expectedBytes[byteXmitBuffer.Length + 4 - 1] = utf32CharBytes[0]; com1.Open(); if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback com2.Open(); com2.Write(byteXmitBuffer, 0, byteXmitBuffer.Length); TCSupport.WaitForReadBufferToLoad(com1, byteXmitBuffer.Length); //Read Every Byte except the last one. The last bye should be left in the last position of SerialPort's //internal buffer. When we try to read this char as UTF32 the buffer should have to be resized so //the other 3 bytes of the ut32 encoded char can be in the buffer com1.Read(new char[1023], 0, 1023); if (1 != com1.BytesToRead) { Fail("Err_9416sapz ExpectedByteToRead={0} actual={1}", 1, com1.BytesToRead); } com2.Write(utf32CharBytes, 1, 3); com2.Write(byteXmitBuffer, 0, byteXmitBuffer.Length); byteRcvBuffer = new byte[(int)(expectedBytes.Length * 1.5)]; TCSupport.WaitForReadBufferToLoad(com1, 4 + byteXmitBuffer.Length); if (expectedBytes.Length != (numBytesRead = com1.Read(byteRcvBuffer, 0, byteRcvBuffer.Length))) { Fail("Err_6481sfadw Expected read to read {0} chars actually read {1}", expectedBytes.Length, numBytesRead); } for (int i = 0; i < expectedBytes.Length; i++) { if (expectedBytes[i] != byteRcvBuffer[i]) { Fail("Err_70782apzh Expected to read {0} actually read {1} at {2}", (int)expectedBytes[i], (int)byteRcvBuffer[i], i); } } if (0 != com1.BytesToRead) { Fail("Err_78028asdf ExpectedByteToRead={0} actual={1}", 0, com1.BytesToRead); } } } [ConditionalFact(nameof(HasLoopbackOrNullModem))] public void LargeInputBuffer() { int bufferLength = largeNumRndBytesToRead; int offset = 0; int count = bufferLength; VerifyRead(new byte[bufferLength], offset, count, largeNumRndBytesToRead); } [ConditionalFact(nameof(HasLoopbackOrNullModem))] public void Read_DataReceivedBeforeTimeout() { using (SerialPort com1 = TCSupport.InitFirstSerialPort()) using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1)) { byte[] byteXmitBuffer = TCSupport.GetRandomBytes(512); byte[] byteRcvBuffer = new byte[byteXmitBuffer.Length]; ASyncRead asyncRead = new ASyncRead(com1, byteRcvBuffer, 0, byteRcvBuffer.Length); var asyncReadTask = new Task(asyncRead.Read); Debug.WriteLine( "Verifying that Read(byte[], int, int) will read characters that have been received after the call to Read was made"); com1.Encoding = Encoding.UTF8; com2.Encoding = Encoding.UTF8; com1.ReadTimeout = 20000; // 20 seconds com1.Open(); if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback com2.Open(); asyncReadTask.Start(); asyncRead.ReadStartedEvent.WaitOne(); //This only tells us that the thread has started to execute code in the method Thread.Sleep(2000); //We need to wait to guarentee that we are executing code in SerialPort com2.Write(byteXmitBuffer, 0, byteXmitBuffer.Length); asyncRead.ReadCompletedEvent.WaitOne(); if (null != asyncRead.Exception) { Fail("Err_04448ajhied Unexpected exception thrown from async read:\n{0}", asyncRead.Exception); } else if (asyncRead.Result < 1) { Fail("Err_0158ahei Expected Read to read at least one character {0}", asyncRead.Result); } else { Thread.Sleep(1000); //We need to wait for all of the bytes to be received int readResult = com1.Read(byteRcvBuffer, asyncRead.Result, byteRcvBuffer.Length - asyncRead.Result); if (asyncRead.Result + readResult != byteXmitBuffer.Length) { Fail("Err_051884ajoedo Expected Read to read {0} characters actually read {1}", byteXmitBuffer.Length - asyncRead.Result, readResult); } else { for (int i = 0; i < byteXmitBuffer.Length; ++i) { if (byteRcvBuffer[i] != byteXmitBuffer[i]) { Fail( "Err_05188ahed Characters differ at {0} expected:{1}({1:X}) actual:{2}({2:X}) asyncRead.Result={3}", i, byteXmitBuffer[i], byteRcvBuffer[i], asyncRead.Result); } } } } TCSupport.WaitForTaskCompletion(asyncReadTask); } } #endregion #region Verification for Test Cases private void VerifyReadException(byte[] buffer, int offset, int count, Type expectedException) { using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { int bufferLength = null == buffer ? 0 : buffer.Length; Debug.WriteLine("Verifying read method throws {0} buffer.Lenght={1}, offset={2}, count={3}", expectedException, bufferLength, offset, count); com.Open(); Assert.Throws(expectedException, () => com.Read(buffer, offset, count)); } } private void VerifyRead(byte[] buffer, int offset, int count) { VerifyRead(buffer, offset, count, numRndBytesToRead); } private void VerifyRead(byte[] buffer, int offset, int count, int numberOfBytesToRead) { VerifyRead(buffer, offset, count, numberOfBytesToRead, ReadDataFromEnum.NonBuffered); } private void VerifyRead(byte[] buffer, int offset, int count, int numberOfBytesToRead, ReadDataFromEnum readDataFrom) { using (SerialPort com1 = TCSupport.InitFirstSerialPort()) using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1)) { Random rndGen = new Random(); byte[] bytesToWrite = new byte[numberOfBytesToRead]; //Genrate random bytes for (int i = 0; i < bytesToWrite.Length; i++) { byte randByte = (byte)rndGen.Next(0, 256); bytesToWrite[i] = randByte; } //Genrate some random bytes in the buffer for (int i = 0; i < buffer.Length; i++) { byte randByte = (byte)rndGen.Next(0, 256); buffer[i] = randByte; } Debug.WriteLine("Verifying read method buffer.Lenght={0}, offset={1}, count={2} with {3} random chars", buffer.Length, offset, count, bytesToWrite.Length); com1.ReadTimeout = 500; com1.Open(); if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback com2.Open(); switch (readDataFrom) { case ReadDataFromEnum.NonBuffered: VerifyReadNonBuffered(com1, com2, bytesToWrite, buffer, offset, count); break; case ReadDataFromEnum.Buffered: VerifyReadBuffered(com1, com2, bytesToWrite, buffer, offset, count); break; case ReadDataFromEnum.BufferedAndNonBuffered: VerifyReadBufferedAndNonBuffered(com1, com2, bytesToWrite, buffer, offset, count); break; default: throw new ArgumentOutOfRangeException(nameof(readDataFrom), readDataFrom, null); } } } private void VerifyReadNonBuffered(SerialPort com1, SerialPort com2, byte[] bytesToWrite, byte[] rcvBuffer, int offset, int count) { VerifyBytesReadOnCom1FromCom2(com1, com2, bytesToWrite, rcvBuffer, offset, count); } private void VerifyReadBuffered(SerialPort com1, SerialPort com2, byte[] bytesToWrite, byte[] rcvBuffer, int offset, int count) { BufferData(com1, com2, bytesToWrite); PerformReadOnCom1FromCom2(com1, com2, bytesToWrite, rcvBuffer, offset, count); } private void VerifyReadBufferedAndNonBuffered(SerialPort com1, SerialPort com2, byte[] bytesToWrite, byte[] rcvBuffer, int offset, int count) { byte[] expectedBytes = new byte[(2 * bytesToWrite.Length)]; BufferData(com1, com2, bytesToWrite); Buffer.BlockCopy(bytesToWrite, 0, expectedBytes, 0, bytesToWrite.Length); Buffer.BlockCopy(bytesToWrite, 0, expectedBytes, bytesToWrite.Length, bytesToWrite.Length); VerifyBytesReadOnCom1FromCom2(com1, com2, bytesToWrite, expectedBytes, rcvBuffer, offset, count); } private void BufferData(SerialPort com1, SerialPort com2, byte[] bytesToWrite) { com2.Write(bytesToWrite, 0, 1); // Write one byte at the begining because we are going to read this to buffer the rest of the data com2.Write(bytesToWrite, 0, bytesToWrite.Length); while (com1.BytesToRead < bytesToWrite.Length) { Thread.Sleep(50); } com1.Read(new char[1], 0, 1); // This should put the rest of the bytes in SerialPorts own internal buffer Assert.Equal(bytesToWrite.Length, com1.BytesToRead); } private void VerifyBytesReadOnCom1FromCom2(SerialPort com1, SerialPort com2, byte[] bytesToWrite, byte[] rcvBuffer, int offset, int count) { VerifyBytesReadOnCom1FromCom2(com1, com2, bytesToWrite, bytesToWrite, rcvBuffer, offset, count); } private void VerifyBytesReadOnCom1FromCom2(SerialPort com1, SerialPort com2, byte[] bytesToWrite, byte[] expectedBytes, byte[] rcvBuffer, int offset, int count) { com2.Write(bytesToWrite, 0, bytesToWrite.Length); com1.ReadTimeout = 500; Thread.Sleep((int)(((bytesToWrite.Length * 10.0) / com1.BaudRate) * 1000) + 250); PerformReadOnCom1FromCom2(com1, com2, expectedBytes, rcvBuffer, offset, count); } private void PerformReadOnCom1FromCom2(SerialPort com1, SerialPort com2, byte[] expectedBytes, byte[] rcvBuffer, int offset, int count) { byte[] buffer = new byte[expectedBytes.Length]; int bytesRead, totalBytesRead; int bytesToRead; byte[] oldRcvBuffer = (byte[])rcvBuffer.Clone(); totalBytesRead = 0; bytesToRead = com1.BytesToRead; while (true) { try { bytesRead = com1.Read(rcvBuffer, offset, count); } catch (TimeoutException) { break; } //While their are more characters to be read if ((bytesToRead > bytesRead && count != bytesRead) || (bytesToRead <= bytesRead && bytesRead != bytesToRead)) { //If we have not read all of the characters that we should have Fail("ERROR!!!: Read did not return all of the characters that were in SerialPort buffer"); } if (expectedBytes.Length < totalBytesRead + bytesRead) { //If we have read in more characters then we expect Fail("ERROR!!!: We have received more characters then were sent {0}", totalBytesRead + bytesRead); } VerifyBuffer(rcvBuffer, oldRcvBuffer, offset, bytesRead); Array.Copy(rcvBuffer, offset, buffer, totalBytesRead, bytesRead); totalBytesRead += bytesRead; if (expectedBytes.Length - totalBytesRead != com1.BytesToRead) { Fail("ERROR!!!: Expected BytesToRead={0} actual={1}", expectedBytes.Length - totalBytesRead, com1.BytesToRead); } oldRcvBuffer = (byte[])rcvBuffer.Clone(); bytesToRead = com1.BytesToRead; } VerifyBuffer(rcvBuffer, oldRcvBuffer, 0, rcvBuffer.Length); //Compare the bytes that were written with the ones we read for (int i = 0; i < expectedBytes.Length; i++) { if (expectedBytes[i] != buffer[i]) { Fail("ERROR!!!: Expected to read {0} actual read {1} at {2}", expectedBytes[i], buffer[i], i); } } if (0 != com1.BytesToRead) { Fail("ERROR!!!: Expected BytesToRead=0 actual BytesToRead={0}", com1.BytesToRead); } if (com1.IsOpen) com1.Close(); if (com2.IsOpen) com2.Close(); } private void VerifyBuffer(byte[] actualBuffer, byte[] expectedBuffer, int offset, int count) { //Verify all character before the offset for (int i = 0; i < offset; i++) { if (actualBuffer[i] != expectedBuffer[i]) { Fail("Err_2038apzn!!!: Expected {0} in buffer at {1} actual {2}", (int)expectedBuffer[i], i, (int)actualBuffer[i]); } } //Verify all character after the offset + count for (int i = offset + count; i < actualBuffer.Length; i++) { if (actualBuffer[i] != expectedBuffer[i]) { Fail("Err_7025nbht!!!: Expected {0} in buffer at {1} actual {2}", (int)expectedBuffer[i], i, (int)actualBuffer[i]); } } } private class ASyncRead { private readonly SerialPort _com; private readonly byte[] _buffer; private readonly int _offset; private readonly int _count; private int _result; private readonly AutoResetEvent _readCompletedEvent; private readonly AutoResetEvent _readStartedEvent; private Exception _exception; public ASyncRead(SerialPort com, byte[] buffer, int offset, int count) { _com = com; _buffer = buffer; _offset = offset; _count = count; _result = -1; _readCompletedEvent = new AutoResetEvent(false); _readStartedEvent = new AutoResetEvent(false); _exception = null; } public void Read() { try { _readStartedEvent.Set(); _result = _com.Read(_buffer, _offset, _count); } catch (Exception e) { _exception = e; } finally { _readCompletedEvent.Set(); } } public AutoResetEvent ReadStartedEvent => _readStartedEvent; public AutoResetEvent ReadCompletedEvent => _readCompletedEvent; public int Result => _result; public Exception Exception => _exception; } #endregion } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Threading; using System.Collections.Generic; using System.Text; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.ScriptEngine.Shared; using OpenSim.Region.ScriptEngine.Shared.Api; using OpenSim.Region.ScriptEngine.Shared.ScriptBase; using OpenSim.Region.Framework.Scenes; using log4net; using LSL_Float = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLFloat; using LSL_Integer = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLInteger; using LSL_Key = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLString; using LSL_List = OpenSim.Region.ScriptEngine.Shared.LSL_Types.list; using LSL_Rotation = OpenSim.Region.ScriptEngine.Shared.LSL_Types.Quaternion; using LSL_String = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLString; using LSL_Vector = OpenSim.Region.ScriptEngine.Shared.LSL_Types.Vector3; namespace OpenSim.Region.ScriptEngine.Yengine { public partial class XMRInstance { /************************************************************************************\ * This module contains these externally useful methods: * * PostEvent() - queues an event to script and wakes script thread to process it * * RunOne() - runs script for a time slice or until it volunteers to give up cpu * * CallSEH() - runs in the microthread to call the event handler * \************************************************************************************/ /** * @brief This can be called in any thread (including the script thread itself) * to queue event to script for processing. */ public void PostEvent(EventParams evt) { ScriptEventCode evc = (ScriptEventCode)Enum.Parse(typeof(ScriptEventCode), evt.EventName); // Put event on end of event queue. bool startIt = false; bool wakeIt = false; lock(m_QueueLock) { bool construct = (m_IState == XMRInstState.CONSTRUCT); // Ignore event if we don't even have such an handler in any state. // We can't be state-specific here because state might be different // by the time this event is dequeued and delivered to the script. if(!construct && // make sure m_HaveEventHandlers is filled in ((uint)evc < (uint)m_HaveEventHandlers.Length) && !m_HaveEventHandlers[(int)evc]) // don't bother if we don't have such a handler in any state return; // Not running means we ignore any incoming events. // But queue if still constructing because m_Running is not yet valid. if(!m_Running && !construct) return; // Only so many of each event type allowed to queue. if((uint)evc < (uint)m_EventCounts.Length) { if(evc == ScriptEventCode.timer) { if(m_EventCounts[(int)evc] >= 1) return; } else if(m_EventCounts[(int)evc] >= MAXEVENTQUEUE) return; m_EventCounts[(int)evc]++; } // Put event on end of instance's event queue. LinkedListNode<EventParams> lln = new LinkedListNode<EventParams>(evt); switch(evc) { // These need to go first. The only time we manually // queue them is for the default state_entry() and we // need to make sure they go before any attach() events // so the heapLimit value gets properly initialized. case ScriptEventCode.state_entry: m_EventQueue.AddFirst(lln); break; // The attach event sneaks to the front of the queue. // This is needed for quantum limiting to work because // we want the attach(NULL_KEY) event to come in front // of all others so the m_DetachQuantum won't run out // before attach(NULL_KEY) is executed. case ScriptEventCode.attach: if(evt.Params[0].ToString() == UUID.Zero.ToString()) { LinkedListNode<EventParams> lln2 = null; for(lln2 = m_EventQueue.First; lln2 != null; lln2 = lln2.Next) { EventParams evt2 = lln2.Value; ScriptEventCode evc2 = (ScriptEventCode)Enum.Parse(typeof(ScriptEventCode), evt2.EventName); if((evc2 != ScriptEventCode.state_entry) && (evc2 != ScriptEventCode.attach)) break; } if(lln2 == null) m_EventQueue.AddLast(lln); else m_EventQueue.AddBefore(lln2, lln); // If we're detaching, limit the qantum. This will also // cause the script to self-suspend after running this // event m_DetachReady.Reset(); m_DetachQuantum = 100; } else m_EventQueue.AddLast(lln); break; // All others just go on end in the order queued. default: m_EventQueue.AddLast(lln); break; } // If instance is idle (ie, not running or waiting to run), // flag it to be on m_StartQueue as we are about to do so. // Flag it now before unlocking so another thread won't try // to do the same thing right now. // Dont' flag it if it's still suspended! if((m_IState == XMRInstState.IDLE) && !m_Suspended) { m_IState = XMRInstState.ONSTARTQ; startIt = true; } // If instance is sleeping (ie, possibly in xmrEventDequeue), // wake it up if event is in the mask. if((m_SleepUntil > DateTime.UtcNow) && !m_Suspended) { int evc1 = (int)evc; int evc2 = evc1 - 32; if((((uint)evc1 < (uint)32) && (((m_SleepEventMask1 >> evc1) & 1) != 0)) || (((uint)evc2 < (uint)32) && (((m_SleepEventMask2 >> evc2) & 1) != 0))) wakeIt = true; } } // If transitioned from IDLE->ONSTARTQ, actually go insert it // on m_StartQueue and give the RunScriptThread() a wake-up. if(startIt) m_Engine.QueueToStart(this); // Likewise, if the event mask triggered a wake, wake it up. if(wakeIt) { m_SleepUntil = DateTime.MinValue; m_Engine.WakeFromSleep(this); } } // This is called in the script thread to step script until it calls // CheckRun(). It returns what the instance's next state should be, // ONSLEEPQ, ONYIELDQ, SUSPENDED or FINISHED. public XMRInstState RunOne() { DateTime now = DateTime.UtcNow; m_SliceStart = Util.GetTimeStampMS(); // If script has called llSleep(), don't do any more until time is up. m_RunOnePhase = "check m_SleepUntil"; if(m_SleepUntil > now) { m_RunOnePhase = "return is sleeping"; return XMRInstState.ONSLEEPQ; } // Also, someone may have called Suspend(). m_RunOnePhase = "check m_SuspendCount"; if(m_SuspendCount > 0) { m_RunOnePhase = "return is suspended"; return XMRInstState.SUSPENDED; } // Make sure we aren't being migrated in or out and prevent that // whilst we are in here. If migration has it locked, don't call // back right away, delay a bit so we don't get in infinite loop. m_RunOnePhase = "lock m_RunLock"; if(!Monitor.TryEnter(m_RunLock)) { m_SleepUntil = now.AddMilliseconds(3); m_RunOnePhase = "return was locked"; return XMRInstState.ONSLEEPQ; } try { m_RunOnePhase = "check entry invariants"; CheckRunLockInvariants(true); Exception e = null; // Maybe it has been Disposed() if(m_Part == null) { m_RunOnePhase = "runone saw it disposed"; return XMRInstState.DISPOSED; } // Do some more of the last event if it didn't finish. if(this.eventCode != ScriptEventCode.None) { lock(m_QueueLock) { if(m_DetachQuantum > 0 && --m_DetachQuantum == 0) { m_Suspended = true; m_DetachReady.Set(); m_RunOnePhase = "detach quantum went zero"; CheckRunLockInvariants(true); return XMRInstState.FINISHED; } } m_RunOnePhase = "resume old event handler"; m_LastRanAt = now; m_InstEHSlice++; callMode = CallMode_NORMAL; e = ResumeEx(); } // Otherwise, maybe we can dequeue a new event and start // processing it. else { m_RunOnePhase = "lock event queue"; EventParams evt = null; ScriptEventCode evc = ScriptEventCode.None; lock(m_QueueLock) { // We can't get here unless the script has been resumed // after creation, then suspended again, and then had // an event posted to it. We just pretend there is no // event int he queue and let the normal mechanics // carry out the suspension. A Resume will handle the // restarting gracefully. This is taking the easy way // out and may be improved in the future. if(m_Suspended) { m_RunOnePhase = "m_Suspended is set"; CheckRunLockInvariants(true); return XMRInstState.FINISHED; } m_RunOnePhase = "dequeue event"; if(m_EventQueue.First != null) { evt = m_EventQueue.First.Value; if(m_DetachQuantum > 0) { evc = (ScriptEventCode)Enum.Parse(typeof(ScriptEventCode), evt.EventName); if(evc != ScriptEventCode.attach) { // This is the case where the attach event // has completed and another event is queued // Stop it from running and suspend m_Suspended = true; m_DetachReady.Set(); m_DetachQuantum = 0; m_RunOnePhase = "nothing to do #3"; CheckRunLockInvariants(true); return XMRInstState.FINISHED; } } m_EventQueue.RemoveFirst(); evc = (ScriptEventCode)Enum.Parse(typeof(ScriptEventCode), evt.EventName); if((int)evc >= 0) m_EventCounts[(int)evc]--; } // If there is no event to dequeue, don't run this script // until another event gets queued. if(evt == null) { if(m_DetachQuantum > 0) { // This will happen if the attach event has run // and exited with time slice left. m_Suspended = true; m_DetachReady.Set(); m_DetachQuantum = 0; } m_RunOnePhase = "nothing to do #4"; CheckRunLockInvariants(true); return XMRInstState.FINISHED; } } // Dequeued an event, so start it going until it either // finishes or it calls CheckRun(). m_RunOnePhase = "start event handler"; m_DetectParams = evt.DetectParams; m_LastRanAt = now; m_InstEHEvent++; e = StartEventHandler(evc, evt.Params); } m_RunOnePhase = "done running"; m_CPUTime += DateTime.UtcNow.Subtract(now).TotalMilliseconds; // Maybe it puqued. if(e != null) { m_RunOnePhase = "handling exception " + e.Message; HandleScriptException(e); m_RunOnePhase = "return had exception " + e.Message; CheckRunLockInvariants(true); return XMRInstState.FINISHED; } // If event handler completed, get rid of detect params. if(this.eventCode == ScriptEventCode.None) m_DetectParams = null; } finally { m_RunOnePhase += "; checking exit invariants and unlocking"; CheckRunLockInvariants(false); Monitor.Exit(m_RunLock); } // Cycle script through the yield queue and call it back asap. m_RunOnePhase = "last return"; return XMRInstState.ONYIELDQ; } /** * @brief Immediately after taking m_RunLock or just before releasing it, check invariants. */ private ScriptEventCode lastEventCode = ScriptEventCode.None; private bool lastActive = false; private string lastRunPhase = ""; public void CheckRunLockInvariants(bool throwIt) { // If not executing any event handler, there shouldn't be any saved stack frames. // If executing an event handler, there should be some saved stack frames. bool active = (stackFrames != null); ScriptEventCode ec = this.eventCode; if(((ec == ScriptEventCode.None) && active) || ((ec != ScriptEventCode.None) && !active)) { m_log.Error("CheckRunLockInvariants: script=" + m_DescName); m_log.Error("CheckRunLockInvariants: eventcode=" + ec.ToString() + ", active=" + active.ToString()); m_log.Error("CheckRunLockInvariants: m_RunOnePhase=" + m_RunOnePhase); m_log.Error("CheckRunLockInvariants: lastec=" + lastEventCode + ", lastAct=" + lastActive + ", lastPhase=" + lastRunPhase); if(throwIt) throw new Exception("CheckRunLockInvariants: eventcode=" + ec.ToString() + ", active=" + active.ToString()); } lastEventCode = ec; lastActive = active; lastRunPhase = m_RunOnePhase; } /* * Start event handler. * * Input: * newEventCode = code of event to be processed * newEhArgs = arguments for the event handler * * Caution: * It is up to the caller to make sure ehArgs[] is correct for * the particular event handler being called. The first thing * a script event handler method does is to unmarshall the args * from ehArgs[] and will throw an array bounds or cast exception * if it can't. */ private Exception StartEventHandler(ScriptEventCode newEventCode, object[] newEhArgs) { // We use this.eventCode == ScriptEventCode.None to indicate we are idle. // So trying to execute ScriptEventCode.None might make a mess. if(newEventCode == ScriptEventCode.None) return new Exception("Can't process ScriptEventCode.None"); // Silly to even try if there is no handler defined for this event. if(((int)newEventCode >= 0) && (m_ObjCode.scriptEventHandlerTable[this.stateCode, (int)newEventCode] == null)) return null; // The microthread shouldn't be processing any event code. // These are assert checks so we throw them directly as exceptions. if(this.eventCode != ScriptEventCode.None) throw new Exception("still processing event " + this.eventCode.ToString()); // Save eventCode so we know what event handler to run in the microthread. // And it also marks us busy so we can't be started again and this event lost. this.eventCode = newEventCode; this.ehArgs = newEhArgs; // This calls ScriptUThread.Main() directly, and returns when Main() [indirectly] // calls Suspend() or when Main() returns, whichever occurs first. // Setting stackFrames = null means run the event handler from the beginning // without doing any stack frame restores first. this.stackFrames = null; return StartEx(); } /** * @brief There was an exception whilst starting/running a script event handler. * Maybe we handle it directly or just print an error message. */ private void HandleScriptException(Exception e) { // The script threw some kind of exception that was not caught at // script level, so the script is no longer running an event handler. eventCode = ScriptEventCode.None; stackFrames = null; if (e is ScriptDeleteException) { // Script did something like llRemoveInventory(llGetScriptName()); // ... to delete itself from the object. m_SleepUntil = DateTime.MaxValue; Verbose("[YEngine]: script self-delete {0}", m_ItemID); m_Part.Inventory.RemoveInventoryItem(m_ItemID); } else if(e is ScriptDieException) { // Script did an llDie() m_RunOnePhase = "dying..."; m_SleepUntil = DateTime.MaxValue; m_Engine.World.DeleteSceneObject(m_Part.ParentGroup, false); } else if(e is ScriptResetException) { // Script did an llResetScript(). m_RunOnePhase = "resetting..."; ResetLocked("HandleScriptResetException"); } else { // Some general script error. SendErrorMessage(e); } } /** * @brief There was an exception running script event handler. * Display error message and disable script (in a way * that the script can be reset to be restarted). */ private void SendErrorMessage(Exception e) { StringBuilder msg = new StringBuilder(); msg.Append("[YEngine]: Exception while running "); msg.Append(m_ItemID); msg.Append('\n'); // Add exception message. string des = e.Message; des = (des == null) ? "" : (": " + des); msg.Append(e.GetType().Name + des + "\n"); // Tell script owner what to do. msg.Append("Prim: <"); msg.Append(m_Part.Name); msg.Append(">, Script: <"); msg.Append(m_Item.Name); msg.Append(">, Location: "); msg.Append(m_Engine.World.RegionInfo.RegionName); msg.Append(" <"); Vector3 pos = m_Part.AbsolutePosition; msg.Append((int)Math.Floor(pos.X)); msg.Append(','); msg.Append((int)Math.Floor(pos.Y)); msg.Append(','); msg.Append((int)Math.Floor(pos.Z)); msg.Append(">\nScript must be Reset to re-enable.\n"); // Display full exception message in log. m_log.Info(msg.ToString() + XMRExceptionStackString(e), e); // Give script owner the stack dump. msg.Append(XMRExceptionStackString(e)); // Send error message to owner. // Suppress internal code stack trace lines. string msgst = msg.ToString(); if(!msgst.EndsWith("\n")) msgst += '\n'; int j = 0; StringBuilder imstr = new StringBuilder(); for(int i = 0; (i = msgst.IndexOf('\n', i)) >= 0; j = ++i) { string line = msgst.Substring(j, i - j); if(line.StartsWith("at ")) { if(line.StartsWith("at (wrapper")) continue; // at (wrapper ... int k = line.LastIndexOf(".cs:"); // ... .cs:linenumber if(Int32.TryParse(line.Substring(k + 4), out k)) continue; } this.llOwnerSay(line); imstr.Append(line); imstr.Append('\n'); } // Send as instant message in case user not online. // Code modelled from llInstantMessage(). IMessageTransferModule transferModule = m_Engine.World.RequestModuleInterface<IMessageTransferModule>(); if(transferModule != null) { UUID friendTransactionID = UUID.Random(); GridInstantMessage gim = new GridInstantMessage(); gim.fromAgentID = new Guid(m_Part.UUID.ToString()); gim.toAgentID = new Guid(m_Part.OwnerID.ToString()); gim.imSessionID = new Guid(friendTransactionID.ToString()); gim.timestamp = (uint)Util.UnixTimeSinceEpoch(); gim.message = imstr.ToString(); gim.dialog = (byte)19; // messgage from script gim.fromGroup = false; gim.offline = (byte)0; gim.ParentEstateID = 0; gim.Position = pos; gim.RegionID = m_Engine.World.RegionInfo.RegionID.Guid; gim.binaryBucket = Util.StringToBytes256( "{0}/{1}/{2}/{3}", m_Engine.World.RegionInfo.RegionName, (int)Math.Floor(pos.X), (int)Math.Floor(pos.Y), (int)Math.Floor(pos.Z)); transferModule.SendInstantMessage(gim, delegate (bool success) { }); } // Say script is sleeping for a very long time. // Reset() is able to cancel this sleeping. m_SleepUntil = DateTime.MaxValue; } /** * @brief The user clicked the Reset Script button. * We want to reset the script to a never-has-ever-run-before state. */ public void Reset() { checkstate: XMRInstState iState = m_IState; switch(iState) { // If it's really being constructed now, that's about as reset as we get. case XMRInstState.CONSTRUCT: return; // If it's idle, that means it is ready to receive a new event. // So we lock the event queue to prevent another thread from taking // it out of idle, verify that it is still in idle then transition // it to resetting so no other thread will touch it. case XMRInstState.IDLE: lock(m_QueueLock) { if(m_IState == XMRInstState.IDLE) { m_IState = XMRInstState.RESETTING; break; } } goto checkstate; // If it's on the start queue, that means it is about to dequeue an // event and start processing it. So we lock the start queue so it // can't be started and transition it to resetting so no other thread // will touch it. case XMRInstState.ONSTARTQ: lock(m_Engine.m_StartQueue) { if(m_IState == XMRInstState.ONSTARTQ) { m_Engine.m_StartQueue.Remove(this); m_IState = XMRInstState.RESETTING; break; } } goto checkstate; // If it's running, tell CheckRun() to suspend the thread then go back // to see what it got transitioned to. case XMRInstState.RUNNING: suspendOnCheckRunHold = true; lock(m_QueueLock) { } goto checkstate; // If it's sleeping, remove it from sleep queue and transition it to // resetting so no other thread will touch it. case XMRInstState.ONSLEEPQ: lock(m_Engine.m_SleepQueue) { if(m_IState == XMRInstState.ONSLEEPQ) { m_Engine.m_SleepQueue.Remove(this); m_IState = XMRInstState.RESETTING; break; } } goto checkstate; // It was just removed from the sleep queue and is about to be put // on the yield queue (ie, is being woken up). // Let that thread complete transition and try again. case XMRInstState.REMDFROMSLPQ: Sleep(10); goto checkstate; // If it's yielding, remove it from yield queue and transition it to // resetting so no other thread will touch it. case XMRInstState.ONYIELDQ: lock(m_Engine.m_YieldQueue) { if(m_IState == XMRInstState.ONYIELDQ) { m_Engine.m_YieldQueue.Remove(this); m_IState = XMRInstState.RESETTING; break; } } goto checkstate; // If it just finished running something, let that thread transition it // to its next state then check again. case XMRInstState.FINISHED: Sleep(10); goto checkstate; // If it's disposed, that's about as reset as it gets. case XMRInstState.DISPOSED: return; // Some other thread is already resetting it, let it finish. case XMRInstState.RESETTING: return; default: throw new Exception("bad state"); } // This thread transitioned the instance to RESETTING so reset it. lock(m_RunLock) { CheckRunLockInvariants(true); // No other thread should have transitioned it from RESETTING. if(m_IState != XMRInstState.RESETTING) throw new Exception("bad state"); // Mark it idle now so it can get queued to process new stuff. m_IState = XMRInstState.IDLE; // Reset everything and queue up default's start_entry() event. ClearQueue(); ResetLocked("external Reset"); CheckRunLockInvariants(true); } } private void ClearQueueExceptLinkMessages() { lock(m_QueueLock) { EventParams[] linkMessages = new EventParams[m_EventQueue.Count]; int n = 0; foreach(EventParams evt2 in m_EventQueue) { if(evt2.EventName == "link_message") linkMessages[n++] = evt2; } m_EventQueue.Clear(); for(int i = m_EventCounts.Length; --i >= 0;) m_EventCounts[i] = 0; for(int i = 0; i < n; i++) m_EventQueue.AddLast(linkMessages[i]); m_EventCounts[(int)ScriptEventCode.link_message] = n; } } private void ClearQueue() { lock(m_QueueLock) { m_EventQueue.Clear(); // no events queued for(int i = m_EventCounts.Length; --i >= 0;) m_EventCounts[i] = 0; } } /** * @brief The script called llResetScript() while it was running and * has suspended. We want to reset the script to a never-has- * ever-run-before state. * * Caller must have m_RunLock locked so we know script isn't * running. */ private void ResetLocked(string from) { m_RunOnePhase = "ResetLocked: releasing controls"; ReleaseControls(); m_RunOnePhase = "ResetLocked: removing script"; m_Part.Inventory.GetInventoryItem(m_ItemID).PermsMask = 0; m_Part.Inventory.GetInventoryItem(m_ItemID).PermsGranter = UUID.Zero; IUrlModule urlModule = m_Engine.World.RequestModuleInterface<IUrlModule>(); if(urlModule != null) urlModule.ScriptRemoved(m_ItemID); AsyncCommandManager.RemoveScript(m_Engine, m_LocalID, m_ItemID); m_RunOnePhase = "ResetLocked: clearing current event"; this.eventCode = ScriptEventCode.None; // not processing an event m_DetectParams = null; // not processing an event m_SleepUntil = DateTime.MinValue; // not doing llSleep() m_ResetCount++; // has been reset once more // Tell next call to 'default state_entry()' to reset all global // vars to their initial values. doGblInit = true; // Throw away all its stack frames. // If the script is resetting itself, there shouldn't be any stack frames. // If the script is being reset by something else, we throw them away cuz we want to start from the beginning of an event handler. stackFrames = null; // Set script to 'default' state and queue call to its // 'state_entry()' event handler. m_RunOnePhase = "ResetLocked: posting default:state_entry() event"; stateCode = 0; m_Part.SetScriptEvents(m_ItemID, GetStateEventFlags(0)); PostEvent(new EventParams("state_entry", zeroObjectArray, zeroDetectParams)); // Tell CheckRun() to let script run. suspendOnCheckRunHold = false; suspendOnCheckRunTemp = false; m_RunOnePhase = "ResetLocked: reset complete"; } private void ReleaseControls() { if(m_Part != null) { bool found; int permsMask; UUID permsGranter; try { permsGranter = m_Part.TaskInventory[m_ItemID].PermsGranter; permsMask = m_Part.TaskInventory[m_ItemID].PermsMask; found = true; } catch { permsGranter = UUID.Zero; permsMask = 0; found = false; } if(found && ((permsMask & ScriptBaseClass.PERMISSION_TAKE_CONTROLS) != 0)) { ScenePresence presence = m_Engine.World.GetScenePresence(permsGranter); if(presence != null) presence.UnRegisterControlEventsToScript(m_LocalID, m_ItemID); } } } /** * @brief The script code should call this routine whenever it is * convenient to perform a migation or switch microthreads. */ public override void CheckRunWork() { if(!suspendOnCheckRunHold && !suspendOnCheckRunTemp) { if(Util.GetTimeStampMS() - m_SliceStart < 60.0) return; suspendOnCheckRunTemp = true; } m_CheckRunPhase = "entered"; // Stay stuck in this loop as long as something wants us suspended. while(suspendOnCheckRunHold || suspendOnCheckRunTemp) { m_CheckRunPhase = "top of while"; suspendOnCheckRunTemp = false; switch(this.callMode) { // Now we are ready to suspend or resume. case CallMode_NORMAL: m_CheckRunPhase = "suspending"; callMode = XMRInstance.CallMode_SAVE; stackFrames = null; throw new StackHibernateException(); // does not return // We get here when the script state has been read in by MigrateInEventHandler(). // Since the stack is completely restored at this point, any subsequent calls // within the functions should do their normal processing instead of trying to // restore their state. // the stack has been restored as a result of calling ResumeEx() // tell script code to process calls normally case CallMode_RESTORE: this.callMode = CallMode_NORMAL; break; default: throw new Exception("callMode=" + callMode); } m_CheckRunPhase = "resumed"; } m_CheckRunPhase = "returning"; // Upon return from CheckRun() it should always be the case that the script is // going to process calls normally, neither saving nor restoring stack frame state. if(callMode != CallMode_NORMAL) throw new Exception("bad callMode " + callMode); } /** * @brief Allow script to dequeue events. */ public void ResumeIt() { lock(m_QueueLock) { m_Suspended = false; if((m_EventQueue != null) && (m_EventQueue.First != null) && (m_IState == XMRInstState.IDLE)) { m_IState = XMRInstState.ONSTARTQ; m_Engine.QueueToStart(this); } m_HasRun = true; } } /** * @brief Block script from dequeuing events. */ public void SuspendIt() { lock(m_QueueLock) { m_Suspended = true; } } } /** * @brief Thrown by CheckRun() to unwind the script stack, capturing frames to * instance.stackFrames as it unwinds. We don't want scripts to be able * to intercept this exception as it would block the stack capture * functionality. */ public class StackCaptureException: Exception, IXMRUncatchable { } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Diagnostics.Contracts; using System.IO; using System.Net.Http.Headers; using System.Threading; using System.Threading.Tasks; namespace System.Net.Http { public class HttpClient : HttpMessageInvoker { #region Fields private static readonly TimeSpan s_defaultTimeout = TimeSpan.FromSeconds(100); private static readonly TimeSpan s_maxTimeout = TimeSpan.FromMilliseconds(int.MaxValue); private static readonly TimeSpan s_infiniteTimeout = Threading.Timeout.InfiniteTimeSpan; private const HttpCompletionOption defaultCompletionOption = HttpCompletionOption.ResponseContentRead; private volatile bool _operationStarted; private volatile bool _disposed; private CancellationTokenSource _pendingRequestsCts; private HttpRequestHeaders _defaultRequestHeaders; private Uri _baseAddress; private TimeSpan _timeout; private long _maxResponseContentBufferSize; #endregion Fields #region Properties public HttpRequestHeaders DefaultRequestHeaders { get { if (_defaultRequestHeaders == null) { _defaultRequestHeaders = new HttpRequestHeaders(); } return _defaultRequestHeaders; } } public Uri BaseAddress { get { return _baseAddress; } set { CheckBaseAddress(value, "value"); CheckDisposedOrStarted(); if (HttpEventSource.Log.IsEnabled()) HttpEventSource.UriBaseAddress(this, _baseAddress.ToString()); _baseAddress = value; } } public TimeSpan Timeout { get { return _timeout; } set { if (value != s_infiniteTimeout && (value <= TimeSpan.Zero || value > s_maxTimeout)) { throw new ArgumentOutOfRangeException(nameof(value)); } CheckDisposedOrStarted(); _timeout = value; } } public long MaxResponseContentBufferSize { get { return _maxResponseContentBufferSize; } set { if (value <= 0) { throw new ArgumentOutOfRangeException(nameof(value)); } if (value > HttpContent.MaxBufferSize) { throw new ArgumentOutOfRangeException(nameof(value), value, string.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_content_buffersize_limit, HttpContent.MaxBufferSize)); } CheckDisposedOrStarted(); _maxResponseContentBufferSize = value; } } #endregion Properties #region Constructors public HttpClient() : this(new HttpClientHandler()) { } public HttpClient(HttpMessageHandler handler) : this(handler, true) { } public HttpClient(HttpMessageHandler handler, bool disposeHandler) : base(handler, disposeHandler) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(NetEventSource.ComponentType.Http, this, ".ctor", handler); _timeout = s_defaultTimeout; _maxResponseContentBufferSize = HttpContent.MaxBufferSize; _pendingRequestsCts = new CancellationTokenSource(); if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(NetEventSource.ComponentType.Http, this, ".ctor", null); } #endregion Constructors #region Public Send #region Simple Get Overloads public Task<string> GetStringAsync(string requestUri) { return GetStringAsync(CreateUri(requestUri)); } public Task<string> GetStringAsync(Uri requestUri) { return GetContentAsync(requestUri, HttpCompletionOption.ResponseContentRead, string.Empty, content => content.ReadAsStringAsync()); } public Task<byte[]> GetByteArrayAsync(string requestUri) { return GetByteArrayAsync(CreateUri(requestUri)); } public Task<byte[]> GetByteArrayAsync(Uri requestUri) { return GetContentAsync(requestUri, HttpCompletionOption.ResponseContentRead, Array.Empty<byte>(), content => content.ReadAsByteArrayAsync()); } // Unbuffered by default public Task<Stream> GetStreamAsync(string requestUri) { return GetStreamAsync(CreateUri(requestUri)); } // Unbuffered by default public Task<Stream> GetStreamAsync(Uri requestUri) { return GetContentAsync(requestUri, HttpCompletionOption.ResponseHeadersRead, Stream.Null, content => content.ReadAsStreamAsync()); } private Task<T> GetContentAsync<T>(Uri requestUri, HttpCompletionOption completionOption, T defaultValue, Func<HttpContent, Task<T>> readAs) { TaskCompletionSource<T> tcs = new TaskCompletionSource<T>(); GetAsync(requestUri, completionOption).ContinueWithStandard(requestTask => { if (HandleRequestFaultsAndCancelation(requestTask, tcs)) { return; } HttpResponseMessage response = requestTask.Result; if (response.Content == null) { tcs.TrySetResult(defaultValue); return; } try { readAs(response.Content).ContinueWithStandard(contentTask => { if (!HttpUtilities.HandleFaultsAndCancelation(contentTask, tcs)) { tcs.TrySetResult(contentTask.Result); } }); } catch (Exception ex) { tcs.TrySetException(ex); } }); return tcs.Task; } #endregion Simple Get Overloads #region REST Send Overloads public Task<HttpResponseMessage> GetAsync(string requestUri) { return GetAsync(CreateUri(requestUri)); } public Task<HttpResponseMessage> GetAsync(Uri requestUri) { return GetAsync(requestUri, defaultCompletionOption); } public Task<HttpResponseMessage> GetAsync(string requestUri, HttpCompletionOption completionOption) { return GetAsync(CreateUri(requestUri), completionOption); } public Task<HttpResponseMessage> GetAsync(Uri requestUri, HttpCompletionOption completionOption) { return GetAsync(requestUri, completionOption, CancellationToken.None); } public Task<HttpResponseMessage> GetAsync(string requestUri, CancellationToken cancellationToken) { return GetAsync(CreateUri(requestUri), cancellationToken); } public Task<HttpResponseMessage> GetAsync(Uri requestUri, CancellationToken cancellationToken) { return GetAsync(requestUri, defaultCompletionOption, cancellationToken); } public Task<HttpResponseMessage> GetAsync(string requestUri, HttpCompletionOption completionOption, CancellationToken cancellationToken) { return GetAsync(CreateUri(requestUri), completionOption, cancellationToken); } public Task<HttpResponseMessage> GetAsync(Uri requestUri, HttpCompletionOption completionOption, CancellationToken cancellationToken) { return SendAsync(new HttpRequestMessage(HttpMethod.Get, requestUri), completionOption, cancellationToken); } public Task<HttpResponseMessage> PostAsync(string requestUri, HttpContent content) { return PostAsync(CreateUri(requestUri), content); } public Task<HttpResponseMessage> PostAsync(Uri requestUri, HttpContent content) { return PostAsync(requestUri, content, CancellationToken.None); } public Task<HttpResponseMessage> PostAsync(string requestUri, HttpContent content, CancellationToken cancellationToken) { return PostAsync(CreateUri(requestUri), content, cancellationToken); } public Task<HttpResponseMessage> PostAsync(Uri requestUri, HttpContent content, CancellationToken cancellationToken) { HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, requestUri); request.Content = content; return SendAsync(request, cancellationToken); } public Task<HttpResponseMessage> PutAsync(string requestUri, HttpContent content) { return PutAsync(CreateUri(requestUri), content); } public Task<HttpResponseMessage> PutAsync(Uri requestUri, HttpContent content) { return PutAsync(requestUri, content, CancellationToken.None); } public Task<HttpResponseMessage> PutAsync(string requestUri, HttpContent content, CancellationToken cancellationToken) { return PutAsync(CreateUri(requestUri), content, cancellationToken); } public Task<HttpResponseMessage> PutAsync(Uri requestUri, HttpContent content, CancellationToken cancellationToken) { HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Put, requestUri); request.Content = content; return SendAsync(request, cancellationToken); } public Task<HttpResponseMessage> DeleteAsync(string requestUri) { return DeleteAsync(CreateUri(requestUri)); } public Task<HttpResponseMessage> DeleteAsync(Uri requestUri) { return DeleteAsync(requestUri, CancellationToken.None); } public Task<HttpResponseMessage> DeleteAsync(string requestUri, CancellationToken cancellationToken) { return DeleteAsync(CreateUri(requestUri), cancellationToken); } public Task<HttpResponseMessage> DeleteAsync(Uri requestUri, CancellationToken cancellationToken) { return SendAsync(new HttpRequestMessage(HttpMethod.Delete, requestUri), cancellationToken); } #endregion REST Send Overloads #region Advanced Send Overloads public Task<HttpResponseMessage> SendAsync(HttpRequestMessage request) { return SendAsync(request, defaultCompletionOption, CancellationToken.None); } public override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { return SendAsync(request, defaultCompletionOption, cancellationToken); } public Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, HttpCompletionOption completionOption) { return SendAsync(request, completionOption, CancellationToken.None); } public Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, HttpCompletionOption completionOption, CancellationToken cancellationToken) { if (request == null) { throw new ArgumentNullException(nameof(request)); } CheckDisposed(); CheckRequestMessage(request); SetOperationStarted(); PrepareRequestMessage(request); // PrepareRequestMessage will resolve the request address against the base address. CancellationTokenSource linkedCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, _pendingRequestsCts.Token); SetTimeout(linkedCts); TaskCompletionSource<HttpResponseMessage> tcs = new TaskCompletionSource<HttpResponseMessage>(); base.SendAsync(request, linkedCts.Token).ContinueWithStandard(task => { try { // The request is completed. Dispose the request content. DisposeRequestContent(request); if (task.IsFaulted) { SetTaskFaulted(request, linkedCts, tcs, task.Exception.GetBaseException()); return; } if (task.IsCanceled) { SetTaskCanceled(request, linkedCts, tcs); return; } HttpResponseMessage response = task.Result; if (response == null) { SetTaskFaulted(request, linkedCts, tcs, new InvalidOperationException(SR.net_http_handler_noresponse)); return; } // If we don't have a response content, just return the response message. if ((response.Content == null) || (completionOption == HttpCompletionOption.ResponseHeadersRead)) { SetTaskCompleted(request, linkedCts, tcs, response); return; } Debug.Assert(completionOption == HttpCompletionOption.ResponseContentRead, "Unknown completion option."); // We have an assigned content. Start loading it into a buffer and return response message once // the whole content is buffered. StartContentBuffering(request, linkedCts, tcs, response); } catch (Exception e) { // Make sure we catch any exception, otherwise the task will catch it and throw in the finalizer. if (NetEventSource.Log.IsEnabled()) NetEventSource.Exception(NetEventSource.ComponentType.Http, this, "SendAsync", e); tcs.TrySetException(e); } }); return tcs.Task; } public void CancelPendingRequests() { CheckDisposed(); if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(NetEventSource.ComponentType.Http, this, "CancelPendingRequests", ""); // With every request we link this cancellation token source. CancellationTokenSource currentCts = Interlocked.Exchange(ref _pendingRequestsCts, new CancellationTokenSource()); currentCts.Cancel(); currentCts.Dispose(); if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(NetEventSource.ComponentType.Http, this, "CancelPendingRequests", ""); } #endregion Advanced Send Overloads #endregion Public Send #region IDisposable Members protected override void Dispose(bool disposing) { if (disposing && !_disposed) { _disposed = true; // Cancel all pending requests (if any). Note that we don't call CancelPendingRequests() but cancel // the CTS directly. The reason is that CancelPendingRequests() would cancel the current CTS and create // a new CTS. We don't want a new CTS in this case. _pendingRequestsCts.Cancel(); _pendingRequestsCts.Dispose(); } base.Dispose(disposing); } #endregion #region Private Helpers private void DisposeRequestContent(HttpRequestMessage request) { Contract.Requires(request != null); // When a request completes, HttpClient disposes the request content so the user doesn't have to. This also // ensures that a HttpContent object is only sent once using HttpClient (similar to HttpRequestMessages // that can also be sent only once). HttpContent content = request.Content; if (content != null) { content.Dispose(); } } private void StartContentBuffering(HttpRequestMessage request, CancellationTokenSource cancellationTokenSource, TaskCompletionSource<HttpResponseMessage> tcs, HttpResponseMessage response) { response.Content.LoadIntoBufferAsync(_maxResponseContentBufferSize).ContinueWithStandard(contentTask => { try { // Make sure to dispose the CTS _before_ setting TaskCompletionSource. Otherwise the task will be // completed and the user may dispose the user CTS on the continuation task leading to a race cond. bool isCancellationRequested = cancellationTokenSource.Token.IsCancellationRequested; // contentTask.Exception is always != null if IsFaulted is true. However, we need to access the // Exception property, otherwise the Task considers the excpetion as "unhandled" and will throw in // its finalizer. if (contentTask.IsFaulted) { response.Dispose(); // If the cancellation token was canceled, we consider the exception to be caused by the // cancellation (e.g. WebException when reading from canceled response stream). if (isCancellationRequested && (contentTask.Exception.GetBaseException() is HttpRequestException)) { SetTaskCanceled(request, cancellationTokenSource, tcs); } else { SetTaskFaulted(request, cancellationTokenSource, tcs, contentTask.Exception.GetBaseException()); } return; } if (contentTask.IsCanceled) { response.Dispose(); SetTaskCanceled(request, cancellationTokenSource, tcs); return; } // When buffering content is completed, set the Task as completed. SetTaskCompleted(request, cancellationTokenSource, tcs, response); } catch (Exception e) { // Make sure we catch any exception, otherwise the task will catch it and throw in the finalizer. response.Dispose(); tcs.TrySetException(e); if (NetEventSource.Log.IsEnabled()) NetEventSource.Exception(NetEventSource.ComponentType.Http, this, "SendAsync", e); } }); } private void SetOperationStarted() { // This method flags the HttpClient instances as "active". I.e. we executed at least one request (or are // in the process of doing so). This information is used to lock-down all property setters. Once a // Send/SendAsync operation started, no property can be changed. if (!_operationStarted) { _operationStarted = true; } } private void CheckDisposedOrStarted() { CheckDisposed(); if (_operationStarted) { throw new InvalidOperationException(SR.net_http_operation_started); } } private void CheckDisposed() { if (_disposed) { throw new ObjectDisposedException(GetType().ToString()); } } private static void CheckRequestMessage(HttpRequestMessage request) { if (!request.MarkAsSent()) { throw new InvalidOperationException(SR.net_http_client_request_already_sent); } } private void PrepareRequestMessage(HttpRequestMessage request) { Uri requestUri = null; if ((request.RequestUri == null) && (_baseAddress == null)) { throw new InvalidOperationException(SR.net_http_client_invalid_requesturi); } if (request.RequestUri == null) { requestUri = _baseAddress; } else { // If the request Uri is an absolute Uri, just use it. Otherwise try to combine it with the base Uri. if (!request.RequestUri.IsAbsoluteUri) { if (_baseAddress == null) { throw new InvalidOperationException(SR.net_http_client_invalid_requesturi); } else { requestUri = new Uri(_baseAddress, request.RequestUri); } } } // We modified the original request Uri. Assign the new Uri to the request message. if (requestUri != null) { request.RequestUri = requestUri; } // Add default headers if (_defaultRequestHeaders != null) { request.Headers.AddHeaders(_defaultRequestHeaders); } } private static void CheckBaseAddress(Uri baseAddress, string parameterName) { if (baseAddress == null) { return; // It's OK to not have a base address specified. } if (!baseAddress.IsAbsoluteUri) { throw new ArgumentException(SR.net_http_client_absolute_baseaddress_required, parameterName); } if (!HttpUtilities.IsHttpUri(baseAddress)) { throw new ArgumentException(SR.net_http_client_http_baseaddress_required, parameterName); } } private void SetTaskFaulted(HttpRequestMessage request, CancellationTokenSource cancellationTokenSource, TaskCompletionSource<HttpResponseMessage> tcs, Exception e) { LogSendError(request, cancellationTokenSource, "SendAsync", e); tcs.TrySetException(e); cancellationTokenSource.Dispose(); } private void SetTaskCanceled(HttpRequestMessage request, CancellationTokenSource cancellationTokenSource, TaskCompletionSource<HttpResponseMessage> tcs) { LogSendError(request, cancellationTokenSource, "SendAsync", null); tcs.TrySetCanceled(cancellationTokenSource.Token); cancellationTokenSource.Dispose(); } private void SetTaskCompleted(HttpRequestMessage request, CancellationTokenSource cancellationTokenSource, TaskCompletionSource<HttpResponseMessage> tcs, HttpResponseMessage response) { if (HttpEventSource.Log.IsEnabled()) HttpEventSource.ClientSendCompleted(this, response, request); tcs.TrySetResult(response); cancellationTokenSource.Dispose(); } private void SetTimeout(CancellationTokenSource cancellationTokenSource) { Contract.Requires(cancellationTokenSource != null); if (_timeout != s_infiniteTimeout) { cancellationTokenSource.CancelAfter(_timeout); } } private void LogSendError(HttpRequestMessage request, CancellationTokenSource cancellationTokenSource, string method, Exception e) { Contract.Requires(request != null); if (cancellationTokenSource.IsCancellationRequested) { if (NetEventSource.Log.IsEnabled()) NetEventSource.PrintError(NetEventSource.ComponentType.Http, this, method, string.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_client_send_canceled, LoggingHash.GetObjectLogHash(request))); } else { Debug.Assert(e != null); if (NetEventSource.Log.IsEnabled()) NetEventSource.PrintError(NetEventSource.ComponentType.Http, this, method, string.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_client_send_error, LoggingHash.GetObjectLogHash(request), e)); } } private Uri CreateUri(String uri) { if (string.IsNullOrEmpty(uri)) { return null; } return new Uri(uri, UriKind.RelativeOrAbsolute); } // Returns true if the task was faulted or canceled and sets tcs accordingly. Non-success status codes count as // faults in cases where the HttpResponseMessage object will not be returned to the developer. private static bool HandleRequestFaultsAndCancelation<T>(Task<HttpResponseMessage> task, TaskCompletionSource<T> tcs) { if (HttpUtilities.HandleFaultsAndCancelation(task, tcs)) { return true; } HttpResponseMessage response = task.Result; if (!response.IsSuccessStatusCode) { if (response.Content != null) { response.Content.Dispose(); } tcs.TrySetException(new HttpRequestException( string.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_message_not_success_statuscode, (int)response.StatusCode, response.ReasonPhrase))); return true; } return false; } #endregion Private Helpers } }
using System; using System.Text; using System.Data; using System.Data.SqlClient; using System.Data.Common; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Xml; using System.Xml.Serialization; using SubSonic; using SubSonic.Utilities; // <auto-generated /> namespace SAEON.Observations.Data { /// <summary> /// Strongly-typed collection for the ModuleX class. /// </summary> [Serializable] public partial class ModuleXCollection : ActiveList<ModuleX, ModuleXCollection> { public ModuleXCollection() {} /// <summary> /// Filters an existing collection based on the set criteria. This is an in-memory filter /// Thanks to developingchris for this! /// </summary> /// <returns>ModuleXCollection</returns> public ModuleXCollection Filter() { for (int i = this.Count - 1; i > -1; i--) { ModuleX o = this[i]; foreach (SubSonic.Where w in this.wheres) { bool remove = false; System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName); if (pi.CanRead) { object val = pi.GetValue(o, null); switch (w.Comparison) { case SubSonic.Comparison.Equals: if (!val.Equals(w.ParameterValue)) { remove = true; } break; } } if (remove) { this.Remove(o); break; } } } return this; } } /// <summary> /// This is an ActiveRecord class which wraps the Module table. /// </summary> [Serializable] public partial class ModuleX : ActiveRecord<ModuleX>, IActiveRecord { #region .ctors and Default Settings public ModuleX() { SetSQLProps(); InitSetDefaults(); MarkNew(); } private void InitSetDefaults() { SetDefaults(); } public ModuleX(bool useDatabaseDefaults) { SetSQLProps(); if(useDatabaseDefaults) ForceDefaults(); MarkNew(); } public ModuleX(object keyID) { SetSQLProps(); InitSetDefaults(); LoadByKey(keyID); } public ModuleX(string columnName, object columnValue) { SetSQLProps(); InitSetDefaults(); LoadByParam(columnName,columnValue); } protected static void SetSQLProps() { GetTableSchema(); } #endregion #region Schema and Query Accessor public static Query CreateQuery() { return new Query(Schema); } public static TableSchema.Table Schema { get { if (BaseSchema == null) SetSQLProps(); return BaseSchema; } } private static void GetTableSchema() { if(!IsSchemaInitialized) { //Schema declaration TableSchema.Table schema = new TableSchema.Table("Module", TableType.Table, DataService.GetInstance("ObservationsDB")); schema.Columns = new TableSchema.TableColumnCollection(); schema.SchemaName = @"dbo"; //columns TableSchema.TableColumn colvarId = new TableSchema.TableColumn(schema); colvarId.ColumnName = "ID"; colvarId.DataType = DbType.Guid; colvarId.MaxLength = 0; colvarId.AutoIncrement = false; colvarId.IsNullable = false; colvarId.IsPrimaryKey = true; colvarId.IsForeignKey = false; colvarId.IsReadOnly = false; colvarId.DefaultSetting = @"(newid())"; colvarId.ForeignKeyTableName = ""; schema.Columns.Add(colvarId); TableSchema.TableColumn colvarName = new TableSchema.TableColumn(schema); colvarName.ColumnName = "Name"; colvarName.DataType = DbType.AnsiString; colvarName.MaxLength = 100; colvarName.AutoIncrement = false; colvarName.IsNullable = false; colvarName.IsPrimaryKey = false; colvarName.IsForeignKey = false; colvarName.IsReadOnly = false; colvarName.DefaultSetting = @""; colvarName.ForeignKeyTableName = ""; schema.Columns.Add(colvarName); TableSchema.TableColumn colvarDescription = new TableSchema.TableColumn(schema); colvarDescription.ColumnName = "Description"; colvarDescription.DataType = DbType.AnsiString; colvarDescription.MaxLength = 500; colvarDescription.AutoIncrement = false; colvarDescription.IsNullable = false; colvarDescription.IsPrimaryKey = false; colvarDescription.IsForeignKey = false; colvarDescription.IsReadOnly = false; colvarDescription.DefaultSetting = @""; colvarDescription.ForeignKeyTableName = ""; schema.Columns.Add(colvarDescription); TableSchema.TableColumn colvarUrl = new TableSchema.TableColumn(schema); colvarUrl.ColumnName = "Url"; colvarUrl.DataType = DbType.AnsiString; colvarUrl.MaxLength = 250; colvarUrl.AutoIncrement = false; colvarUrl.IsNullable = false; colvarUrl.IsPrimaryKey = false; colvarUrl.IsForeignKey = false; colvarUrl.IsReadOnly = false; colvarUrl.DefaultSetting = @""; colvarUrl.ForeignKeyTableName = ""; schema.Columns.Add(colvarUrl); TableSchema.TableColumn colvarIcon = new TableSchema.TableColumn(schema); colvarIcon.ColumnName = "Icon"; colvarIcon.DataType = DbType.Int32; colvarIcon.MaxLength = 0; colvarIcon.AutoIncrement = false; colvarIcon.IsNullable = false; colvarIcon.IsPrimaryKey = false; colvarIcon.IsForeignKey = false; colvarIcon.IsReadOnly = false; colvarIcon.DefaultSetting = @""; colvarIcon.ForeignKeyTableName = ""; schema.Columns.Add(colvarIcon); TableSchema.TableColumn colvarModuleID = new TableSchema.TableColumn(schema); colvarModuleID.ColumnName = "ModuleID"; colvarModuleID.DataType = DbType.Guid; colvarModuleID.MaxLength = 0; colvarModuleID.AutoIncrement = false; colvarModuleID.IsNullable = true; colvarModuleID.IsPrimaryKey = false; colvarModuleID.IsForeignKey = true; colvarModuleID.IsReadOnly = false; colvarModuleID.DefaultSetting = @""; colvarModuleID.ForeignKeyTableName = "Module"; schema.Columns.Add(colvarModuleID); TableSchema.TableColumn colvarIOrder = new TableSchema.TableColumn(schema); colvarIOrder.ColumnName = "iOrder"; colvarIOrder.DataType = DbType.Int32; colvarIOrder.MaxLength = 0; colvarIOrder.AutoIncrement = false; colvarIOrder.IsNullable = true; colvarIOrder.IsPrimaryKey = false; colvarIOrder.IsForeignKey = false; colvarIOrder.IsReadOnly = false; colvarIOrder.DefaultSetting = @""; colvarIOrder.ForeignKeyTableName = ""; schema.Columns.Add(colvarIOrder); BaseSchema = schema; //add this schema to the provider //so we can query it later DataService.Providers["ObservationsDB"].AddSchema("Module",schema); } } #endregion #region Props [XmlAttribute("Id")] [Bindable(true)] public Guid Id { get { return GetColumnValue<Guid>(Columns.Id); } set { SetColumnValue(Columns.Id, value); } } [XmlAttribute("Name")] [Bindable(true)] public string Name { get { return GetColumnValue<string>(Columns.Name); } set { SetColumnValue(Columns.Name, value); } } [XmlAttribute("Description")] [Bindable(true)] public string Description { get { return GetColumnValue<string>(Columns.Description); } set { SetColumnValue(Columns.Description, value); } } [XmlAttribute("Url")] [Bindable(true)] public string Url { get { return GetColumnValue<string>(Columns.Url); } set { SetColumnValue(Columns.Url, value); } } [XmlAttribute("Icon")] [Bindable(true)] public int Icon { get { return GetColumnValue<int>(Columns.Icon); } set { SetColumnValue(Columns.Icon, value); } } [XmlAttribute("ModuleID")] [Bindable(true)] public Guid? ModuleID { get { return GetColumnValue<Guid?>(Columns.ModuleID); } set { SetColumnValue(Columns.ModuleID, value); } } [XmlAttribute("IOrder")] [Bindable(true)] public int? IOrder { get { return GetColumnValue<int?>(Columns.IOrder); } set { SetColumnValue(Columns.IOrder, value); } } #endregion #region PrimaryKey Methods protected override void SetPrimaryKey(object oValue) { base.SetPrimaryKey(oValue); SetPKValues(); } public SAEON.Observations.Data.ModuleXCollection ChildModuleXRecords() { return new SAEON.Observations.Data.ModuleXCollection().Where(ModuleX.Columns.ModuleID, Id).Load(); } public SAEON.Observations.Data.RoleModuleCollection RoleModuleRecords() { return new SAEON.Observations.Data.RoleModuleCollection().Where(RoleModule.Columns.ModuleID, Id).Load(); } #endregion #region ForeignKey Properties private SAEON.Observations.Data.ModuleX _ParentModuleX = null; /// <summary> /// Returns a ModuleX ActiveRecord object related to this ModuleX /// /// </summary> public SAEON.Observations.Data.ModuleX ParentModuleX { // get { return SAEON.Observations.Data.ModuleX.FetchByID(this.ModuleID); } get { return _ParentModuleX ?? (_ParentModuleX = SAEON.Observations.Data.ModuleX.FetchByID(this.ModuleID)); } set { SetColumnValue("ModuleID", value.Id); } } #endregion //no ManyToMany tables defined (0) #region ObjectDataSource support /// <summary> /// Inserts a record, can be used with the Object Data Source /// </summary> public static void Insert(Guid varId,string varName,string varDescription,string varUrl,int varIcon,Guid? varModuleID,int? varIOrder) { ModuleX item = new ModuleX(); item.Id = varId; item.Name = varName; item.Description = varDescription; item.Url = varUrl; item.Icon = varIcon; item.ModuleID = varModuleID; item.IOrder = varIOrder; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } /// <summary> /// Updates a record, can be used with the Object Data Source /// </summary> public static void Update(Guid varId,string varName,string varDescription,string varUrl,int varIcon,Guid? varModuleID,int? varIOrder) { ModuleX item = new ModuleX(); item.Id = varId; item.Name = varName; item.Description = varDescription; item.Url = varUrl; item.Icon = varIcon; item.ModuleID = varModuleID; item.IOrder = varIOrder; item.IsNew = false; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } #endregion #region Typed Columns public static TableSchema.TableColumn IdColumn { get { return Schema.Columns[0]; } } public static TableSchema.TableColumn NameColumn { get { return Schema.Columns[1]; } } public static TableSchema.TableColumn DescriptionColumn { get { return Schema.Columns[2]; } } public static TableSchema.TableColumn UrlColumn { get { return Schema.Columns[3]; } } public static TableSchema.TableColumn IconColumn { get { return Schema.Columns[4]; } } public static TableSchema.TableColumn ModuleIDColumn { get { return Schema.Columns[5]; } } public static TableSchema.TableColumn IOrderColumn { get { return Schema.Columns[6]; } } #endregion #region Columns Struct public struct Columns { public static string Id = @"ID"; public static string Name = @"Name"; public static string Description = @"Description"; public static string Url = @"Url"; public static string Icon = @"Icon"; public static string ModuleID = @"ModuleID"; public static string IOrder = @"iOrder"; } #endregion #region Update PK Collections public void SetPKValues() { } #endregion #region Deep Save public void DeepSave() { Save(); } #endregion } }
/// This code was generated by /// \ / _ _ _| _ _ /// | (_)\/(_)(_|\/| |(/_ v1.0.0 /// / / /// <summary> /// UserResource /// </summary> using Newtonsoft.Json; using System; using System.Collections.Generic; using Twilio.Base; using Twilio.Clients; using Twilio.Converters; using Twilio.Exceptions; using Twilio.Http; namespace Twilio.Rest.IpMessaging.V1.Service { public class UserResource : Resource { private static Request BuildFetchRequest(FetchUserOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Get, Rest.Domain.IpMessaging, "/v1/Services/" + options.PathServiceSid + "/Users/" + options.PathSid + "", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// fetch /// </summary> /// <param name="options"> Fetch User parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of User </returns> public static UserResource Fetch(FetchUserOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildFetchRequest(options, client)); return FromJson(response.Content); } #if !NET35 /// <summary> /// fetch /// </summary> /// <param name="options"> Fetch User parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of User </returns> public static async System.Threading.Tasks.Task<UserResource> FetchAsync(FetchUserOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildFetchRequest(options, client)); return FromJson(response.Content); } #endif /// <summary> /// fetch /// </summary> /// <param name="pathServiceSid"> The service_sid </param> /// <param name="pathSid"> The sid </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of User </returns> public static UserResource Fetch(string pathServiceSid, string pathSid, ITwilioRestClient client = null) { var options = new FetchUserOptions(pathServiceSid, pathSid); return Fetch(options, client); } #if !NET35 /// <summary> /// fetch /// </summary> /// <param name="pathServiceSid"> The service_sid </param> /// <param name="pathSid"> The sid </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of User </returns> public static async System.Threading.Tasks.Task<UserResource> FetchAsync(string pathServiceSid, string pathSid, ITwilioRestClient client = null) { var options = new FetchUserOptions(pathServiceSid, pathSid); return await FetchAsync(options, client); } #endif private static Request BuildDeleteRequest(DeleteUserOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Delete, Rest.Domain.IpMessaging, "/v1/Services/" + options.PathServiceSid + "/Users/" + options.PathSid + "", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// delete /// </summary> /// <param name="options"> Delete User parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of User </returns> public static bool Delete(DeleteUserOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildDeleteRequest(options, client)); return response.StatusCode == System.Net.HttpStatusCode.NoContent; } #if !NET35 /// <summary> /// delete /// </summary> /// <param name="options"> Delete User parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of User </returns> public static async System.Threading.Tasks.Task<bool> DeleteAsync(DeleteUserOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildDeleteRequest(options, client)); return response.StatusCode == System.Net.HttpStatusCode.NoContent; } #endif /// <summary> /// delete /// </summary> /// <param name="pathServiceSid"> The service_sid </param> /// <param name="pathSid"> The sid </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of User </returns> public static bool Delete(string pathServiceSid, string pathSid, ITwilioRestClient client = null) { var options = new DeleteUserOptions(pathServiceSid, pathSid); return Delete(options, client); } #if !NET35 /// <summary> /// delete /// </summary> /// <param name="pathServiceSid"> The service_sid </param> /// <param name="pathSid"> The sid </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of User </returns> public static async System.Threading.Tasks.Task<bool> DeleteAsync(string pathServiceSid, string pathSid, ITwilioRestClient client = null) { var options = new DeleteUserOptions(pathServiceSid, pathSid); return await DeleteAsync(options, client); } #endif private static Request BuildCreateRequest(CreateUserOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Post, Rest.Domain.IpMessaging, "/v1/Services/" + options.PathServiceSid + "/Users", postParams: options.GetParams(), headerParams: null ); } /// <summary> /// create /// </summary> /// <param name="options"> Create User parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of User </returns> public static UserResource Create(CreateUserOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildCreateRequest(options, client)); return FromJson(response.Content); } #if !NET35 /// <summary> /// create /// </summary> /// <param name="options"> Create User parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of User </returns> public static async System.Threading.Tasks.Task<UserResource> CreateAsync(CreateUserOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildCreateRequest(options, client)); return FromJson(response.Content); } #endif /// <summary> /// create /// </summary> /// <param name="pathServiceSid"> The service_sid </param> /// <param name="identity"> The identity </param> /// <param name="roleSid"> The role_sid </param> /// <param name="attributes"> The attributes </param> /// <param name="friendlyName"> The friendly_name </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of User </returns> public static UserResource Create(string pathServiceSid, string identity, string roleSid = null, string attributes = null, string friendlyName = null, ITwilioRestClient client = null) { var options = new CreateUserOptions(pathServiceSid, identity){RoleSid = roleSid, Attributes = attributes, FriendlyName = friendlyName}; return Create(options, client); } #if !NET35 /// <summary> /// create /// </summary> /// <param name="pathServiceSid"> The service_sid </param> /// <param name="identity"> The identity </param> /// <param name="roleSid"> The role_sid </param> /// <param name="attributes"> The attributes </param> /// <param name="friendlyName"> The friendly_name </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of User </returns> public static async System.Threading.Tasks.Task<UserResource> CreateAsync(string pathServiceSid, string identity, string roleSid = null, string attributes = null, string friendlyName = null, ITwilioRestClient client = null) { var options = new CreateUserOptions(pathServiceSid, identity){RoleSid = roleSid, Attributes = attributes, FriendlyName = friendlyName}; return await CreateAsync(options, client); } #endif private static Request BuildReadRequest(ReadUserOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Get, Rest.Domain.IpMessaging, "/v1/Services/" + options.PathServiceSid + "/Users", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// read /// </summary> /// <param name="options"> Read User parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of User </returns> public static ResourceSet<UserResource> Read(ReadUserOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildReadRequest(options, client)); var page = Page<UserResource>.FromJson("users", response.Content); return new ResourceSet<UserResource>(page, options, client); } #if !NET35 /// <summary> /// read /// </summary> /// <param name="options"> Read User parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of User </returns> public static async System.Threading.Tasks.Task<ResourceSet<UserResource>> ReadAsync(ReadUserOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildReadRequest(options, client)); var page = Page<UserResource>.FromJson("users", response.Content); return new ResourceSet<UserResource>(page, options, client); } #endif /// <summary> /// read /// </summary> /// <param name="pathServiceSid"> The service_sid </param> /// <param name="pageSize"> Page size </param> /// <param name="limit"> Record limit </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of User </returns> public static ResourceSet<UserResource> Read(string pathServiceSid, int? pageSize = null, long? limit = null, ITwilioRestClient client = null) { var options = new ReadUserOptions(pathServiceSid){PageSize = pageSize, Limit = limit}; return Read(options, client); } #if !NET35 /// <summary> /// read /// </summary> /// <param name="pathServiceSid"> The service_sid </param> /// <param name="pageSize"> Page size </param> /// <param name="limit"> Record limit </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of User </returns> public static async System.Threading.Tasks.Task<ResourceSet<UserResource>> ReadAsync(string pathServiceSid, int? pageSize = null, long? limit = null, ITwilioRestClient client = null) { var options = new ReadUserOptions(pathServiceSid){PageSize = pageSize, Limit = limit}; return await ReadAsync(options, client); } #endif /// <summary> /// Fetch the target page of records /// </summary> /// <param name="targetUrl"> API-generated URL for the requested results page </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The target page of records </returns> public static Page<UserResource> GetPage(string targetUrl, ITwilioRestClient client) { client = client ?? TwilioClient.GetRestClient(); var request = new Request( HttpMethod.Get, targetUrl ); var response = client.Request(request); return Page<UserResource>.FromJson("users", response.Content); } /// <summary> /// Fetch the next page of records /// </summary> /// <param name="page"> current page of records </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The next page of records </returns> public static Page<UserResource> NextPage(Page<UserResource> page, ITwilioRestClient client) { var request = new Request( HttpMethod.Get, page.GetNextPageUrl(Rest.Domain.IpMessaging) ); var response = client.Request(request); return Page<UserResource>.FromJson("users", response.Content); } /// <summary> /// Fetch the previous page of records /// </summary> /// <param name="page"> current page of records </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The previous page of records </returns> public static Page<UserResource> PreviousPage(Page<UserResource> page, ITwilioRestClient client) { var request = new Request( HttpMethod.Get, page.GetPreviousPageUrl(Rest.Domain.IpMessaging) ); var response = client.Request(request); return Page<UserResource>.FromJson("users", response.Content); } private static Request BuildUpdateRequest(UpdateUserOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Post, Rest.Domain.IpMessaging, "/v1/Services/" + options.PathServiceSid + "/Users/" + options.PathSid + "", postParams: options.GetParams(), headerParams: null ); } /// <summary> /// update /// </summary> /// <param name="options"> Update User parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of User </returns> public static UserResource Update(UpdateUserOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildUpdateRequest(options, client)); return FromJson(response.Content); } #if !NET35 /// <summary> /// update /// </summary> /// <param name="options"> Update User parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of User </returns> public static async System.Threading.Tasks.Task<UserResource> UpdateAsync(UpdateUserOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildUpdateRequest(options, client)); return FromJson(response.Content); } #endif /// <summary> /// update /// </summary> /// <param name="pathServiceSid"> The service_sid </param> /// <param name="pathSid"> The sid </param> /// <param name="roleSid"> The role_sid </param> /// <param name="attributes"> The attributes </param> /// <param name="friendlyName"> The friendly_name </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of User </returns> public static UserResource Update(string pathServiceSid, string pathSid, string roleSid = null, string attributes = null, string friendlyName = null, ITwilioRestClient client = null) { var options = new UpdateUserOptions(pathServiceSid, pathSid){RoleSid = roleSid, Attributes = attributes, FriendlyName = friendlyName}; return Update(options, client); } #if !NET35 /// <summary> /// update /// </summary> /// <param name="pathServiceSid"> The service_sid </param> /// <param name="pathSid"> The sid </param> /// <param name="roleSid"> The role_sid </param> /// <param name="attributes"> The attributes </param> /// <param name="friendlyName"> The friendly_name </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of User </returns> public static async System.Threading.Tasks.Task<UserResource> UpdateAsync(string pathServiceSid, string pathSid, string roleSid = null, string attributes = null, string friendlyName = null, ITwilioRestClient client = null) { var options = new UpdateUserOptions(pathServiceSid, pathSid){RoleSid = roleSid, Attributes = attributes, FriendlyName = friendlyName}; return await UpdateAsync(options, client); } #endif /// <summary> /// Converts a JSON string into a UserResource object /// </summary> /// <param name="json"> Raw JSON string </param> /// <returns> UserResource object represented by the provided JSON </returns> public static UserResource FromJson(string json) { // Convert all checked exceptions to Runtime try { return JsonConvert.DeserializeObject<UserResource>(json); } catch (JsonException e) { throw new ApiException(e.Message, e); } } /// <summary> /// The sid /// </summary> [JsonProperty("sid")] public string Sid { get; private set; } /// <summary> /// The account_sid /// </summary> [JsonProperty("account_sid")] public string AccountSid { get; private set; } /// <summary> /// The service_sid /// </summary> [JsonProperty("service_sid")] public string ServiceSid { get; private set; } /// <summary> /// The attributes /// </summary> [JsonProperty("attributes")] public string Attributes { get; private set; } /// <summary> /// The friendly_name /// </summary> [JsonProperty("friendly_name")] public string FriendlyName { get; private set; } /// <summary> /// The role_sid /// </summary> [JsonProperty("role_sid")] public string RoleSid { get; private set; } /// <summary> /// The identity /// </summary> [JsonProperty("identity")] public string Identity { get; private set; } /// <summary> /// The is_online /// </summary> [JsonProperty("is_online")] public bool? IsOnline { get; private set; } /// <summary> /// The is_notifiable /// </summary> [JsonProperty("is_notifiable")] public bool? IsNotifiable { get; private set; } /// <summary> /// The date_created /// </summary> [JsonProperty("date_created")] public DateTime? DateCreated { get; private set; } /// <summary> /// The date_updated /// </summary> [JsonProperty("date_updated")] public DateTime? DateUpdated { get; private set; } /// <summary> /// The joined_channels_count /// </summary> [JsonProperty("joined_channels_count")] public int? JoinedChannelsCount { get; private set; } /// <summary> /// The links /// </summary> [JsonProperty("links")] public Dictionary<string, string> Links { get; private set; } /// <summary> /// The url /// </summary> [JsonProperty("url")] public Uri Url { get; private set; } private UserResource() { } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.InteropServices; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { using ASM_CACHE = GlobalAssemblyCacheLocation.ASM_CACHE; /// <summary> /// Provides APIs to enumerate and look up assemblies stored in the Global Assembly Cache. /// </summary> internal sealed class ClrGlobalAssemblyCache : GlobalAssemblyCache { #region Interop private const int MAX_PATH = 260; [ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("21b8916c-f28e-11d2-a473-00c04f8ef448")] private interface IAssemblyEnum { [PreserveSig] int GetNextAssembly(out FusionAssemblyIdentity.IApplicationContext ppAppCtx, out FusionAssemblyIdentity.IAssemblyName ppName, uint dwFlags); [PreserveSig] int Reset(); [PreserveSig] int Clone(out IAssemblyEnum ppEnum); } [ComImport, Guid("e707dcde-d1cd-11d2-bab9-00c04f8eceae"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] private interface IAssemblyCache { void UninstallAssembly(); void QueryAssemblyInfo(uint dwFlags, [MarshalAs(UnmanagedType.LPWStr)] string pszAssemblyName, ref ASSEMBLY_INFO pAsmInfo); void CreateAssemblyCacheItem(); void CreateAssemblyScavenger(); void InstallAssembly(); } [StructLayout(LayoutKind.Sequential)] private unsafe struct ASSEMBLY_INFO { public uint cbAssemblyInfo; public readonly uint dwAssemblyFlags; public readonly ulong uliAssemblySizeInKB; public char* pszCurrentAssemblyPathBuf; public uint cchBuf; } [DllImport("clr", PreserveSig = true)] private static extern int CreateAssemblyEnum(out IAssemblyEnum ppEnum, FusionAssemblyIdentity.IApplicationContext pAppCtx, FusionAssemblyIdentity.IAssemblyName pName, ASM_CACHE dwFlags, IntPtr pvReserved); [DllImport("clr", PreserveSig = false)] private static extern void CreateAssemblyCache(out IAssemblyCache ppAsmCache, uint dwReserved); #endregion /// <summary> /// Enumerates assemblies in the GAC returning those that match given partial name and /// architecture. /// </summary> /// <param name="partialName">Optional partial name.</param> /// <param name="architectureFilter">Optional architecture filter.</param> public override IEnumerable<AssemblyIdentity> GetAssemblyIdentities(AssemblyName partialName, ImmutableArray<ProcessorArchitecture> architectureFilter = default(ImmutableArray<ProcessorArchitecture>)) { return GetAssemblyIdentities(FusionAssemblyIdentity.ToAssemblyNameObject(partialName), architectureFilter); } /// <summary> /// Enumerates assemblies in the GAC returning those that match given partial name and /// architecture. /// </summary> /// <param name="partialName">The optional partial name.</param> /// <param name="architectureFilter">The optional architecture filter.</param> public override IEnumerable<AssemblyIdentity> GetAssemblyIdentities(string partialName = null, ImmutableArray<ProcessorArchitecture> architectureFilter = default(ImmutableArray<ProcessorArchitecture>)) { FusionAssemblyIdentity.IAssemblyName nameObj; if (partialName != null) { nameObj = FusionAssemblyIdentity.ToAssemblyNameObject(partialName); if (nameObj == null) { return SpecializedCollections.EmptyEnumerable<AssemblyIdentity>(); } } else { nameObj = null; } return GetAssemblyIdentities(nameObj, architectureFilter); } /// <summary> /// Enumerates assemblies in the GAC returning their simple names. /// </summary> /// <param name="architectureFilter">Optional architecture filter.</param> /// <returns>Unique simple names of GAC assemblies.</returns> public override IEnumerable<string> GetAssemblySimpleNames(ImmutableArray<ProcessorArchitecture> architectureFilter = default(ImmutableArray<ProcessorArchitecture>)) { var q = from nameObject in GetAssemblyObjects(partialNameFilter: null, architectureFilter: architectureFilter) select FusionAssemblyIdentity.GetName(nameObject); return q.Distinct(); } private static IEnumerable<AssemblyIdentity> GetAssemblyIdentities( FusionAssemblyIdentity.IAssemblyName partialName, ImmutableArray<ProcessorArchitecture> architectureFilter) { return from nameObject in GetAssemblyObjects(partialName, architectureFilter) select FusionAssemblyIdentity.ToAssemblyIdentity(nameObject); } private const int S_OK = 0; private const int S_FALSE = 1; // Internal for testing. internal static IEnumerable<FusionAssemblyIdentity.IAssemblyName> GetAssemblyObjects( FusionAssemblyIdentity.IAssemblyName partialNameFilter, ImmutableArray<ProcessorArchitecture> architectureFilter) { IAssemblyEnum enumerator; FusionAssemblyIdentity.IApplicationContext applicationContext = null; int hr = CreateAssemblyEnum(out enumerator, applicationContext, partialNameFilter, ASM_CACHE.GAC, IntPtr.Zero); if (hr == S_FALSE) { // no assembly found yield break; } else if (hr != S_OK) { Exception e = Marshal.GetExceptionForHR(hr); if (e is FileNotFoundException) { // invalid assembly name: yield break; } else if (e != null) { throw e; } else { // for some reason it might happen that CreateAssemblyEnum returns non-zero HR that doesn't correspond to any exception: #if SCRIPTING throw new ArgumentException(Microsoft.CodeAnalysis.Scripting.ScriptingResources.InvalidAssemblyName); #else throw new ArgumentException(Microsoft.CodeAnalysis.WorkspaceDesktopResources.Invalid_assembly_name); #endif } } while (true) { FusionAssemblyIdentity.IAssemblyName nameObject; hr = enumerator.GetNextAssembly(out applicationContext, out nameObject, 0); if (hr != 0) { if (hr < 0) { Marshal.ThrowExceptionForHR(hr); } break; } if (!architectureFilter.IsDefault) { var assemblyArchitecture = FusionAssemblyIdentity.GetProcessorArchitecture(nameObject); if (!architectureFilter.Contains(assemblyArchitecture)) { continue; } } yield return nameObject; } } public override AssemblyIdentity ResolvePartialName( string displayName, out string location, ImmutableArray<ProcessorArchitecture> architectureFilter, CultureInfo preferredCulture) { if (displayName == null) { throw new ArgumentNullException(nameof(displayName)); } location = null; FusionAssemblyIdentity.IAssemblyName nameObject = FusionAssemblyIdentity.ToAssemblyNameObject(displayName); if (nameObject == null) { return null; } var candidates = GetAssemblyObjects(nameObject, architectureFilter); string cultureName = (preferredCulture != null && !preferredCulture.IsNeutralCulture) ? preferredCulture.Name : null; var bestMatch = FusionAssemblyIdentity.GetBestMatch(candidates, cultureName); if (bestMatch == null) { return null; } location = GetAssemblyLocation(bestMatch); return FusionAssemblyIdentity.ToAssemblyIdentity(bestMatch); } internal static unsafe string GetAssemblyLocation(FusionAssemblyIdentity.IAssemblyName nameObject) { // NAME | VERSION | CULTURE | PUBLIC_KEY_TOKEN | RETARGET | PROCESSORARCHITECTURE string fullName = FusionAssemblyIdentity.GetDisplayName(nameObject, FusionAssemblyIdentity.ASM_DISPLAYF.FULL); fixed (char* p = new char[MAX_PATH]) { ASSEMBLY_INFO info = new ASSEMBLY_INFO { cbAssemblyInfo = (uint)Marshal.SizeOf<ASSEMBLY_INFO>(), pszCurrentAssemblyPathBuf = p, cchBuf = MAX_PATH }; IAssemblyCache assemblyCacheObject; CreateAssemblyCache(out assemblyCacheObject, 0); assemblyCacheObject.QueryAssemblyInfo(0, fullName, ref info); Debug.Assert(info.pszCurrentAssemblyPathBuf != null); Debug.Assert(info.pszCurrentAssemblyPathBuf[info.cchBuf - 1] == '\0'); var result = Marshal.PtrToStringUni((IntPtr)info.pszCurrentAssemblyPathBuf, (int)info.cchBuf - 1); Debug.Assert(result.IndexOf('\0') == -1); return result; } } } }
//--------------------------------------------------------------------- // <copyright file="CsdlSemanticsNavigationSource.cs" company="Microsoft"> // Copyright (C) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information. // </copyright> //--------------------------------------------------------------------- namespace Microsoft.OData.Edm.Csdl.CsdlSemantics { using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using Microsoft.OData.Edm; using Microsoft.OData.Edm.Annotations; using Microsoft.OData.Edm.Csdl.Parsing.Ast; using Microsoft.OData.Edm.Expressions; using Microsoft.OData.Edm.Library; using Microsoft.OData.Edm.Library.Expressions; /// <summary> /// Provides semantics for CsdlAbstractNavigationSource. /// </summary> internal abstract class CsdlSemanticsNavigationSource : CsdlSemanticsElement, IEdmNavigationSource { [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1304:NonPrivateReadonlyFieldsMustBeginWithUpperCaseLetter", Justification = "protected field in internal class.")] protected readonly CsdlAbstractNavigationSource navigationSource; [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1304:NonPrivateReadonlyFieldsMustBeginWithUpperCaseLetter", Justification = "protected field in internal class.")] protected readonly CsdlSemanticsEntityContainer container; [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1304:NonPrivateReadonlyFieldsMustBeginWithUpperCaseLetter", Justification = "protected field in internal class.")] protected readonly IEdmPathExpression path; [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1304:NonPrivateReadonlyFieldsMustBeginWithUpperCaseLetter", Justification = "protected field in internal class.")] protected readonly Cache<CsdlSemanticsNavigationSource, IEdmEntityType> typeCache = new Cache<CsdlSemanticsNavigationSource, IEdmEntityType>(); protected static readonly Func<CsdlSemanticsNavigationSource, IEdmEntityType> ComputeElementTypeFunc = (me) => me.ComputeElementType(); private readonly Cache<CsdlSemanticsNavigationSource, IEnumerable<IEdmNavigationPropertyBinding>> navigationTargetsCache = new Cache<CsdlSemanticsNavigationSource, IEnumerable<IEdmNavigationPropertyBinding>>(); private static readonly Func<CsdlSemanticsNavigationSource, IEnumerable<IEdmNavigationPropertyBinding>> ComputeNavigationTargetsFunc = (me) => me.ComputeNavigationTargets(); private readonly Dictionary<IEdmNavigationProperty, IEdmContainedEntitySet> containedNavigationPropertyCache = new Dictionary<IEdmNavigationProperty, IEdmContainedEntitySet>(); private readonly Dictionary<IEdmNavigationProperty, IEdmUnknownEntitySet> unknownNavigationPropertyCache = new Dictionary<IEdmNavigationProperty, IEdmUnknownEntitySet>(); public CsdlSemanticsNavigationSource(CsdlSemanticsEntityContainer container, CsdlAbstractNavigationSource navigationSource) : base(navigationSource) { this.container = container; this.navigationSource = navigationSource; this.path = new EdmPathExpression(this.navigationSource.Name); } public override CsdlSemanticsModel Model { get { return this.container.Model; } } public IEdmEntityContainer Container { get { return this.container; } } public override CsdlElement Element { get { return this.navigationSource; } } public string Name { get { return this.navigationSource.Name; } } public Expressions.IEdmPathExpression Path { get { return this.path; } } public abstract IEdmType Type { get; } public abstract EdmContainerElementKind ContainerElementKind { get; } public IEnumerable<IEdmNavigationPropertyBinding> NavigationPropertyBindings { get { return this.navigationTargetsCache.GetValue(this, ComputeNavigationTargetsFunc, null); } } public IEdmNavigationSource FindNavigationTarget(IEdmNavigationProperty property) { EdmUtil.CheckArgumentNull(property, "property"); if (!property.ContainsTarget) { foreach (IEdmNavigationPropertyBinding targetMapping in this.NavigationPropertyBindings) { if (targetMapping.NavigationProperty == property) { return targetMapping.Target; } } } else { return EdmUtil.DictionaryGetOrUpdate( this.containedNavigationPropertyCache, property, navProperty => new EdmContainedEntitySet(this, navProperty)); } return EdmUtil.DictionaryGetOrUpdate( this.unknownNavigationPropertyCache, property, navProperty => new EdmUnknownEntitySet(this, navProperty)); } protected override IEnumerable<IEdmVocabularyAnnotation> ComputeInlineVocabularyAnnotations() { return this.Model.WrapInlineVocabularyAnnotations(this, this.container.Context); } protected abstract IEdmEntityType ComputeElementType(); private IEnumerable<IEdmNavigationPropertyBinding> ComputeNavigationTargets() { return this.navigationSource.NavigationPropertyBindings.Select(this.CreateSemanticMappingForBinding).ToList(); } private IEdmNavigationPropertyBinding CreateSemanticMappingForBinding(CsdlNavigationPropertyBinding binding) { IEdmNavigationProperty navigationProperty = this.ResolveNavigationPropertyPathForBinding(binding); IEdmNavigationSource targetNavigationSource = this.Container.FindEntitySetExtended(binding.Target); if (targetNavigationSource == null) { targetNavigationSource = this.Container.FindSingletonExtended(binding.Target); if (targetNavigationSource == null) { targetNavigationSource = new UnresolvedEntitySet(binding.Target, this.Container, binding.Location); } } return new EdmNavigationPropertyBinding(navigationProperty, targetNavigationSource); } private IEdmNavigationProperty ResolveNavigationPropertyPathForBinding(CsdlNavigationPropertyBinding binding) { Debug.Assert(binding != null, "binding != null"); string bindingPath = binding.Path; Debug.Assert(bindingPath != null, "bindingPath != null"); IEdmEntityType definingType = this.typeCache.GetValue(this, ComputeElementTypeFunc, null); const char Slash = '/'; if (bindingPath.Length == 0 || bindingPath[bindingPath.Length - 1] == Slash) { // if the path did not actually contain a navigation property, then treat it as an unresolved path. // TODO: improve the error given in this case? return new UnresolvedNavigationPropertyPath(definingType, bindingPath, binding.Location); } IEdmNavigationProperty navigationProperty; string[] pathSegements = bindingPath.Split(Slash); for (int index = 0; index < pathSegements.Length - 1; index++) { string pathSegement = pathSegements[index]; if (pathSegement.Length == 0) { // TODO: improve the error given in this case? return new UnresolvedNavigationPropertyPath(definingType, bindingPath, binding.Location); } IEdmEntityType derivedType = this.container.Context.FindType(pathSegement) as IEdmEntityType; if (derivedType == null) { IEdmProperty property = definingType.FindProperty(pathSegement); navigationProperty = property as IEdmNavigationProperty; if (navigationProperty == null) { return new UnresolvedNavigationPropertyPath(definingType, bindingPath, binding.Location); } definingType = navigationProperty.ToEntityType(); } else { definingType = derivedType; } } navigationProperty = definingType.FindProperty(pathSegements.Last()) as IEdmNavigationProperty; if (navigationProperty == null) { // TODO: improve the error given in this case? navigationProperty = new UnresolvedNavigationPropertyPath(definingType, bindingPath, binding.Location); } return navigationProperty; } } }
using System; using System.Collections; using System.IO; using BigMath; using NUnit.Framework; using Raksha.Bcpg; using Raksha.Bcpg.OpenPgp; using Raksha.Crypto; using Raksha.Crypto.Generators; using Raksha.Crypto.Parameters; using Raksha.Math; using Raksha.Security; using Raksha.Utilities.Encoders; using Raksha.Tests.Utilities; namespace Raksha.Tests.Bcpg.OpenPgp { [TestFixture] public class PgpKeyRingTest : SimpleTest { private static readonly byte[] pub1 = Base64.Decode( "mQGiBEA83v0RBADzKVLVCnpWQxX0LCsevw/3OLs0H7MOcLBQ4wMO9sYmzGYn" + "xpVj+4e4PiCP7QBayWyy4lugL6Lnw7tESvq3A4v3fefcxaCTkJrryiKn4+Cg" + "y5rIBbrSKNtCEhVi7xjtdnDjP5kFKgHYjVOeIKn4Cz/yzPG3qz75kDknldLf" + "yHxp2wCgwW1vAE5EnZU4/UmY7l8kTNkMltMEAJP4/uY4zcRwLI9Q2raPqAOJ" + "TYLd7h+3k/BxI0gIw96niQ3KmUZDlobbWBI+VHM6H99vcttKU3BgevNf8M9G" + "x/AbtW3SS4De64wNSU3189XDG8vXf0vuyW/K6Pcrb8exJWY0E1zZQ1WXT0gZ" + "W0kH3g5ro//Tusuil9q2lVLF2ovJA/0W+57bPzi318dWeNs0tTq6Njbc/GTG" + "FUAVJ8Ss5v2u6h7gyJ1DB334ExF/UdqZGldp0ugkEXaSwBa2R7d3HBgaYcoP" + "Ck1TrovZzEY8gm7JNVy7GW6mdOZuDOHTxyADEEP2JPxh6eRcZbzhGuJuYIif" + "IIeLOTI5Dc4XKeV32a+bWrQidGVzdCAoVGVzdCBrZXkpIDx0ZXN0QHViaWNh" + "bGwuY29tPohkBBMRAgAkBQJAPN79AhsDBQkB4TOABgsJCAcDAgMVAgMDFgIB" + "Ah4BAheAAAoJEJh8Njfhe8KmGDcAoJWr8xgPr75y/Cp1kKn12oCCOb8zAJ4p" + "xSvk4K6tB2jYbdeSrmoWBZLdMLACAAC5AQ0EQDzfARAEAJeUAPvUzJJbKcc5" + "5Iyb13+Gfb8xBWE3HinQzhGr1v6A1aIZbRj47UPAD/tQxwz8VAwJySx82ggN" + "LxCk4jW9YtTL3uZqfczsJngV25GoIN10f4/j2BVqZAaX3q79a3eMiql1T0oE" + "AGmD7tO1LkTvWfm3VvA0+t8/6ZeRLEiIqAOHAAQNBACD0mVMlAUgd7REYy/1" + "mL99Zlu9XU0uKyUex99sJNrcx1aj8rIiZtWaHz6CN1XptdwpDeSYEOFZ0PSu" + "qH9ByM3OfjU/ya0//xdvhwYXupn6P1Kep85efMBA9jUv/DeBOzRWMFG6sC6y" + "k8NGG7Swea7EHKeQI40G3jgO/+xANtMyTIhPBBgRAgAPBQJAPN8BAhsMBQkB" + "4TOAAAoJEJh8Njfhe8KmG7kAn00mTPGJCWqmskmzgdzeky5fWd7rAKCNCp3u" + "ZJhfg0htdgAfIy8ppm05vLACAAA="); private static readonly byte[] sec1 = Base64.Decode( "lQHhBEA83v0RBADzKVLVCnpWQxX0LCsevw/3OLs0H7MOcLBQ4wMO9sYmzGYn" + "xpVj+4e4PiCP7QBayWyy4lugL6Lnw7tESvq3A4v3fefcxaCTkJrryiKn4+Cg" + "y5rIBbrSKNtCEhVi7xjtdnDjP5kFKgHYjVOeIKn4Cz/yzPG3qz75kDknldLf" + "yHxp2wCgwW1vAE5EnZU4/UmY7l8kTNkMltMEAJP4/uY4zcRwLI9Q2raPqAOJ" + "TYLd7h+3k/BxI0gIw96niQ3KmUZDlobbWBI+VHM6H99vcttKU3BgevNf8M9G" + "x/AbtW3SS4De64wNSU3189XDG8vXf0vuyW/K6Pcrb8exJWY0E1zZQ1WXT0gZ" + "W0kH3g5ro//Tusuil9q2lVLF2ovJA/0W+57bPzi318dWeNs0tTq6Njbc/GTG" + "FUAVJ8Ss5v2u6h7gyJ1DB334ExF/UdqZGldp0ugkEXaSwBa2R7d3HBgaYcoP" + "Ck1TrovZzEY8gm7JNVy7GW6mdOZuDOHTxyADEEP2JPxh6eRcZbzhGuJuYIif" + "IIeLOTI5Dc4XKeV32a+bWv4CAwJ5KgazImo+sGBfMhDiBcBTqyDGhKHNgHic" + "0Pky9FeRvfXTc2AO+jGmFPjcs8BnTWuDD0/jkQnRZpp1TrQidGVzdCAoVGVz" + "dCBrZXkpIDx0ZXN0QHViaWNhbGwuY29tPohkBBMRAgAkBQJAPN79AhsDBQkB" + "4TOABgsJCAcDAgMVAgMDFgIBAh4BAheAAAoJEJh8Njfhe8KmGDcAn3XeXDMg" + "BZgrZzFWU2IKtA/5LG2TAJ0Vf/jjyq0jZNZfGfoqGTvD2MAl0rACAACdAVgE" + "QDzfARAEAJeUAPvUzJJbKcc55Iyb13+Gfb8xBWE3HinQzhGr1v6A1aIZbRj4" + "7UPAD/tQxwz8VAwJySx82ggNLxCk4jW9YtTL3uZqfczsJngV25GoIN10f4/j" + "2BVqZAaX3q79a3eMiql1T0oEAGmD7tO1LkTvWfm3VvA0+t8/6ZeRLEiIqAOH" + "AAQNBACD0mVMlAUgd7REYy/1mL99Zlu9XU0uKyUex99sJNrcx1aj8rIiZtWa" + "Hz6CN1XptdwpDeSYEOFZ0PSuqH9ByM3OfjU/ya0//xdvhwYXupn6P1Kep85e" + "fMBA9jUv/DeBOzRWMFG6sC6yk8NGG7Swea7EHKeQI40G3jgO/+xANtMyTP4C" + "AwJ5KgazImo+sGBl2C7CFuI+5KM4ZhbtVie7l+OiTpr5JW2z5VgnV3EX9p04" + "LcGKfQvD65+ELwli6yh8B2zGcipqTaYk3QoYNIhPBBgRAgAPBQJAPN8BAhsM" + "BQkB4TOAAAoJEJh8Njfhe8KmG7kAniuRkaFFv1pdCBN8JJXpcorHmyouAJ9L" + "xxmusffR6OI7WgD3XZ0AL8zUC7ACAAA="); // private static readonly char[] pass1 = "qwertzuiop".ToCharArray(); private static readonly byte[] pub2 = Base64.Decode( "mQGiBEBtfW8RBADfWjTxFedIbGBNVgh064D/OCf6ul7x4PGsCl+BkAyheYkr" + "mVUsChmBKoeXaY+Fb85wwusXzyM/6JFK58Rg+vEb3Z19pue8Ixxq7cRtCtOA" + "tOP1eKXLNtTRWJutvLkQmeOa19UZ6ziIq23aWuWKSq+KKMWek2GUnGycnx5M" + "W0pn1QCg/39r9RKhY9cdKYqRcqsr9b2B/AsD/Ru24Q15Jmrsl9zZ6EC47J49" + "iNW5sLQx1qf/mgfVWQTmU2j6gq4ND1OuK7+0OP/1yMOUpkjjcqxFgTnDAAoM" + "hHDTzCv/aZzIzmMvgLsYU3aIMfbz+ojpuASMCMh+te01cEMjiPWwDtdWWOdS" + "OSyX9ylzhO3PiNDks8R83onsacYpA/9WhTcg4bvkjaj66I7wGZkm3BmTxNSb" + "pE4b5HZDh31rRYhY9tmrryCfFnU4BS2Enjj5KQe9zFv7pUBCBW2oFo8i8Osn" + "O6fa1wVN4fBHC6wqWmmpnkFerNPkiC9V75KUFIfeWHmT3r2DVSO3dfdHDERA" + "jFIAioMLjhaX6DnODF5KQrABh7QmU2FpIFB1bGxhYmhvdGxhIDxwc2FpQG15" + "amF2YXdvcmxkLmNvbT6wAwP//4kAVwQQEQIAFwUCQG19bwcLCQgHAwIKAhkB" + "BRsDAAAAAAoJEKXQf/RT99uYmfAAoMKxV5g2owIfmy2w7vSLvOQUpvvOAJ4n" + "jB6xJot523rPAQW9itPoGGekirABZ7kCDQRAbX1vEAgA9kJXtwh/CBdyorrW" + "qULzBej5UxE5T7bxbrlLOCDaAadWoxTpj0BV89AHxstDqZSt90xkhkn4DIO9" + "ZekX1KHTUPj1WV/cdlJPPT2N286Z4VeSWc39uK50T8X8dryDxUcwYc58yWb/" + "Ffm7/ZFexwGq01uejaClcjrUGvC/RgBYK+X0iP1YTknbzSC0neSRBzZrM2w4" + "DUUdD3yIsxx8Wy2O9vPJI8BD8KVbGI2Ou1WMuF040zT9fBdXQ6MdGGzeMyEs" + "tSr/POGxKUAYEY18hKcKctaGxAMZyAcpesqVDNmWn6vQClCbAkbTCD1mpF1B" + "n5x8vYlLIhkmuquiXsNV6TILOwACAgf9F7/nJHDayJ3pBVTTVSq2g5WKUXMg" + "xxGKTvOahiVRcbO03w0pKAkH85COakVfe56sMYpWRl36adjNoKOxaciow74D" + "1R5snY/hv/kBXPBkzo4UMkbANIVaZ0IcnLp+rkkXcDVbRCibZf8FfCY1zXbq" + "d680UtEgRbv1D8wFBqfMt7kLsuf9FnIw6vK4DU06z5ZDg25RHGmswaDyY6Mw" + "NGCrKGbHf9I/T7MMuhGF/in8UU8hv8uREOjseOqklG3/nsI1hD/MdUC7fzXi" + "MRO4RvahLoeXOuaDkMYALdJk5nmNuCL1YPpbFGttI3XsK7UrP/Fhd8ND6Nro" + "wCqrN6keduK+uLABh4kATAQYEQIADAUCQG19bwUbDAAAAAAKCRCl0H/0U/fb" + "mC/0AJ4r1yvyu4qfOXlDgmVuCsvHFWo63gCfRIrCB2Jv/N1cgpmq0L8LGHM7" + "G/KwAWeZAQ0EQG19owEIAMnavLYqR7ffaDPbbq+lQZvLCK/3uA0QlyngNyTa" + "sDW0WC1/ryy2dx7ypOOCicjnPYfg3LP5TkYAGoMjxH5+xzM6xfOR+8/EwK1z" + "N3A5+X/PSBDlYjQ9dEVKrvvc7iMOp+1K1VMf4Ug8Yah22Ot4eLGP0HRCXiv5" + "vgdBNsAl/uXnBJuDYQmLrEniqq/6UxJHKHxZoS/5p13Cq7NfKB1CJCuJXaCE" + "TW2do+cDpN6r0ltkF/r+ES+2L7jxyoHcvQ4YorJoDMlAN6xpIZQ8dNaTYP/n" + "Mx/pDS3shUzbU+UYPQrreJLMF1pD+YWP5MTKaZTo+U/qPjDFGcadInhPxvh3" + "1ssAEQEAAbABh7QuU2FuZGh5YSBQdWxsYWJob3RsYSA8cHNhbmRoeWFAbXlq" + "YXZhd29ybGQuY29tPrADA///iQEtBBABAgAXBQJAbX2jBwsJCAcDAgoCGQEF" + "GwMAAAAACgkQx87DL9gOvoeVUwgAkQXYiF0CxhKbDnuabAssnOEwJrutgCRO" + "CJRQvIwTe3fe6hQaWn2Yowt8OQtNFiR8GfAY6EYxyFLKzZbAI/qtq5fHmN3e" + "RSyNWe6d6e17hqZZL7kf2sVkyGTChHj7Jiuo7vWkdqT2MJN6BW5tS9CRH7Me" + "D839STv+4mAAO9auGvSvicP6UEQikAyCy/ihoJxLQlspfbSNpi0vrUjCPT7N" + "tWwfP0qF64i9LYkjzLqihnu+UareqOPhXcWnyFKrjmg4ezQkweNU2pdvCLbc" + "W24FhT92ivHgpLyWTswXcqjhFjVlRr0+2sIz7v1k0budCsJ7PjzOoH0hJxCv" + "sJQMlZR/e7ABZ7kBDQRAbX2kAQgAm5j+/LO2M4pKm/VUPkYuj3eefHkzjM6n" + "KbvRZX1Oqyf+6CJTxQskUWKAtkzzKafPdS5Wg0CMqeXov+EFod4bPEYccszn" + "cKd1U8NRwacbEpCvvvB84Yl2YwdWpDpkryyyLI4PbCHkeuwx9Dc2z7t4XDB6" + "FyAJTMAkia7nzYa/kbeUO3c2snDb/dU7uyCsyKtTZyTyhTgtl/f9L03Bgh95" + "y3mOUz0PimJ0Sg4ANczF4d04BpWkjLNVJi489ifWodPlHm1hag5drYekYpWJ" + "+3g0uxs5AwayV9BcOkPKb1uU3EoYQw+nn0Kn314Nvx2M1tKYunuVNLEm0PhA" + "/+B8PTq8BQARAQABsAGHiQEiBBgBAgAMBQJAbX2kBRsMAAAAAAoJEMfOwy/Y" + "Dr6HkLoH/RBY8lvUv1r8IdTs5/fN8e/MnGeThLl+JrlYF/4t3tjXYIf5xUj/" + "c9NdjreKYgHfMtrbVM08LlxUVQlkjuF3DIk5bVH9Blq8aXmyiwiM5GrCry+z" + "WiqkpZze1G577C38mMJbHDwbqNCLALMzo+W2q04Avl5sniNnDNGbGz9EjhRg" + "o7oS16KkkD6Ls4RnHTEZ0vyZOXodDHu+sk/2kzj8K07kKaM8rvR7aDKiI7HH" + "1GxJz70fn1gkKuV2iAIIiU25bty+S3wr+5h030YBsUZF1qeKCdGOmpK7e9Of" + "yv9U7rf6Z5l8q+akjqLZvej9RnxeH2Um7W+tGg2me482J+z6WOawAWc="); private static readonly byte[] sec2 = Base64.Decode( "lQHpBEBtfW8RBADfWjTxFedIbGBNVgh064D/OCf6ul7x4PGsCl+BkAyheYkr" + "mVUsChmBKoeXaY+Fb85wwusXzyM/6JFK58Rg+vEb3Z19pue8Ixxq7cRtCtOA" + "tOP1eKXLNtTRWJutvLkQmeOa19UZ6ziIq23aWuWKSq+KKMWek2GUnGycnx5M" + "W0pn1QCg/39r9RKhY9cdKYqRcqsr9b2B/AsD/Ru24Q15Jmrsl9zZ6EC47J49" + "iNW5sLQx1qf/mgfVWQTmU2j6gq4ND1OuK7+0OP/1yMOUpkjjcqxFgTnDAAoM" + "hHDTzCv/aZzIzmMvgLsYU3aIMfbz+ojpuASMCMh+te01cEMjiPWwDtdWWOdS" + "OSyX9ylzhO3PiNDks8R83onsacYpA/9WhTcg4bvkjaj66I7wGZkm3BmTxNSb" + "pE4b5HZDh31rRYhY9tmrryCfFnU4BS2Enjj5KQe9zFv7pUBCBW2oFo8i8Osn" + "O6fa1wVN4fBHC6wqWmmpnkFerNPkiC9V75KUFIfeWHmT3r2DVSO3dfdHDERA" + "jFIAioMLjhaX6DnODF5KQv4JAwIJH6A/rzqmMGAG4e+b8Whdvp8jaTGVT4CG" + "M1b65rbiDyAuf5KTFymQBOIi9towgFzG9NXAZC07nEYSukN56tUTUDNVsAGH" + "tCZTYWkgUHVsbGFiaG90bGEgPHBzYWlAbXlqYXZhd29ybGQuY29tPrADA///" + "iQBXBBARAgAXBQJAbX1vBwsJCAcDAgoCGQEFGwMAAAAACgkQpdB/9FP325iZ" + "8ACgwrFXmDajAh+bLbDu9Iu85BSm+84AnieMHrEmi3nbes8BBb2K0+gYZ6SK" + "sAFnnQJqBEBtfW8QCAD2Qle3CH8IF3KiutapQvMF6PlTETlPtvFuuUs4INoB" + "p1ajFOmPQFXz0AfGy0OplK33TGSGSfgMg71l6RfUodNQ+PVZX9x2Uk89PY3b" + "zpnhV5JZzf24rnRPxfx2vIPFRzBhznzJZv8V+bv9kV7HAarTW56NoKVyOtQa" + "8L9GAFgr5fSI/VhOSdvNILSd5JEHNmszbDgNRR0PfIizHHxbLY7288kjwEPw" + "pVsYjY67VYy4XTjTNP18F1dDox0YbN4zISy1Kv884bEpQBgRjXyEpwpy1obE" + "AxnIByl6ypUM2Zafq9AKUJsCRtMIPWakXUGfnHy9iUsiGSa6q6Jew1XpMgs7" + "AAICB/0Xv+ckcNrInekFVNNVKraDlYpRcyDHEYpO85qGJVFxs7TfDSkoCQfz" + "kI5qRV97nqwxilZGXfpp2M2go7FpyKjDvgPVHmydj+G/+QFc8GTOjhQyRsA0" + "hVpnQhycun6uSRdwNVtEKJtl/wV8JjXNdup3rzRS0SBFu/UPzAUGp8y3uQuy" + "5/0WcjDq8rgNTTrPlkODblEcaazBoPJjozA0YKsoZsd/0j9Pswy6EYX+KfxR" + "TyG/y5EQ6Ox46qSUbf+ewjWEP8x1QLt/NeIxE7hG9qEuh5c65oOQxgAt0mTm" + "eY24IvVg+lsUa20jdewrtSs/8WF3w0Po2ujAKqs3qR524r64/gkDAmmp39NN" + "U2pqYHokufIOab2VpD7iQo8UjHZNwR6dpjyky9dVfIe4MA0H+t0ju8UDdWoe" + "IkRu8guWsI83mjGPbIq8lmsZOXPCA8hPuBmL0iaj8TnuotmsBjIBsAGHiQBM" + "BBgRAgAMBQJAbX1vBRsMAAAAAAoJEKXQf/RT99uYL/QAnivXK/K7ip85eUOC" + "ZW4Ky8cVajreAJ9EisIHYm/83VyCmarQvwsYczsb8rABZ5UDqARAbX2jAQgA" + "ydq8tipHt99oM9tur6VBm8sIr/e4DRCXKeA3JNqwNbRYLX+vLLZ3HvKk44KJ" + "yOc9h+Dcs/lORgAagyPEfn7HMzrF85H7z8TArXM3cDn5f89IEOViND10RUqu" + "+9zuIw6n7UrVUx/hSDxhqHbY63h4sY/QdEJeK/m+B0E2wCX+5ecEm4NhCYus" + "SeKqr/pTEkcofFmhL/mnXcKrs18oHUIkK4ldoIRNbZ2j5wOk3qvSW2QX+v4R" + "L7YvuPHKgdy9DhiismgMyUA3rGkhlDx01pNg/+czH+kNLeyFTNtT5Rg9Cut4" + "kswXWkP5hY/kxMpplOj5T+o+MMUZxp0ieE/G+HfWywARAQABCWEWL2cKQKcm" + "XFTNsWgRoOcOkKyJ/osERh2PzNWvOF6/ir1BMRsg0qhd+hEcoWHaT+7Vt12i" + "5Y2Ogm2HFrVrS5/DlV/rw0mkALp/3cR6jLOPyhmq7QGwhG27Iy++pLIksXQa" + "RTboa7ZasEWw8zTqa4w17M5Ebm8dtB9Mwl/kqU9cnIYnFXj38BWeia3iFBNG" + "PD00hqwhPUCTUAcH9qQPSqKqnFJVPe0KQWpq78zhCh1zPUIa27CE86xRBf45" + "XbJwN+LmjCuQEnSNlloXJSPTRjEpla+gWAZz90fb0uVIR1dMMRFxsuaO6aCF" + "QMN2Mu1wR/xzTzNCiQf8cVzq7YkkJD8ChJvu/4BtWp3BlU9dehAz43mbMhaw" + "Qx3NmhKR/2dv1cJy/5VmRuljuzC+MRtuIjJ+ChoTa9ubNjsT6BF5McRAnVzf" + "raZK+KVWCGA8VEZwe/K6ouYLsBr6+ekCKIkGZdM29927m9HjdFwEFjnzQlWO" + "NZCeYgDcK22v7CzobKjdo2wdC7XIOUVCzMWMl+ch1guO/Y4KVuslfeQG5X1i" + "PJqV+bwJriCx5/j3eE/aezK/vtZU6cchifmvefKvaNL34tY0Myz2bOx44tl8" + "qNcGZbkYF7xrNCutzI63xa2ruN1p3hNxicZV1FJSOje6+ITXkU5Jmufto7IJ" + "t/4Q2dQefBQ1x/d0EdX31yK6+1z9dF/k3HpcSMb5cAWa2u2g4duAmREHc3Jz" + "lHCsNgyzt5mkb6kS43B6og8Mm2SOx78dBIOA8ANzi5B6Sqk3/uN5eQFLY+sQ" + "qGxXzimyfbMjyq9DdqXThx4vlp3h/GC39KxL5MPeB0oe6P3fSP3C2ZGjsn3+" + "XcYk0Ti1cBwBOFOZ59WYuc61B0wlkiU/WGeaebABh7QuU2FuZGh5YSBQdWxs" + "YWJob3RsYSA8cHNhbmRoeWFAbXlqYXZhd29ybGQuY29tPrADA///iQEtBBAB" + "AgAXBQJAbX2jBwsJCAcDAgoCGQEFGwMAAAAACgkQx87DL9gOvoeVUwgAkQXY" + "iF0CxhKbDnuabAssnOEwJrutgCROCJRQvIwTe3fe6hQaWn2Yowt8OQtNFiR8" + "GfAY6EYxyFLKzZbAI/qtq5fHmN3eRSyNWe6d6e17hqZZL7kf2sVkyGTChHj7" + "Jiuo7vWkdqT2MJN6BW5tS9CRH7MeD839STv+4mAAO9auGvSvicP6UEQikAyC" + "y/ihoJxLQlspfbSNpi0vrUjCPT7NtWwfP0qF64i9LYkjzLqihnu+UareqOPh" + "XcWnyFKrjmg4ezQkweNU2pdvCLbcW24FhT92ivHgpLyWTswXcqjhFjVlRr0+" + "2sIz7v1k0budCsJ7PjzOoH0hJxCvsJQMlZR/e7ABZ50DqARAbX2kAQgAm5j+" + "/LO2M4pKm/VUPkYuj3eefHkzjM6nKbvRZX1Oqyf+6CJTxQskUWKAtkzzKafP" + "dS5Wg0CMqeXov+EFod4bPEYccszncKd1U8NRwacbEpCvvvB84Yl2YwdWpDpk" + "ryyyLI4PbCHkeuwx9Dc2z7t4XDB6FyAJTMAkia7nzYa/kbeUO3c2snDb/dU7" + "uyCsyKtTZyTyhTgtl/f9L03Bgh95y3mOUz0PimJ0Sg4ANczF4d04BpWkjLNV" + "Ji489ifWodPlHm1hag5drYekYpWJ+3g0uxs5AwayV9BcOkPKb1uU3EoYQw+n" + "n0Kn314Nvx2M1tKYunuVNLEm0PhA/+B8PTq8BQARAQABCXo6bD6qi3s4U8Pp" + "Uf9l3DyGuwiVPGuyb2P+sEmRFysi2AvxMe9CkF+CLCVYfZ32H3Fcr6XQ8+K8" + "ZGH6bJwijtV4QRnWDZIuhUQDS7dsbGqTh4Aw81Fm0Bz9fpufViM9RPVEysxs" + "CZRID+9jDrACthVsbq/xKomkKdBfNTK7XzGeZ/CBr9F4EPlnBWClURi9txc0" + "pz9YP5ZRy4XTFgx+jCbHgKWUIz4yNaWQqpSgkHEDrGZwstXeRaaPftcfQN+s" + "EO7OGl/Hd9XepGLez4vKSbT35CnqTwMzCK1IwUDUzyB4BYEFZ+p9TI18HQDW" + "hA0Wmf6E8pjS16m/SDXoiRY43u1jUVZFNFzz25uLFWitfRNHCLl+VfgnetZQ" + "jMFr36HGVQ65fogs3avkgvpgPwDc0z+VMj6ujTyXXgnCP/FdhzgkRFJqgmdJ" + "yOlC+wFmZJEs0MX7L/VXEXdpR27XIGYm24CC7BTFKSdlmR1qqenXHmCCg4Wp" + "00fV8+aAsnesgwPvxhCbZQVp4v4jqhVuB/rvsQu9t0rZnKdDnWeom/F3StYo" + "A025l1rrt0wRP8YS4XlslwzZBqgdhN4urnzLH0/F3X/MfjP79Efj7Zk07vOH" + "o/TPjz8lXroPTscOyXWHwtQqcMhnVsj9jvrzhZZSdUuvnT30DR7b8xcHyvAo" + "WG2cnF/pNSQX11RlyyAOlw9TOEiDJ4aLbFdkUt+qZdRKeC8mEC2xsQ87HqFR" + "pWKWABWaoUO0nxBEmvNOy97PkIeGVFNHDLlIeL++Ry03+JvuNNg4qAnwacbJ" + "TwQzWP4vJqre7Gl/9D0tVlD4Yy6Xz3qyosxdoFpeMSKHhgKVt1bk0SQP7eXA" + "C1c+eDc4gN/ZWpl+QLqdk2T9vr4wRAaK5LABh4kBIgQYAQIADAUCQG19pAUb" + "DAAAAAAKCRDHzsMv2A6+h5C6B/0QWPJb1L9a/CHU7Of3zfHvzJxnk4S5fia5" + "WBf+Ld7Y12CH+cVI/3PTXY63imIB3zLa21TNPC5cVFUJZI7hdwyJOW1R/QZa" + "vGl5sosIjORqwq8vs1oqpKWc3tRue+wt/JjCWxw8G6jQiwCzM6PltqtOAL5e" + "bJ4jZwzRmxs/RI4UYKO6EteipJA+i7OEZx0xGdL8mTl6HQx7vrJP9pM4/CtO" + "5CmjPK70e2gyoiOxx9RsSc+9H59YJCrldogCCIlNuW7cvkt8K/uYdN9GAbFG" + "RdanignRjpqSu3vTn8r/VO63+meZfKvmpI6i2b3o/UZ8Xh9lJu1vrRoNpnuP" + "Nifs+ljmsAFn"); private static readonly char[] sec2pass1 = "sandhya".ToCharArray(); private static readonly char[] sec2pass2 = "psai".ToCharArray(); private static readonly byte[] pub3 = Base64.Decode( "mQGiBEB9BH0RBACtYQtE7tna6hgGyGLpq+ds3r2cLC0ISn5dNw7tm9vwiNVF" + "JA2N37RRrifw4PvgelRSvLaX3M3ZBqC9s1Metg3v4FSlIRtSLWCNpHSvNw7i" + "X8C2Xy9Hdlbh6Y/50o+iscojLRE14upfR1bIkcCZQGSyvGV52V2wBImUUZjV" + "s2ZngwCg7mu852vK7+euz4WaL7ERVYtq9CMEAJ5swrljerDpz/RQ4Lhp6KER" + "KyuI0PUttO57xINGshEINgYlZdGaZHRueHe7uKfI19mb0T4N3NJWaZ0wF+Cn" + "rixsq0VrTUfiwfZeGluNG73aTCeY45fVXMGTTSYXzS8T0LW100Xn/0g9HRyA" + "xUpuWo8IazxkMqHJis2uwriYKpAfA/9anvj5BS9p5pfPjp9dGM7GTMIYl5f2" + "fcP57f+AW1TVR6IZiMJAvAdeWuLtwLnJiFpGlnFz273pfl+sAuqm1yNceImR" + "2SDDP4+vtyycWy8nZhgEuhZx3W3cWMQz5WyNJSY1JJHh9TCQkCoN8E7XpVP4" + "zEPboB2GzD93mfD8JLHP+7QtVGVzdCBLZXkgKG5vIGNvbW1lbnQpIDx0ZXN0" + "QGJvdW5jeWNhc3RsZS5vcmc+iFkEExECABkFAkB9BH0ECwcDAgMVAgMDFgIB" + "Ah4BAheAAAoJEKnMV8vjZQOpSRQAnidAQswYkrXQAFcLBzhxQTknI9QMAKDR" + "ryV3l6xuCCgHST8JlxpbjcXhlLACAAPRwXPBcQEQAAEBAAAAAAAAAAAAAAAA" + "/9j/4AAQSkZJRgABAQEASABIAAD//gAXQ3JlYXRlZCB3aXRoIFRoZSBHSU1Q" + "/9sAQwAIBgYHBgUIBwcHCQkICgwUDQwLCwwZEhMPFB0aHx4dGhwcICQuJyAi" + "LCMcHCg3KSwwMTQ0NB8nOT04MjwuMzQy/9sAQwEJCQkMCwwYDQ0YMiEcITIy" + "MjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIy" + "MjIy/8AAEQgAFAAUAwEiAAIRAQMRAf/EABoAAQACAwEAAAAAAAAAAAAAAAAE" + "BQIDBgf/xAAoEAABAgUDBAEFAAAAAAAAAAABAgMABBEhMQUSQQYTIiNhFFGB" + "kcH/xAAXAQEAAwAAAAAAAAAAAAAAAAAEAgMF/8QAJBEAAQQAAwkAAAAAAAAA" + "AAAAAQACERIEIfATMTJBUZGx0fH/2gAMAwEAAhEDEQA/APMuotJlJVxstqaP" + "o22NlAUp+YsNO0qSUtBcMu6n6EtOHcfPAHHFI16++oajQtTA3DapK02HFR8U" + "pE9pTbQWtKm2WG2rlxVyQTcfGbn7Qm0OIjL77Wrs2NNm9lzTmmSxQ0PX4opS" + "prk5tmESF6syggzGwOLG6gXgHFbZhBixk8XlIDcOQLRKt+rX+3qC5ZLTQblp" + "Qlvwvxn9CMpZturVGkJHapQJphRH8hCLXbzrqpYsCx1zC5rtpJNuYQhASc0U" + "AQv/2YhcBBMRAgAcBQJAfQV+AhsDBAsHAwIDFQIDAxYCAQIeAQIXgAAKCRCp" + "zFfL42UDqfa2AJ9hjtEeDTbTEAuuSbzhYFxN/qc0FACgsmzysdbBpuN65yK0" + "1tbEaeIMtqCwAgADuM0EQH0EfhADAKpG5Y6vGbm//xZYG08RRmdi67dZjF59" + "Eqfo43mRrliangB8qkqoqqf3za2OUbXcZUQ/ajDXUvjJAoY2b5XJURqmbtKk" + "wPRIeD2+wnKABat8wmcFhZKATX1bqjdyRRGxawADBgMAoMJKJLELdnn885oJ" + "6HDmIez++ZWTlafzfUtJkQTCRKiE0NsgSvKJr/20VdK3XUA/iy0m1nQwfzv/" + "okFuIhEPgldzH7N/NyEvtN5zOv/TpAymFKewAQ26luEu6l+lH4FsiEYEGBEC" + "AAYFAkB9BH4ACgkQqcxXy+NlA6mtMgCgtQMFBaKymktM+DQmCgy2qjW7WY0A" + "n3FaE6UZE9GMDmCIAjhI+0X9aH6CsAIAAw=="); private static readonly byte[] sec3 = Base64.Decode( "lQHhBEB9BH0RBACtYQtE7tna6hgGyGLpq+ds3r2cLC0ISn5dNw7tm9vwiNVF" + "JA2N37RRrifw4PvgelRSvLaX3M3ZBqC9s1Metg3v4FSlIRtSLWCNpHSvNw7i" + "X8C2Xy9Hdlbh6Y/50o+iscojLRE14upfR1bIkcCZQGSyvGV52V2wBImUUZjV" + "s2ZngwCg7mu852vK7+euz4WaL7ERVYtq9CMEAJ5swrljerDpz/RQ4Lhp6KER" + "KyuI0PUttO57xINGshEINgYlZdGaZHRueHe7uKfI19mb0T4N3NJWaZ0wF+Cn" + "rixsq0VrTUfiwfZeGluNG73aTCeY45fVXMGTTSYXzS8T0LW100Xn/0g9HRyA" + "xUpuWo8IazxkMqHJis2uwriYKpAfA/9anvj5BS9p5pfPjp9dGM7GTMIYl5f2" + "fcP57f+AW1TVR6IZiMJAvAdeWuLtwLnJiFpGlnFz273pfl+sAuqm1yNceImR" + "2SDDP4+vtyycWy8nZhgEuhZx3W3cWMQz5WyNJSY1JJHh9TCQkCoN8E7XpVP4" + "zEPboB2GzD93mfD8JLHP+/4DAwIvYrn+YqRaaGAu19XUj895g/GROyP8WEaU" + "Bd/JNqWc4kE/0guetGnPzq7G3bLVwiKfFd4X7BrgHAo3mrQtVGVzdCBLZXkg" + "KG5vIGNvbW1lbnQpIDx0ZXN0QGJvdW5jeWNhc3RsZS5vcmc+iFkEExECABkF" + "AkB9BH0ECwcDAgMVAgMDFgIBAh4BAheAAAoJEKnMV8vjZQOpSRQAoKZy6YS1" + "irF5/Q3JlWiwbkN6dEuLAJ9lldRLOlXsuQ5JW1+SLEc6K9ho4rACAADRwXPB" + "cQEQAAEBAAAAAAAAAAAAAAAA/9j/4AAQSkZJRgABAQEASABIAAD//gAXQ3Jl" + "YXRlZCB3aXRoIFRoZSBHSU1Q/9sAQwAIBgYHBgUIBwcHCQkICgwUDQwLCwwZ" + "EhMPFB0aHx4dGhwcICQuJyAiLCMcHCg3KSwwMTQ0NB8nOT04MjwuMzQy/9sA" + "QwEJCQkMCwwYDQ0YMiEcITIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIy" + "MjIyMjIyMjIyMjIyMjIyMjIyMjIy/8AAEQgAFAAUAwEiAAIRAQMRAf/EABoA" + "AQACAwEAAAAAAAAAAAAAAAAEBQIDBgf/xAAoEAABAgUDBAEFAAAAAAAAAAAB" + "AgMABBEhMQUSQQYTIiNhFFGBkcH/xAAXAQEAAwAAAAAAAAAAAAAAAAAEAgMF" + "/8QAJBEAAQQAAwkAAAAAAAAAAAAAAQACERIEIfATMTJBUZGx0fH/2gAMAwEA" + "AhEDEQA/APMuotJlJVxstqaPo22NlAUp+YsNO0qSUtBcMu6n6EtOHcfPAHHF" + "I16++oajQtTA3DapK02HFR8UpE9pTbQWtKm2WG2rlxVyQTcfGbn7Qm0OIjL7" + "7Wrs2NNm9lzTmmSxQ0PX4opSprk5tmESF6syggzGwOLG6gXgHFbZhBixk8Xl" + "IDcOQLRKt+rX+3qC5ZLTQblpQlvwvxn9CMpZturVGkJHapQJphRH8hCLXbzr" + "qpYsCx1zC5rtpJNuYQhASc0UAQv/2YhcBBMRAgAcBQJAfQV+AhsDBAsHAwID" + "FQIDAxYCAQIeAQIXgAAKCRCpzFfL42UDqfa2AJ9hjtEeDTbTEAuuSbzhYFxN" + "/qc0FACgsmzysdbBpuN65yK01tbEaeIMtqCwAgAAnQEUBEB9BH4QAwCqRuWO" + "rxm5v/8WWBtPEUZnYuu3WYxefRKn6ON5ka5Ymp4AfKpKqKqn982tjlG13GVE" + "P2ow11L4yQKGNm+VyVEapm7SpMD0SHg9vsJygAWrfMJnBYWSgE19W6o3ckUR" + "sWsAAwYDAKDCSiSxC3Z5/POaCehw5iHs/vmVk5Wn831LSZEEwkSohNDbIEry" + "ia/9tFXSt11AP4stJtZ0MH87/6JBbiIRD4JXcx+zfzchL7Teczr/06QMphSn" + "sAENupbhLupfpR+BbP4DAwIvYrn+YqRaaGBjvFK1fbxCt7ZM4I2W/3BC0lCX" + "m/NypKNspGflec8u96uUlA0fNCnxm6f9nbB0jpvoKi0g4iqAf+P2iEYEGBEC" + "AAYFAkB9BH4ACgkQqcxXy+NlA6mtMgCgvccZA/Sg7BXVpxli47SYhxSHoM4A" + "oNCOMplSnYTuh5ikKeBWtz36gC1psAIAAA=="); private static readonly char[] sec3pass1 = "123456".ToCharArray(); // // GPG comment packets. // private static readonly byte[] sec4 = Base64.Decode( "lQG7BD0PbK8RBAC0cW4Y2MZXmAmqYp5Txyw0kSQsFvwZKHNMFRv996IsN57URVF5" + "BGMVPRBi9dNucWbjiSYpiYN13wE9IuLZsvVaQojV4XWGRDc+Rxz9ElsXnsYQ3mZU" + "7H1bNQEofstChk4z+dlvPBN4GFahrIzn/CeVUn6Ut7dVdYbiTqviANqNXwCglfVA" + "2OEePvqFnGxs1jhJyPSOnTED/RwRvsLH/k43mk6UEvOyN1RIpBXN+Ieqs7h1gFrQ" + "kB+WMgeP5ZUsotTffVDSUS9UMxRQggVUW1Xml0geGwQsNfkr/ztWMs/T4xp1v5j+" + "QyJx6OqNlkGdqOsoqkzJx0SQ1zBxdinFyyC4H95SDAb/RQOu5LQmxFG7quexztMs" + "infEA/9cVc9+qCo92yRAaXRqKNVVQIQuPxeUsGMyVeJQvJBD4An8KTMCdjpF10Cp" + "qA3t+n1S0zKr5WRUtvS6y60MOONO+EJWVWBNkx8HJDaIMNkfoqQoz3Krn7w6FE/v" + "/5uwMd6jY3N3yJZn5nDZT9Yzv9Nx3j+BrY+henRlSU0c6xDc9QAAnjJYg0Z83VJG" + "6HrBcgc4+4K6lHulCqH9JiM6RFNBX2ZhY3RvcjoAAK9hV206agp99GI6x5qE9+pU" + "vs6O+Ich/SYjOkRTQV9mYWN0b3I6AACvYAfGn2FGrpBYbjnpTuFOHJMS/T5xg/0m" + "IzpEU0FfZmFjdG9yOgAAr0dAQz6XxMwxWIn8xIZR/v2iN2L9C6O0EkZvbyBCYXIg" + "PGJhekBxdXV4PohXBBMRAgAXBQI9D2yvBQsHCgMEAxUDAgMWAgECF4AACgkQUGLI" + "YCIktfoGogCfZiXMJUKrScqozv5tMwzTTk2AaT8AniM5iRr0Du/Y08SL/NMhtF6H" + "hJ89nO4EPQ9ssRADAI6Ggxj6ZBfoavuXd/ye99osW8HsNlbqhXObu5mCMNySX2wa" + "HoWyRUEaUkI9eQw+MlHzIwzA32E7y2mU3OQBKdgLcBg4jxtcWVEg8ESKF9MpFXxl" + "pExxWrr4DFBfCRcsTwAFEQL9G3OvwJuEZXgx2JSS41D3pG4/qiHYICVa0u3p/14i" + "cq0kXajIk5ZJ6frCIAHIzuQ3n7jjzr05yR8s/qCrNbBA+nlkVNa/samk+jCzxxxa" + "cR/Dbh2wkvTFuDFFETwQYLuZAADcDck4YGQAmHivVT2NNDCf/aTz0+CJWl+xRc2l" + "Qw7D/SQjOkVMR19mYWN0b3I6AACbBnv9m5/bb/pjYAm2PtDp0CysQ9X9JCM6RUxH" + "X2ZhY3RvcjoAAJsFyHnSmaWguTFf6lJ/j39LtUNtmf0kIzpFTEdfZmFjdG9yOgAA" + "mwfwMD3LxmWtuCWBE9BptWMNH07Z/SQjOkVMR19mYWN0b3I6AACbBdhBrbSiM4UN" + "y7khDW2Sk0e4v9mIRgQYEQIABgUCPQ9ssQAKCRBQYshgIiS1+jCMAJ9txwHnb1Kl" + "6i/fSoDs8SkdM7w48wCdFvPEV0sSxE73073YhBgPZtMWbBo="); // // PGP freeware version 7 // private static readonly byte[] pub5 = Base64.Decode( "mQENBEBrBE4BCACjXVcNIFDQSofaIyZnALb2CRg+WY9uUqgHEEAOlPe03Cs5STM5" + "HDlNmrh4TdFceJ46rxk1mQOjULES1YfHay8lCIzrD7FX4oj0r4DC14Fs1vXaSar2" + "1szIpttOw3obL4A1e0p6N4jjsoG7N/pA0fEL0lSw92SoBrMbAheXRg4qNTZvdjOR" + "grcuOuwgJRvPLtRXlhyLBoyhkd5mmrIDGv8QHJ/UjpeIcRXY9kn9oGXnEYcRbMaU" + "VwXB4pLzWqz3ZejFI3lOxRWjm760puPOnGYlzSVBxlt2LgzUgSj1Mn+lIpWmAzsa" + "xEiU4xUwEomQns72yYRZ6D3euNCibcte4SeXABEBAAG0KXBhbGFzaCBrYXNvZGhh" + "biA8cGthc29kaGFuQHRpYWEtY3JlZi5vcmc+iQEuBBABAgAYBQJAawROCAsBAwkI" + "BwIKAhkBBRsDAAAAAAoJEOfelumuiOrYqPEH+wYrdP5Tq5j+E5yN1pyCg1rwbSOt" + "Dka0y0p7Oq/VIGLk692IWPItLEunnBXQtGBcWqklrvogvlhxtf16FgoyScfLJx1e" + "1cJa+QQnVuH+VOESN6iS9Gp9lUfVOHv74mEMXw0l2Djfy/lnrkAMBatggyGnF9xF" + "VXOLk1J2WVFm9KUE23o6qdB7RGkf31pN2eA7SWmkdJSkUH7o/QSFBI+UTRZ/IY5P" + "ZIJpsdiIOqd9YMG/4RoSZuPqNRR6x7BSs8nQVR9bYs4PPlp4GfdRnOcRonoTeJCZ" + "83RnsraWJnJTg34gRLBcqumhTuFKc8nuCNK98D6zkQESdcHLLTquCOaF5L+5AQ0E" + "QGsETwEIAOVwNCTaDZvW4dowPbET1bI5UeYY8rAGLYsWSUfgaFv2srMiApyBVltf" + "i6OLcPjcUCHDBjCv4pwx/C4qcHWb8av4xQIpqQXOpO9NxYE1eZnel/QB7DtH12ZO" + "nrDNmHtaXlulcKNGe1i1utlFhgzfFx6rWkRL0ENmkTkaQmPY4gTGymJTUhBbsSRq" + "2ivWqQA1TPwBuda73UgslIAHRd/SUaxjXoLpMbGOTeqzcKGjr5XMPTs7/YgBpWPP" + "UxMlEQIiU3ia1bxpEhx05k97ceK6TSH2oCPQA7gumjxOSjKT+jEm+8jACVzymEmc" + "XRy4D5Ztqkw/Z16pvNcu1DI5m6xHwr8AEQEAAYkBIgQYAQIADAUCQGsETwUbDAAA" + "AAAKCRDn3pbprojq2EynB/4/cEOtKbI5UisUd3vkTzvWOcqWUqGqi5wjjioNtIM5" + "pur2nFvhQE7SZ+PbAa87HRJU/4WcWMcoLkHD48JrQwHCHOLHSV5muYowb78X4Yh9" + "epYtSJ0uUahcn4Gp48p4BkhgsPYXkxEImSYzAOWStv21/7WEMqItMYl89BV6Upm8" + "HyTJx5MPTDbMR7X51hRg3OeQs6po3WTCWRzFIMyGm1rd/VK1L5ZDFPqO3S6YUJ0z" + "cxecYruvfK0Wp7q834wE8Zkl/PQ3NhfEPL1ZiLr/L00Ty+77/FZqt8SHRCICzOfP" + "OawcVGI+xHVXW6lijMpB5VaVIH8i2KdBMHXHtduIkPr9"); private static readonly byte[] sec5 = Base64.Decode( "lQOgBEBrBE4BCACjXVcNIFDQSofaIyZnALb2CRg+WY9uUqgHEEAOlPe03Cs5STM5" + "HDlNmrh4TdFceJ46rxk1mQOjULES1YfHay8lCIzrD7FX4oj0r4DC14Fs1vXaSar2" + "1szIpttOw3obL4A1e0p6N4jjsoG7N/pA0fEL0lSw92SoBrMbAheXRg4qNTZvdjOR" + "grcuOuwgJRvPLtRXlhyLBoyhkd5mmrIDGv8QHJ/UjpeIcRXY9kn9oGXnEYcRbMaU" + "VwXB4pLzWqz3ZejFI3lOxRWjm760puPOnGYlzSVBxlt2LgzUgSj1Mn+lIpWmAzsa" + "xEiU4xUwEomQns72yYRZ6D3euNCibcte4SeXABEBAAEB8wqP7JkKN6oMNi1xJNqU" + "vvt0OV4CCnrIFiOPCjebjH/NC4T/9pJ6BYSjYdo3VEPNhPhRS9U3071Kqbdt35J5" + "kmzMq1yNStC1jkxHRCNTMsb1yIEY1v+fv8/Cy+tBpvAYiJKaox8jW3ppi9vTHZjW" + "tYYq0kwAVojMovz1O3wW/pEF69UPBmPYsze+AHA1UucYYqdWO8U2tsdFJET/hYpe" + "o7ppHJJCdqWzeiE1vDUrih9pP3MPpzcRS/gU7HRDb5HbfP7ghSLzByEa+2mvg5eK" + "eLwNAx2OUtrVg9rJswXX7DOLa1nKPhdGrSV/qwuK4rBdaqJ/OvszVJ0Vln0T/aus" + "it1PAuVROLUPqTVVN8/zkMenFbf5vtryC3GQYXvvZq+l3a4EXwrR/1pqrTfnfOuD" + "GwlFhRJAqPfthxZS68/xC8qAmTtkl7j4nscNM9kSoZ3BFwSyD9B/vYHPWGlqnpGF" + "k/hBXuIgl07KIeNIyEC3f1eRyaiMFqEz5yXbbTfEKirSVpHM/mpeKxG8w96aK3Je" + "AV0X6ZkC4oLTp6HCG2TITUIeNxCh2rX3fhr9HvBDXBbMHgYlIcLwzNkwDX74cz/7" + "nIclcubaWjEkDHP20XFicuChFc9zx6kBYuYy170snltTBgTWSuRH15W4NQqrLo37" + "zyzZQubX7CObgQJu4ahquiOg4SWl6uEI7+36U0SED7sZzw8ns1LxrwOWbXuHie1i" + "xCvsJ4RpJJ03iEdNdUIb77qf6AriqE92tXzcVXToBv5S2K5LdFYNJ1rWdwaKJRkt" + "kmjCL67KM9WT/IagsUyU+57ao3COtqw9VWZi6ev+ubM6fIV0ZK46NEggOLph1hi2" + "gZ9ew9uVuruYg7lG2Ku82N0fjrQpcGFsYXNoIGthc29kaGFuIDxwa2Fzb2RoYW5A" + "dGlhYS1jcmVmLm9yZz6dA6AEQGsETwEIAOVwNCTaDZvW4dowPbET1bI5UeYY8rAG" + "LYsWSUfgaFv2srMiApyBVltfi6OLcPjcUCHDBjCv4pwx/C4qcHWb8av4xQIpqQXO" + "pO9NxYE1eZnel/QB7DtH12ZOnrDNmHtaXlulcKNGe1i1utlFhgzfFx6rWkRL0ENm" + "kTkaQmPY4gTGymJTUhBbsSRq2ivWqQA1TPwBuda73UgslIAHRd/SUaxjXoLpMbGO" + "TeqzcKGjr5XMPTs7/YgBpWPPUxMlEQIiU3ia1bxpEhx05k97ceK6TSH2oCPQA7gu" + "mjxOSjKT+jEm+8jACVzymEmcXRy4D5Ztqkw/Z16pvNcu1DI5m6xHwr8AEQEAAQF7" + "osMrvQieBAJFYY+x9jKPVclm+pVaMaIcHKwCTv6yUZMqbHNRTfwdCVKTdAzdlh5d" + "zJNXXRu8eNwOcfnG3WrWAy59cYE389hA0pQPOh7iL2V1nITf1qdLru1HJqqLC+dy" + "E5GtkNcgvQYbv7ACjQacscvnyBioYC6TATtPnHipMO0S1sXEnmUugNlW88pDln4y" + "VxCtQXMBjuqMt0bURqmb+RoYhHhoCibo6sexxSnbEAPHBaW1b1Rm7l4UBSW6S5U0" + "MXURE60IHfP1TBe1l/xOIxOi8qdBQCyaFW2up00EhRBy/WOO6KAYXQrRRpOs9TBq" + "ic2wquwZePmErTbIttnnBcAKmpodrM/JBkn/we5fVg+FDTP8sM/Ubv0ZuM70aWmF" + "v0/ZKbkCkh2YORLWl5+HR/RKShdkmmFgZZ5uzbOGxxEGKhw+Q3+QFUF7PmYOnOtv" + "s9PZE3dV7ovRDoXIjfniD1+8sLUWwW5d+3NHAQnCHJrLnPx4sTHx6C0yWMcyZk6V" + "fNHpLK4xDTbgoTmxJa/4l+wa0iD69h9K/Nxw/6+X/GEM5w3d/vjlK1Da6urN9myc" + "GMsfiIll5DNIWdLLxCBPFmhJy653CICQLY5xkycWB7JOZUBTOEVrYr0AbBZSTkuB" + "fq5p9MfH4N51M5TWnwlJnqEiGnpaK+VDeP8GniwCidTYyiocNPvghvWIzG8QGWMY" + "PFncRpjFxmcY4XScYYpyRme4qyPbJhbZcgGpfeLvFKBPmNxVKJ2nXTdx6O6EbHDj" + "XctWqNd1EQas7rUN728u7bk8G7m37MGqQuKCpNvOScH4TnPROBY8get0G3bC4mWz" + "6emPeENnuyElfWQiHEtCZr1InjnNbb/C97O+vWu9PfsE"); private static readonly char[] sec5pass1 = "12345678".ToCharArray(); // // Werner Koch "odd keys" // private static readonly byte[] pub6 = Base64.Decode( "mQGiBDWiHh4RBAD+l0rg5p9rW4M3sKvmeyzhs2mDxhRKDTVVUnTwpMIR2kIA9pT4" + "3No/coPajDvhZTaDM/vSz25IZDZWJ7gEu86RpoEdtr/eK8GuDcgsWvFs5+YpCDwW" + "G2dx39ME7DN+SRvEE1xUm4E9G2Nnd2UNtLgg82wgi/ZK4Ih9CYDyo0a9awCgisn3" + "RvZ/MREJmQq1+SjJgDx+c2sEAOEnxGYisqIKcOTdPOTTie7o7x+nem2uac7uOW68" + "N+wRWxhGPIxsOdueMIa7U94Wg/Ydn4f2WngJpBvKNaHYmW8j1Q5zvZXXpIWRXSvy" + "TR641BceGHNdYiR/PiDBJsGQ3ac7n7pwhV4qex3IViRDJWz5Dzr88x+Oju63KtxY" + "urUIBACi7d1rUlHr4ok7iBRlWHYXU2hpUIQ8C+UOE1XXT+HB7mZLSRONQnWMyXnq" + "bAAW+EUUX2xpb54CevAg4eOilt0es8GZMmU6c0wdUsnMWWqOKHBFFlDIvyI27aZ9" + "quf0yvby63kFCanQKc0QnqGXQKzuXbFqBYW2UQrYgjXji8rd8bQnV2VybmVyIEtv" + "Y2ggKGdudXBnIHNpZykgPGRkOWpuQGdudS5vcmc+iGUEExECAB0FAjZVoKYFCQht" + "DIgDCwQDBRUDAgYBAxYCAQIXgAASCRBot6uJV1SNzQdlR1BHAAEBLj4AoId15gcy" + "YpBX2YLtEQTlXPp3mtEGAJ9UxzJE/t3EHCHK2bAIOkBwIW8ItIkBXwMFEDWiHkMD" + "bxG4/z6qCxADYzIFHR6I9Si9gzPQNRcFs2znrTp5pV5Mk6f1aqRgZxL3E4qUZ3xe" + "PQhwAo3fSy3kCwLmFGqvzautSMHn8K5V1u+T5CSHqLFYKqj5FGtuB/xwoKDXH6UO" + "P0+l5IP8H1RTjme3Fhqahec+zPG3NT57vc2Ru2t6PmuAwry2BMuSFMBs7wzXkyC3" + "DbI54MV+IKPjHMORivK8uI8jmna9hdNVyBifCk1GcxkHBSCFvU8xJePsA/Q//zCe" + "lvrnrIiMfY4CQTmKzke9MSzbAZQIRddgrGAsiX1tE8Z3YMd8lDpuujHLVEdWZo6s" + "54OJuynHrtFFObdapu0uIrT+dEXSASMUbEuNCLL3aCnrEtGJCwxB2TPQvCCvR2BK" + "zol6MGWxA+nmddeQib2r+GXoKXLdnHcpsAjA7lkXk3IFyJ7MLFK6uDrjGbGJs2FK" + "SduUjS/Ib4hGBBARAgAGBQI1oic8AAoJEGx+4bhiHMATftYAn1fOaKDUOt+dS38r" + "B+CJ2Q+iElWJAKDRPpp8q5GylbM8DPlMpClWN3TYqYhGBBARAgAGBQI27U5sAAoJ" + "EF3iSZZbA1iiarYAn35qU3ZOlVECELE/3V6q98Q30eAaAKCtO+lacH0Qq1E6v4BP" + "/9y6MoLIhohiBBMRAgAiAhsDBAsHAwIDFQIDAxYCAQIeAQIXgAUCP+mCaQUJDDMj" + "ywAKCRBot6uJV1SNzaLvAJwLsPV1yfc2D+yT+2W11H/ftNMDvwCbBweORhCb/O/E" + "Okg2UTXJBR4ekoCIXQQTEQIAHQMLBAMFFQMCBgEDFgIBAheABQI/6YJzBQkMMyPL" + "AAoJEGi3q4lXVI3NgroAn2Z+4KgVo2nzW72TgCJwkAP0cOc2AJ0ZMilsOWmxmEG6" + "B4sHMLkB4ir4GIhdBBMRAgAdAwsEAwUVAwIGAQMWAgECF4AFAj/pgnMFCQwzI8sA" + "CgkQaLeriVdUjc2CugCfRrOIfllp3mSmGpHgIxvg5V8vtMcAn0BvKVehOn+12Yvn" + "9BCHfg34jUZbiF0EExECAB0DCwQDBRUDAgYBAxYCAQIXgAUCP+mCcwUJDDMjywAK" + "CRBot6uJV1SNzYK6AJ9x7R+daNIjkieNW6lJeVUIoj1UHgCeLZm025uULML/5DFs" + "4tUvXs8n9XiZAaIENaIg8xEEALYPe0XNsPjx+inTQ+Izz527ZJnoc6BhWik/4a2b" + "ZYENSOQXAMKTDQMv2lLeI0i6ceB967MNubhHeVdNeOWYHFSM1UGRfhmZERISho3b" + "p+wVZvVG8GBVwpw34PJjgYU/0tDwnJaJ8BzX6j0ecTSTjQPnaUEtdJ/u/gmG9j02" + "18TzAKDihdNoKJEU9IKUiSjdGomSuem/VwQArHfaucSiDmY8+zyZbVLLnK6UJMqt" + "sIv1LvAg20xwXoUk2bY8H3tXL4UZ8YcoSXYozwALq3cIo5UZJ0q9Of71mI8WLK2i" + "FSYVplpTX0WMClAdkGt3HgVb7xtOhGt1mEKeRQjNZ2LteUQrRDD9MTQ+XxcvEN0I" + "pAj4kBJe9bR6HzAD/iecCmGwSlHUZZrgqWzv78o79XxDdcuLdl4i2fL7kwEOf9js" + "De7hGs27yrdJEmAG9QF9TOF9LJFmE1CqkgW+EpKxsY01Wjm0BFJB1R7iPUaUtFRZ" + "xYqfgXarmPjql2iBi+cVjLzGu+4BSojVAPgP/hhcnIowf4M4edPiICMP1GVjtCFX" + "ZXJuZXIgS29jaCA8d2VybmVyLmtvY2hAZ3V1Zy5kZT6IYwQTEQIAGwUCNs8JNwUJ" + "CCCxRAMLCgMDFQMCAxYCAQIXgAASCRBsfuG4YhzAEwdlR1BHAAEBaSAAn3YkpT5h" + "xgehGFfnX7izd+c8jI0SAJ9qJZ6jJvXnGB07p60aIPYxgJbLmYkAdQMFEDWjdxQd" + "GfTBDJhXpQEBPfMC/0cxo+4xYVAplFO0nIYyjQgP7D8O0ufzPsIwF3kvb7b5FNNj" + "fp+DAhN6G0HOIgkL3GsWtCfH5UHali+mtNFIKDpTtr+F/lPpZP3OPzzsLZS4hYTq" + "mMs1O/ACq8axKgAilYkBXwMFEDWiJw4DbxG4/z6qCxADB9wFH0i6mmn6rWYKFepJ" + "hXyhE4wWqRPJAnvfoiWUntDp4aIQys6lORigVXIWo4k4SK/FH59YnzF7578qrTZW" + "/RcA0bIqJqzqaqsOdTYEFa49cCjvLnBW4OebJlLTUs/nnmU0FWKW8OwwL+pCu8d7" + "fLSSnggBsrUQwbepuw0cJoctFPAz5T1nQJieQKVsHaCNwL2du0XefOgF5ujB1jK1" + "q3p4UysF9hEcBR9ltE3THr+iv4jtZXmC1P4at9W5LFWsYuwr0U3yJcaKSKp0v/wG" + "EWe2J/gFQZ0hB1+35RrCZPgiWsEv87CHaG6XtQ+3HhirBCJsYhmOikVKoEan6PhU" + "VR1qlXEytpAt389TBnvyceAX8hcHOE3diuGvILEgYes3gw3s5ZmM7bUX3jm2BrX8" + "WchexUFUQIuKW2cL379MFXR8TbxpVxrsRYE/4jHZBYhGBBARAgAGBQI27U4LAAoJ" + "EF3iSZZbA1iifJoAoLEsGy16hV/CfmDku6D1CBUIxXvpAJ9GBApdC/3OXig7sBrV" + "CWOb3MQzcLkBjQQ2zwcIEAYA9zWEKm5eZpMMBRsipL0IUeSKEyeKUjABX4vYNurl" + "44+2h6Y8rHn7rG1l/PNj39UJXBkLFj1jk8Q32v+3BQDjvwv8U5e/kTgGlf7hH3WS" + "W38RkZw18OXYCvnoWkYneIuDj6/HH2bVNXmTac05RkBUPUv4yhqlaFpkVcswKGuE" + "NRxujv/UWvVF+/2P8uSQgkmGp/cbwfMTkC8JBVLLBRrJhl1uap2JjZuSVklUUBez" + "Vf3NJMagVzx47HPqLVl4yr4bAAMGBf9PujlH5I5OUnvZpz+DXbV/WQVfV1tGRCra" + "kIj3mpN6GnUDF1LAbe6vayUUJ+LxkM1SqQVcmuy/maHXJ+qrvNLlPqUZPmU5cINl" + "sA7bCo1ljVUp54J1y8PZUx6HxfEl/LzLVkr+ITWnyqeiRikDecUf4kix2teTlx6I" + "3ecqT5oNqZSRXWwnN4SbkXtAd7rSgEptUYhQXgSEarp1pXJ4J4rgqFa49jKISDJq" + "rn/ElltHe5Fx1bpfkCIYlYk45Cga9bOIVAQYEQIADAUCNs8HCAUJBvPJAAASCRBs" + "fuG4YhzAEwdlR1BHAAEBeRUAoIGpCDmMy195TatlloHAJEjZu5KaAJwOvW989hOb" + "8cg924YIFVA1+4/Ia7kBjQQ1oiE8FAYAkQmAlOXixb8wra83rE1i7LCENLzlvBZW" + "KBXN4ONelZAnnkOm7IqRjMhtKRJN75zqVyKUaUwDKjpf9J5K2t75mSxBtnbNRqL3" + "XodjHK93OcAUkz3ci7iuC/b24JI2q4XeQG/v4YR1VodM0zEQ1IC0JCq4Pl39QZyX" + "JdZCrUFvMcXq5ruNSldztBqTFFUiFbkw1Fug/ZyXJve2FVcbsRXFrB7EEuy+iiU/" + "kZ/NViKk0L4T6KRHVsEiriNlCiibW19fAAMFBf9Tbv67KFMDrLqQan/0oSSodjDQ" + "KDGqtoh7KQYIKPXqfqT8ced9yd5MLFwPKf3t7AWG1ucW2x118ANYkPSU122UTndP" + "sax0cY4XkaHxaNwpNFCotGQ0URShxKNpcqbdfvy+1d8ppEavgOyxnV1JOkLjZJLw" + "K8bgxFdbPWcsJJnjuuH3Pwz87CzTgOSYQxMPnIwQcx5buZIV5NeELJtcbbd3RVua" + "K/GQht8QJpuXSji8Nl1FihYDjACR8TaRlAh50GmIRgQoEQIABgUCOCv7gwAKCRBs" + "fuG4YhzAE9hTAJ9cRHu+7q2hkxpFfnok4mRisofCTgCgzoPjNIuYiiV6+wLB5o11" + "7MNWPZCIVAQYEQIADAUCNaIhPAUJB4TOAAASCRBsfuG4YhzAEwdlR1BHAAEBDfUA" + "oLstR8cg5QtHwSQ3nFCOKEREUFIwAKDID3K3hM+b6jW1o+tNX9dnjb+YMZkAbQIw" + "bYOUAAABAwC7ltmO5vdKssohwzXEZeYvDW2ll3CYD2I+ruiNq0ybxkfFBopq9cxt" + "a0OvVML4LK/TH+60f/Fqx9wg2yk9APXyaomdLrXfWyfZ91YtNCfj3ElC4XB4qqm0" + "HRn0wQyYV6UABRG0IVdlcm5lciBLb2NoIDx3ZXJuZXIua29jaEBndXVnLmRlPokA" + "lQMFEDRfoOmOB31Gi6BmjQEBzwgD/2fHcdDXuRRY+SHvIVESweijstB+2/sVRp+F" + "CDjR74Kg576sJHfTJCxtSSmzpaVpelb5z4URGJ/Byi5L9AU7hC75S1ZnJ+MjBT6V" + "ePyk/r0uBrMkU/lMG7lk/y2By3Hll+edjzJsdwn6aoNPiyen4Ch4UGTEguxYsLq0" + "HES/UvojiQEVAwUTNECE2gnp+QqKck5FAQH+1Af/QMlYPlLG+5E19qP6AilKQUzN" + "kd1TWMenXTS66hGIVwkLVQDi6RCimhnLMq/F7ENA8bSbyyMuncaBz5dH4kjfiDp1" + "o64LULcTmN1LW9ctpTAIeLLJZnwxoJLkUbLUYKADKqIBXHMt2B0zRmhFOqEjRN+P" + "hI7XCcHeHWHiDeUB58QKMyeoJ/QG/7zLwnNgDN2PVqq2E72C3ye5FOkYLcHfWKyB" + "Rrn6BdUphAB0LxZujSGk8ohZFbia+zxpWdE8xSBhZbjVGlwLurmS2UTjjxByBNih" + "eUD6IC3u5P6psld0OfqnpriZofP0CBP2oTk65r529f/1lsy2kfWrVPYIFJXEnIkA" + "lQMFEDQyneGkWMS9SnJfMQEBMBMD/1ADuhhuY9kyN7Oj6DPrDt5SpPQDGS0Jtw3y" + "uIPoed+xyzlrEuL2HeaOj1O9urpn8XLN7V21ajkzlqsxnGkOuifbE9UT67o2b2vC" + "ldCcY4nV5n+U1snMDwNv+RkcEgNa8ANiWkm03UItd7/FpHDQP0FIgbPEPwRoBN87" + "I4gaebfRiQCVAwUQNDUSwxRNm5Suj3z1AQGMTAP/UaXXMhPzcjjLxBW0AccTdHUt" + "Li+K+rS5PNxxef2nnasEhCdK4GkM9nwJgsP0EZxCG3ZSAIlWIgQ3MK3ZAV1Au5pL" + "KolRjFyEZF420wAtiE7V+4lw3FCqNoXDJEFC3BW431kx1wAhDk9VaIHHadYcof4d" + "dmMLQOW2cJ7LDEEBW/WJAJUDBRA0M/VQImbGhU33abUBARcoA/9eerDBZGPCuGyE" + "mQBcr24KPJHWv/EZIKl5DM/Ynz1YZZbzLcvEFww34mvY0jCfoVcCKIeFFBMKiSKr" + "OMtoVC6cQMKpmhE9hYRStw4E0bcf0BD/stepdVtpwRnG8SDP2ZbmtgyjYT/7T4Yt" + "6/0f6N/0NC7E9qfq4ZlpU3uCGGu/44kAlQMFEDQz8kp2sPVxuCQEdQEBc5YD/Rix" + "vFcLTO1HznbblrO0WMzQc+R4qQ50CmCpWcFMwvVeQHo/bxoxGggNMmuVT0bqf7Mo" + "lZDSJNS96IAN32uf25tYHgERnQaMhmi1aSHvRDh4jxFu8gGVgL6lWit/vBDW/BiF" + "BCH6sZJJrGSuSdpecTtaWC8OJGDoKTO9PqAA/HQRiQB1AwUQNDJSx011eFs7VOAZ" + "AQGdKQL/ea3qD2OP3wVTzXvfjQL1CosX4wyKusBBhdt9u2vOT+KWkiRk1o35nIOG" + "uZLHtSFQDY8CVDOkqg6g4sVbOcTl8QUwHA+A4AVDInwTm1m4Bk4oeCIwk4Bp6mDd" + "W11g28k/iQEVAgUSNDIWPm/Y4wPDeaMxAQGvBQgAqGhzA/21K7oL/L5S5Xz//eO7" + "J8hgvqqGXWd13drNy3bHbKPn7TxilkA3ca24st+6YPZDdSUHLMCqg16YOMyQF8gE" + "kX7ZHWPacVoUpCmSz1uQ3p6W3+u5UCkRpgQN8wBbJx5ZpBBqeq5q/31okaoNjzA2" + "ghEWyR5Ll+U0C87MY7pc7PlNHGCr0ZNOhhtf1jU+H9ag5UyT6exIYim3QqWYruiC" + "LSUcim0l3wK7LMW1w/7Q6cWfAFQvl3rGjt3rg6OWg9J4H2h5ukf5JNiRybkupmat" + "UM+OVMRkf93jzU62kbyZpJBHiQZuxxJaLkhpv2RgWib9pbkftwEy/ZnmjkxlIIkA" + "lQMFEDQvWjh4313xYR8/NQEB37QEAIi9vR9h9ennz8Vi7RNU413h1ZoZjxfEbOpk" + "QAjE/LrZ/L5WiWdoStSiyqCLPoyPpQafiU8nTOr1KmY4RgceJNgxIW4OiSMoSvrh" + "c2kqP+skb8A2B4+47Aqjr5fSAVfVfrDMqDGireOguhQ/hf9BOYsM0gs+ROdtyLWP" + "tMjRnFlviD8DBRAz8qQSj6lRT5YOKXIRAntSAJ9StSEMBoFvk8iRWpXb6+LDNLUW" + "zACfT8iY3IxwvMF6jjCHrbuxQkL7chSJARUDBRA0MMO7569NIyeqD3EBATIAB/4t" + "CPZ1sLWO07g2ZCpiP1HlYpf5PENaXtaasFvhWch7eUe3DksuMEPzB5GnauoQZAku" + "hEGkoEfrfL3AXtXH+WMm2t7dIcTBD4p3XkeZ+PgJpKiASXDyul9rumXXvMxSL4KV" + "7ar+F1ZJ0ycCx2r2au0prPao70hDAzLTy16hrWgvdHSK7+wwaYO5TPCL5JDmcB+d" + "HKW72qNUOD0pxbe0uCkkb+gDxeVX28pZEkIIOMMV/eAs5bs/smV+eJqWT/EyfVBD" + "o7heF2aeyJj5ecxNOODr88xKF7qEpqazCQ4xhvFY+Yn6+vNCcYfkoZbOn0XQAvqf" + "a2Vab9woVIVSaDji/mlPiQB1AwUQNDC233FfeD4HYGBJAQFh6QL/XCgm5O3q9kWp" + "gts1MHKoHoh7vxSSQGSP2k7flNP1UB2nv4sKvyGM8eJKApuROIodcTkccM4qXaBu" + "XunMr5kJlvDJPm+NLzKyhtQP2fWI7xGYwiCiB29gm1GFMjdur4amiQEVAwUQNDBR" + "9fjDdqGixRdJAQE+mAf+JyqJZEVFwNwZ2hSIMewekC1r7N97p924nqfZKnzn6weF" + "pE80KIJSWtEVzI0XvHlVCOnS+WRxn7zxwrOTbrcEOy0goVbNgUsP5ypZa2/EM546" + "uyyJTvgD0nwA45Q4bP5sGhjh0G63r9Vwov7itFe4RDBGM8ibGnZTr9hHo469jpom" + "HSNeavcaUYyEqcr4GbpQmdpJTnn/H0A+fMl7ZHRoaclNx9ZksxihuCRrkQvUOb3u" + "RD9lFIhCvNwEardN62dKOKJXmn1TOtyanZvnmWigU5AmGuk6FpsClm3p5vvlid64" + "i49fZt9vW5krs2XfUevR4oL0IyUl+qW2HN0DIlDiAYkAlQMFEDQvbv2wcgJwUPMh" + "JQEBVBID/iOtS8CQfMxtG0EmrfaeVUU8R/pegBmVWDBULAp8CLTtdfxjVzs/6DXw" + "0RogXMRRl2aFfu1Yp0xhBYjII6Kque/FzAFXY9VNF1peqnPt7ADdeptYMppZa8sG" + "n9BBRu9Fsw69z6JkyqvMiVxGcKy3XEpVGr0JHx8Xt6BYdrULiKr2iQB1AwUQNC68" + "n6jZR/ntlUftAQFaYgL+NUYEj/sX9M5xq1ORX0SsVPMpNamHO3JBSmZSIzjiox5M" + "AqoFOCigAkonuzk5aBy/bRHy1cmDBOxf4mNhzrH8N6IkGvPE70cimDnbFvr+hoZS" + "jIqxtELNZsLuLVavLPAXiQCVAwUQNC6vWocCuHlnLQXBAQHb1gQAugp62aVzDCuz" + "4ntfXsmlGbLY7o5oZXYIKdPP4riOj4imcJh6cSgYFL6OMzeIp9VW/PHo2mk8kkdk" + "z5uif5LqOkEuIxgra7p1Yq/LL4YVhWGQeD8hwpmu+ulYoPOw40dVYS36PwrHIH9a" + "fNhl8Or5O2VIHIWnoQ++9r6gwngFQOyJAJUDBRAzHnkh1sNKtX1rroUBAWphBACd" + "huqm7GHoiXptQ/Y5F6BivCjxr9ch+gPSjaLMhq0kBHVO+TbXyVefVVGVgCYvFPjo" + "zM8PEVykQAtY//eJ475aGXjF+BOAhl2z0IMkQKCJMExoEDHbcj0jIIMZ2/+ptgtb" + "FSyJ2DQ3vvCdbw/1kyPHTPfP+L2u40GWMIYVBbyouokAlQMFEDMe7+UZsymln7HG" + "2QEBzMED/3L0DyPK/u6PyAd1AdpjUODTkWTZjZ6XA2ubc6IXXsZWpmCgB/24v8js" + "J3DIsvUD3Ke55kTr6xV+au+mAkwOQqWUTUWfQCkSrSDlbUJ1VPBzhyTpuzjBopte" + "7o3R6XXfcLiC5jY6eCX0QtLGhKpLjTr5uRhf1fYODGsAGXmCByDviQB1AgUQMy6U" + "MB0Z9MEMmFelAQHV4AMAjdFUIyFtpTr5jkyZSd3y//0JGO0z9U9hLVxeBBCwvdEQ" + "xsrpeTtVdqpeKZxHN1GhPCYvgLFZAQlcPh/Gc8u9uO7wVSgJc3zYKFThKpQevdF/" + "rzjTCHfgigf5Iui0qiqBiQCVAwUQMx22bAtzgG/ED06dAQFi0gQAkosqTMWy+1eU" + "Xbi2azFK3RX5ERf9wlN7mqh7TvwcPXvVWzUARnwRv+4kk3uOWI18q5UPis7KH3KY" + "OVeRrPd8bbp6SjhBh82ourTEQUXLBDQiI1V1cZZmwwEdlnAnhFnkXgMBNM2q7oBe" + "fRHADfYDfGo90wXyrVVL+GihDNpzUwOJAJUDBRAzHUFnOWvfULwOR3EBAbOYA/90" + "JIrKmxhwP6quaheFOjjPoxDGEZpGJEOwejEByYj+AgONCRmQS3BydtubA+nm/32D" + "FeG8pe/dnFvGc+QgNW560hK21C2KJj72mhjRlg/na7jz4/MmBAv5k61Q7roWi0rw" + "x+R9NSHxpshC8A92zmvo8w/XzVSogC8pJ04jcnY6YokAlQMFEDMdPtta9LwlvuSC" + "3QEBvPMD/3TJGroHhHYjHhiEpDZZVszeRQ0cvVI/uLLi5yq3W4F6Jy47DF8VckA7" + "mw0bXrOMNACN7Je7uyaU85qvJC2wgoQpFGdFlkjmkAwDAjR+koEysiE8FomiOHhv" + "EpEY/SjSS4jj4IPmgV8Vq66XjPw+i7Z0RsPLOIf67yZHxypNiBiYiQCVAwUQMxxw" + "pKrq6G7/78D5AQHo2QQAjnp6KxOl6Vvv5rLQ/4rj3OemvF7IUUq34xb25i/BSvGB" + "UpDQVUmhv/qIfWvDqWGZedyM+AlNSfUWPWnP41S8OH+lcERH2g2dGKGl7kH1F2Bx" + "ByZlqREHm2q624wPPA35RLXtXIx06yYjLtJ7b+FCAX6PUgZktZYk5gwjdoAGrC2J" + "AJUDBRAzGvcCKC6c7f53PGUBAUozA/9l/qKmcqbi8RtLsKQSh3vHds9d22zcbkuJ" + "PBSoOv2D7i2VLshaQFjq+62uYZGE6nU1WP5sZcBDuWjoX4t4NrffnOG/1R9D0t1t" + "9F47D77HJzjvo+J52SN520YHcbT8VoHdPRoEOXPN4tzhvn2GapVVdaAlWM0MLloh" + "NH3I9jap9okAdQMFEDMZlUAnyXglSykrxQEBnuwC/jXbFL+jzs2HQCuo4gyVrPlU" + "ksQCLYZjNnZtw1ca697GV3NhBhSXR9WHLQH+ZWnpTzg2iL3WYSdi9tbPs78iY1FS" + "d4EG8H9V700oQG8dlICF5W2VjzR7fByNosKM70WSXYkBFQMFEDMWBsGCy1t9eckW" + "HQEBHzMH/jmrsHwSPrA5R055VCTuDzdS0AJ+tuWkqIyqQQpqbost89Hxper3MmjL" + "Jas/VJv8EheuU3vQ9a8sG2SnlWKLtzFqpk7TCkyq/H3blub0agREbNnYhHHTGQFC" + "YJb4lWjWvMjfP+N5jvlLcnDqQPloXfAOgy7W90POoqFrsvhxdpnXgoLrzyNNja1O" + "1NRj+Cdv/GmJYNi6sQe43zmXWeA7syLKMw6058joDqEJFKndgSp3Zy/yXmObOZ/H" + "C2OJwA3gzEaAu8Pqd1svwGIGznqtTNCn9k1+rMvJPaxglg7PXIJS282hmBl9AcJl" + "wmh2GUCswl9/sj+REWTb8SgJUbkFcp6JAJUDBRAwdboVMPfsgxioXMEBAQ/LA/9B" + "FTZ9T95P/TtsxeC7lm9imk2mpNQCBEvXk286FQnGFtDodGfBfcH5SeKHaUNxFaXr" + "39rDGUtoTE98iAX3qgCElf4V2rzgoHLpuQzCg3U35dfs1rIxlpcSDk5ivaHpPV3S" + "v+mlqWL049y+3bGaZeAnwM6kvGMP2uccS9U6cbhpw4hGBBARAgAGBQI3GtRfAAoJ" + "EF3iSZZbA1iikWUAoIpSuXzuN/CI63dZtT7RL7c/KtWUAJ929SAtTr9SlpSgxMC8" + "Vk1T1i5/SYkBFQMFEzccnFnSJilEzmrGwQEBJxwH/2oauG+JlUC3zBUsoWhRQwqo" + "7DdqaPl7sH5oCGDKS4x4CRA23U15NicDI7ox6EizkwCjk0dRr1EeRK+RqL1b/2T4" + "2B6nynOLhRG2A0BPHRRJLcoL4nKfoPSo/6dIC+3iVliGEl90KZZD5bnONrVJQkRj" + "ZL8Ao+9IpmoYh8XjS5xMLEF9oAQqAkA93nVBm56lKmaL1kl+M3dJFtNKtVB8de1Z" + "XifDs8HykD42qYVtcseCKxZXhC3UTG5YLNhPvgZKH8WBCr3zcR13hFDxuecUmu0M" + "VhvEzoKyBYYt0rrqnyWrxwbv4gSTUWH5ZbgsTjc1SYKZxz6hrPQnfYWzNkznlFWJ" + "ARUDBRM0xL43CdxwOTnzf10BATOCB/0Q6WrpzwPMofjHj54MiGLKVP++Yfwzdvns" + "HxVpTZLZ5Ux8ErDsnLmvUGphnLVELZwEkEGRjln7a19h9oL8UYZaV+IcR6tQ06Fb" + "1ldR+q+3nXtBYzGhleXdgJQSKLJkzPF72tvY0DHUB//GUV9IBLQMvfG8If/AFsih" + "4iXi96DOtUAbeuIhnMlWwLJFeGjLLsX1u6HSX33xy4bGX6v/UcHbTSSYaxzb92GR" + "/xpP2Xt332hOFRkDZL52g27HS0UrEJWdAVZbh25KbZEl7C6zX/82OZ5nTEziHo20" + "eOS6Nrt2+gLSeA9X5h/+qUx30kTPz2LUPBQyIqLCJkHM8+0q5j9ciQCiAwUTNMS+" + "HZFeTizbCJMJAQFrGgRlEAkG1FYU4ufTxsaxhFZy7xv18527Yxpls6mSCi1HL55n" + "Joce6TI+Z34MrLOaiZljeQP3EUgzA+cs1sFRago4qz2wS8McmQ9w0FNQQMz4vVg9" + "CVi1JUVd4EWYvJpA8swDd5b9+AodYFEsfxt9Z3aP+AcWFb10RlVVsNw9EhObc6IM" + "nwAOHCEI9vp5FzzFiQCVAwUQNxyr6UyjTSyISdw9AQHf+wP+K+q6hIQ09tkgaYaD" + "LlWKLbuxePXqM4oO72qi70Gkg0PV5nU4l368R6W5xgR8ZkxlQlg85sJ0bL6wW/Sj" + "Mz7pP9hkhNwk0x3IFkGMTYG8i6Gt8Nm7x70dzJoiC+A496PryYC0rvGVf+Om8j5u" + "TexBBjb/jpJhAQ/SGqeDeCHheOC0Lldlcm5lciBLb2NoIChtZWluIGFsdGVyIGtl" + "eSkgPHdrQGNvbXB1dGVyLm9yZz6JAHUDBRM2G2MyHRn0wQyYV6UBASKKAv4wzmK7" + "a9Z+g0KH+6W8ffIhzrQo8wDAU9X1WJKzJjS205tx4mmdnAt58yReBc/+5HXTI8IK" + "R8IgF+LVXKWAGv5P5AqGhnPMeQSCs1JYdf9MPvbe34jD8wA1LTWFXn9e/cWIRgQQ" + "EQIABgUCNxrUaQAKCRBd4kmWWwNYovRiAJ9dJBVfjx9lGARoFXmAieYrMGDrmwCZ" + "AQyO4Wo0ntQ+iq4do9M3/FTFjiCZAaIENu1I6REEAJRGEqcYgXJch5frUYBj2EkD" + "kWAbhRqVXnmiF3PjCEGAPMMYsTddiU7wcKfiCAqKWWXow7BjTJl6Do8RT1jdKpPO" + "lBJXqqPYzsyBxLzE6mLps0K7SLJlSKTQqSVRcx0jx78JWYGlAlP0Kh9sPV2w/rPh" + "0LrPeOKXT7lZt/DrIhfPAKDL/sVqCrmY3QfvrT8kSKJcgtLWfQP/cfbqVNrGjW8a" + "m631N3UVA3tWfpgM/T9OjmKmw44NE5XfPJTAXlCV5j7zNMUkDeoPkrFF8DvbpYQs" + "4XWYHozDjhR2Q+eI6gZ0wfmhLHqqc2eVVkEG7dT57Wp9DAtCMe7RZfhnarTQMqlY" + "tOEa/suiHk0qLo59NsyF8eh68IDNCeYD/Apzonwaq2EQ1OEpfFlp6LcSnS34+UGZ" + "tTO4BgJdmEjr/QrIPp6bJDstgho+/2oR8yQwuHGJwbS/8ADA4IFEpLduSpzrABho" + "7RuNQcm96bceRY+7Hza3zf7pg/JGdWOb+bC3S4TIpK+3sx3YNWs7eURwpGREeJi5" + "/Seic+GXlGzltBpXZXJuZXIgS29jaCA8d2tAZ251cGcub3JnPohjBBMRAgAbBQI3" + "Gs+QBQkMyXyAAwsKAwMVAwIDFgIBAheAABIJEF3iSZZbA1iiB2VHUEcAAQFdwgCe" + "O/s43kCLDMIsHCb2H3LC59clC5UAn1EyrqWk+qcOXLpQIrP6Qa3QSmXIiEYEEBEC" + "AAYFAjca0T0ACgkQbH7huGIcwBOF9ACeNwO8G2G0ei03z0g/n3QZIpjbzvEAnRaE" + "qX2PuBbClWoIP6h9yrRlAEbUiQB1AwUQNxrRYx0Z9MEMmFelAQHRrgL/QDNKPV5J" + "gWziyzbHvEKfTIw/Ewv6El2MadVvQI8kbPN4qkPr2mZWwPzuc9rneCPQ1eL8AOdC" + "8+ZyxWzx2vsrk/FcU5donMObva2ct4kqJN6xl8xjsxDTJhBSFRaiBJjxiEYEEBEC" + "AAYFAjca0aMACgkQaLeriVdUjc0t+ACghK37H2vTYeXXieNJ8aZkiPJSte4An0WH" + "FOotQdTW4NmZJK+Uqk5wbWlgiEYEEBECAAYFAjdPH10ACgkQ9u7fIBhLxNktvgCe" + "LnQ5eOxAJz+Cvkb7FnL/Ko6qc5YAnjhWWW5c1o3onvKEH2Je2wQa8T6iiEYEEBEC" + "AAYFAjenJv4ACgkQmDRl2yFDlCJ+yQCfSy1zLftEfLuIHZsUHis9U0MlqLMAn2EI" + "f7TI1M5OKysQcuFLRC58CfcfiEUEEBECAAYFAjfhQTMACgkQNmdg8X0u14h55wCf" + "d5OZCV3L8Ahi4QW/JoXUU+ZB0M0AmPe2uw7WYDLOzv48H76tm6cy956IRgQQEQIA" + "BgUCOCpiDwAKCRDj8lhUEo8OeRsdAJ9FHupRibBPG2t/4XDqF+xiMLL/8ACfV5F2" + "SR0ITE4k/C+scS1nJ1KZUDW0C1dlcm5lciBLb2NoiGMEExECABsFAjbtSOoFCQzJ" + "fIADCwoDAxUDAgMWAgECF4AAEgkQXeJJllsDWKIHZUdQRwABAbXWAJ9SCW0ieOpL" + "7AY6vF+OIaMmw2ZW1gCgkto0eWfgpjAuVg6jXqR1wHt2pQOJAh4EEBQDAAYFAjcv" + "WdQACgkQbEwxpbHVFWcNxQf/bg14WGJ0GWMNSuuOOR0WYzUaNtzYpiLSVyLrreXt" + "o8LBNwzbgzj2ramW7Ri+tYJAHLhtua8ZgSeibmgBuZasF8db1m5NN1ZcHBXGTysA" + "jp+KnicTZ9Orj75D9o3oSmMyRcisEhr+gkj0tVhGfOAOC6eKbufVuyYFDVIyOyUB" + "GlW7ApemzAzYemfs3DdjHn87lkjHMVESO4fM5rtLuSc7cBfL/e6ljaWQc5W8S0gI" + "Dv0VtL39pMW4BlpKa25r14oJywuUpvWCZusvDm7ZJnqZ/WmgOHQUsyYudTROpGIb" + "lsNg8iqC6huWpGSBRdu3oRQRhkqpfVdszz6BB/nAx01q2wf/Q+U9XId1jyzxUL1S" + "GgaYMf6QdyjHQ1oxuFLNxzM6C/M069twbNgXJ71RsDDXVxFZfSTjSiH100AP9+9h" + "b5mycaXLUOXYDvOSFzHBd/LsjFNVrrFbDs5Xw+cLGVHOIgR5IWAfgu5d1PAZU9uQ" + "VgdGnQfmZg383RSPxvR3fnZz1rHNUGmS6w7x6FVbxa1QU2t38gNacIwHATAPcBpy" + "JLfXoznbpg3ADbgCGyDjBwnuPQEQkYwRakbczRrge8IaPZbt2HYPoUsduXMZyJI8" + "z5tvu7pUDws51nV1EX15BcN3++aY5pUyA1ItaaDymQVmoFbQC0BNMzMO53dMnFko" + "4i42kohGBBARAgAGBQI3OvmjAAoJEHUPZJXInZM+hosAnRntCkj/70shGTPxgpUF" + "74zA+EbzAKCcMkyHXIz2W0Isw3gDt27Z9ggsE4hGBBARAgAGBQI3NyPFAAoJEPbu" + "3yAYS8TZh2UAoJVmzw85yHJzsXQ1vpO2IAPfv59NAJ9WY0oiYqb3q1MSxBRwG0gV" + "iNCJ7YkBFQMFEDdD3tNSgFdEdlNAHQEByHEH/2JMfg71GgiyGJTKxCAymdyf2j2y" + "fH6wI782JK4BWV4c0E/V38q+jpIYslihV9t8s8w1XK5niMaLwlCOyBWOkDP3ech6" + "+GPPtfB3cmlL2hS896PWZ1adQHgCeQpB837n56yj0aTs4L1xarbSVT22lUwMiU6P" + "wYdH2Rh8nh8FvN0IZsbln2nOj73qANQzNflmseUKF1Xh4ck8yLrRd4r6amhxAVAf" + "cYFRJN4zdLL3cmhgkt0ADZlzAwXnEjwdHHy7SvAJk1ecNOA9pFsOJbvnzufd1afs" + "/CbG78I+0JDhg75Z2Nwq8eKjsKqiO0zz/vG5yWSndZvWkTWz3D3b1xr1Id2IRgQQ" + "EQIABgUCOCpiHgAKCRDj8lhUEo8OeQ+QAKCbOTscyUnWHSrDo4fIy0MThEjhOgCe" + "L4Kb7TWkd/OHQScVBO8sTUz0+2g="); // private static readonly byte[] pub6check = Base64.Decode("62O9"); // // revoked sub key // private static readonly byte[] pub7 = Base64.Decode( "mQGiBEFOsIwRBADcjRx7nAs4RaWsQU6p8/ECLZD9sSeYc6CN6UDI96RKj0/hCzMs" + "qlA0+9fzGZ7ZEJ34nuvDKlhKGC7co5eOiE0a9EijxgcrZU/LClZWa4YfyNg/ri6I" + "yTyfOfrPQ33GNQt2iImDf3FKp7XKuY9nIxicGQEaW0kkuAmbV3oh0+9q8QCg/+fS" + "epDEqEE/+nKONULGizKUjMED/RtL6RThRftZ9DOSdBytGYd48z35pca/qZ6HA36K" + "PVQwi7V77VKQyKFLTOXPLnVyO85hyYB/Nv4DFHN+vcC7/49lfoyYMZlN+LarckHi" + "NL154wmmzygB/KKysvWBLgkErEBCD0xBDd89iTQNlDtVQAWGORVffl6WWjOAkliG" + "3dL6A/9A288HfFRnywqi3xddriV6wCPmStC3dkCS4vHk2ofS8uw4ZNoRlp1iEPna" + "ai2Xa9DX1tkhaGk2k96MqqbBdGpbW8sMA9otJ9xdMjWEm/CgJUFUFQf3zaVy3mkM" + "S2Lvb6P4Wc2l/diEEIyK8+PqJItSh0OVU3K9oM7ngHwVcalKILQVUkV2b2tlZCA8" + "UmV2b2tlZEB0ZWQ+iQBOBBARAgAOBQJBTrCMBAsDAgECGQEACgkQvglkcFA/c63+" + "QgCguh8rsJbPTtbhZcrqBi5Mo1bntLEAoPZQ0Kjmu2knRUpHBeUemHDB6zQeuQIN" + "BEFOsIwQCAD2Qle3CH8IF3KiutapQvMF6PlTETlPtvFuuUs4INoBp1ajFOmPQFXz" + "0AfGy0OplK33TGSGSfgMg71l6RfUodNQ+PVZX9x2Uk89PY3bzpnhV5JZzf24rnRP" + "xfx2vIPFRzBhznzJZv8V+bv9kV7HAarTW56NoKVyOtQa8L9GAFgr5fSI/VhOSdvN" + "ILSd5JEHNmszbDgNRR0PfIizHHxbLY7288kjwEPwpVsYjY67VYy4XTjTNP18F1dD" + "ox0YbN4zISy1Kv884bEpQBgRjXyEpwpy1obEAxnIByl6ypUM2Zafq9AKUJsCRtMI" + "PWakXUGfnHy9iUsiGSa6q6Jew1XpMgs7AAICB/93zriSvSHqsi1FeEmUBo431Jkh" + "VerIzb6Plb1j6FIq+s3vyvx9K+dMvjotZqylWZj4GXpH+2xLJTjWkrGSfUZVI2Nk" + "nyOFxUCKLLqaqVBFAQIjULfvQfGEWiGQKk9aRLkdG+D+8Y2N9zYoBXoQ9arvvS/t" + "4mlOsiuaTe+BZ4x+BXTpF4b9sKZl7V8QP/TkoJWUdydkvxciHdWp7ssqyiKOFRhG" + "818knDfFQ3cn2w/RnOb+7AF9wDncXDPYLfpPv9b2qZoLrXcyvlLffGDUdWs553ut" + "1F5AprMURs8BGmY9BnjggfVubHdhTUoA4gVvrdaf+D9NwZAl0xK/5Y/oPuMZiQBG" + "BBgRAgAGBQJBTrCMAAoJEL4JZHBQP3Ot09gAoMmLKloVDP+WhDXnsM5VikxysZ4+" + "AKCrJAUO+lYAyPYwEwgK+bKmUGeKrIkARgQoEQIABgUCQU6wpQAKCRC+CWRwUD9z" + "rQK4AJ98kKFxGU6yhHPr6jYBJPWemTNOXgCfeGB3ox4PXeS4DJDuLy9yllytOjo="); // private static readonly byte[] pub7check = Base64.Decode("f/YQ"); private static readonly byte[] pub8 = Base64.Decode( "mQGiBEEcraYRBADFYj+uFOhHz5SdECvJ3Z03P47gzmWLQ5HH8fPYC9rrv7AgqFFX" + "aWlJJVMLua9e6xoCiDWJs/n4BbZ/weL/11ELg6XqUnzFhYyz0H2KFsPgQ/b9lWLY" + "MtcPMFy5jE33hv/ixHgYLFqoNaAIbg0lzYEW/otQ9IhRl16fO1Q/CQZZrQCg/9M2" + "V2BTmm9RYog86CXJtjawRBcD/RIqU0zulxZ2Zt4javKVxrGIwW3iBU935ebmJEIK" + "Y5EVkGKBOCvsApZ+RGzpYeR2uMsTnQi8RJgiAnjaoVPCdsVJE7uQ0h8XuJ5n5mJ2" + "kLCFlF2hj5ViicZzse+crC12CGtgRe8z23ubLRcd6IUGhVutK8/b5knZ22vE14JD" + "ykKdA/96ObzJQdiuuPsEWN799nUUCaYWPAoLAmiXuICSP4GEnxLbYHWo8zhMrVMT" + "9Q5x3h8cszUz7Acu2BXjP1m96msUNoxPOZtt88NlaFz1Q/JSbQTsVOMd9b/IRN6S" + "A/uU0BiKEMHXuT8HUHVPK49oCKhZrGFP3RT8HZxDKLmR/qrgZ7ABh7QhSmlhIFlp" + "eXUgPHl5amlhQG5vd21lZGlhdGVjaC5jb20+sAMD//+JAF0EEBECAB0FAkEcraYH" + "CwkIBwMCCgIZAQUbAwAAAAUeAQAAAAAKCRD0/lb4K/9iFJlhAKCRMifQewiX5o8F" + "U099FG3QnLVUZgCfWpMOsHulGHfNrxdBSkE5Urqh1ymwAWe5Ag0EQRytphAIAPZC" + "V7cIfwgXcqK61qlC8wXo+VMROU+28W65Szgg2gGnVqMU6Y9AVfPQB8bLQ6mUrfdM" + "ZIZJ+AyDvWXpF9Sh01D49Vlf3HZSTz09jdvOmeFXklnN/biudE/F/Ha8g8VHMGHO" + "fMlm/xX5u/2RXscBqtNbno2gpXI61Brwv0YAWCvl9Ij9WE5J280gtJ3kkQc2azNs" + "OA1FHQ98iLMcfFstjvbzySPAQ/ClWxiNjrtVjLhdONM0/XwXV0OjHRhs3jMhLLUq" + "/zzhsSlAGBGNfISnCnLWhsQDGcgHKXrKlQzZlp+r0ApQmwJG0wg9ZqRdQZ+cfL2J" + "SyIZJrqrol7DVekyCzsAAgIH/3K2wKRSzkIpDfZR25+tnQ8brv3TYoDZo3/wN3F/" + "r6PGjx0150Q8g8EAC0bqm4rXWzOqdSxYxvIPOAGm5P4y+884yS6j3vKcXitT7vj+" + "ODc2pVwGDLDjrMRrosSK89ycPCK6R/5pD7Rv4l9DWi2fgLvXqJHS2/ujUf2uda9q" + "i9xNMnBXIietR82Sih4undFUOwh6Mws/o3eed9DIdaqv2Y2Aw43z/rJ6cjSGV3C7" + "Rkf9x85AajYA3LwpS8d99tgFig2u6V/A16oi6/M51oT0aR/ZAk50qUc4WBk9uRUX" + "L3Y+P6v6FCBE/06fgVltwcQHO1oKYKhH532tDL+9mW5/dYGwAYeJAEwEGBECAAwF" + "AkEcraYFGwwAAAAACgkQ9P5W+Cv/YhShrgCg+JW8m5nF3R/oZGuG87bXQBszkjMA" + "oLhGPncuGKowJXMRVc70/8qwXQJLsAFnmQGiBD2K5rYRBADD6kznWZA9nH/pMlk0" + "bsG4nI3ELgyI7KpgRSS+Dr17+CCNExxCetT+fRFpiEvUcSxeW4pOe55h0bQWSqLo" + "MNErXVJEXrm1VPkC08W8D/gZuPIsdtKJu4nowvdoA+WrI473pbeONGjaEDbuIJak" + "yeKM1VMSGhsImdKtxqhndq2/6QCg/xARUIzPRvKr2TJ52K393895X1kEAMCdjSs+" + "vABnhaeNNR5+NNkkIOCCjCS8qZRZ4ZnIayvn9ueG3KrhZeBIHoajUHrlTXBVj7XO" + "wXVfGpW17jCDiqhU8Pu6VwEwX1iFbuUwqBffiRLXKg0zfcN+MyFKToi+VsJi4jiZ" + "zcwUFMb8jE8tvR/muXti7zKPRPCbNBExoCt4A/0TgkzAosG/W4dUkkbc6XoHrjob" + "iYuy6Xbs/JYlV0vf2CyuKCZC6UoznO5x2GkvOyVtAgyG4HSh1WybdrutZ8k0ysks" + "mOthE7n7iczdj9Uwg2h+TfgDUnxcCAwxnOsX5UaBqGdkX1PjCWs+O3ZhUDg6UsZc" + "7O5a3kstf16lHpf4q7ABAIkAYQQfEQIAIQUCPYrmtgIHABcMgBHRi/xlIgI+Q6LT" + "kNJ7zKvTd87NHAAKCRDJM3gHb/sRj7bxAJ9f6mdlXQH7gMaYiY5tBe/FRtPr1gCf" + "UhDJQG0ARvORFWHjwhhBMLxW7j2wAWC0KkRlc21vbmQgS2VlIDxkZXNtb25kLmtl" + "ZUBub3dtZWRpYXRlY2guY29tPrADAQD9iQBYBBARAgAYBQI9iua2CAsDCQgHAgEK" + "AhkBBRsDAAAAAAoJEMkzeAdv+xGP7v4An19iqadBCCgDIe2DTpspOMidwQYPAJ4/" + "5QXbcn4ClhOKTO3ZEZefQvvL27ABYLkCDQQ9iua2EAgA9kJXtwh/CBdyorrWqULz" + "Bej5UxE5T7bxbrlLOCDaAadWoxTpj0BV89AHxstDqZSt90xkhkn4DIO9ZekX1KHT" + "UPj1WV/cdlJPPT2N286Z4VeSWc39uK50T8X8dryDxUcwYc58yWb/Ffm7/ZFexwGq" + "01uejaClcjrUGvC/RgBYK+X0iP1YTknbzSC0neSRBzZrM2w4DUUdD3yIsxx8Wy2O" + "9vPJI8BD8KVbGI2Ou1WMuF040zT9fBdXQ6MdGGzeMyEstSr/POGxKUAYEY18hKcK" + "ctaGxAMZyAcpesqVDNmWn6vQClCbAkbTCD1mpF1Bn5x8vYlLIhkmuquiXsNV6TIL" + "OwACAgf/SO+bbg+owbFKVN5HgOjOElQZVnCsegwCLqTeQzPPzsWmkGX2qZJPDIRN" + "RZfJzti6+oLJwaRA/3krjviUty4VKhZ3lKg8fd9U0jEdnw+ePA7yJ6gZmBHL15U5" + "OKH4Zo+OVgDhO0c+oetFpend+eKcvtoUcRoQoi8VqzYUNG0b/nmZGDlxQe1/ZNbP" + "HpNf1BAtJXivCEKMD6PVzsLPg2L4tFIvD9faeeuKYQ4jcWtTkBLuIaZba3i3a4wG" + "xTN20j9HpISVuLW/EfZAK1ef4DNjLmHEU9dMzDqfi+hPmMbGlFqcKr+VjcYIDuje" + "o+92xm/EWAmlti88r2hZ3MySamHDrLABAIkATAQYEQIADAUCPYrmtgUbDAAAAAAK" + "CRDJM3gHb/sRjzVTAKDVS+OJLMeS9VLAmT8atVCB42MwIQCgoh1j3ccWnhc/h6B7" + "9Uqz3fUvGoewAWA="); private static readonly byte[] sec8 = Base64.Decode( "lQHpBEEcraYRBADFYj+uFOhHz5SdECvJ3Z03P47gzmWLQ5HH8fPYC9rrv7AgqFFX" + "aWlJJVMLua9e6xoCiDWJs/n4BbZ/weL/11ELg6XqUnzFhYyz0H2KFsPgQ/b9lWLY" + "MtcPMFy5jE33hv/ixHgYLFqoNaAIbg0lzYEW/otQ9IhRl16fO1Q/CQZZrQCg/9M2" + "V2BTmm9RYog86CXJtjawRBcD/RIqU0zulxZ2Zt4javKVxrGIwW3iBU935ebmJEIK" + "Y5EVkGKBOCvsApZ+RGzpYeR2uMsTnQi8RJgiAnjaoVPCdsVJE7uQ0h8XuJ5n5mJ2" + "kLCFlF2hj5ViicZzse+crC12CGtgRe8z23ubLRcd6IUGhVutK8/b5knZ22vE14JD" + "ykKdA/96ObzJQdiuuPsEWN799nUUCaYWPAoLAmiXuICSP4GEnxLbYHWo8zhMrVMT" + "9Q5x3h8cszUz7Acu2BXjP1m96msUNoxPOZtt88NlaFz1Q/JSbQTsVOMd9b/IRN6S" + "A/uU0BiKEMHXuT8HUHVPK49oCKhZrGFP3RT8HZxDKLmR/qrgZ/4JAwLXyWhb4pf4" + "nmCmD0lDwoYvatLiR7UQVM2MamxClIiT0lCPN9C2AYIFgRWAJNS215Tjx7P/dh7e" + "8sYfh5XEHErT3dMbsAGHtCFKaWEgWWl5dSA8eXlqaWFAbm93bWVkaWF0ZWNoLmNv" + "bT6wAwP//4kAXQQQEQIAHQUCQRytpgcLCQgHAwIKAhkBBRsDAAAABR4BAAAAAAoJ" + "EPT+Vvgr/2IUmWEAoJEyJ9B7CJfmjwVTT30UbdCctVRmAJ9akw6we6UYd82vF0FK" + "QTlSuqHXKbABZ50CawRBHK2mEAgA9kJXtwh/CBdyorrWqULzBej5UxE5T7bxbrlL" + "OCDaAadWoxTpj0BV89AHxstDqZSt90xkhkn4DIO9ZekX1KHTUPj1WV/cdlJPPT2N" + "286Z4VeSWc39uK50T8X8dryDxUcwYc58yWb/Ffm7/ZFexwGq01uejaClcjrUGvC/" + "RgBYK+X0iP1YTknbzSC0neSRBzZrM2w4DUUdD3yIsxx8Wy2O9vPJI8BD8KVbGI2O" + "u1WMuF040zT9fBdXQ6MdGGzeMyEstSr/POGxKUAYEY18hKcKctaGxAMZyAcpesqV" + "DNmWn6vQClCbAkbTCD1mpF1Bn5x8vYlLIhkmuquiXsNV6TILOwACAgf/crbApFLO" + "QikN9lHbn62dDxuu/dNigNmjf/A3cX+vo8aPHTXnRDyDwQALRuqbitdbM6p1LFjG" + "8g84Aabk/jL7zzjJLqPe8pxeK1Pu+P44NzalXAYMsOOsxGuixIrz3Jw8IrpH/mkP" + "tG/iX0NaLZ+Au9eokdLb+6NR/a51r2qL3E0ycFciJ61HzZKKHi6d0VQ7CHozCz+j" + "d5530Mh1qq/ZjYDDjfP+snpyNIZXcLtGR/3HzkBqNgDcvClLx3322AWKDa7pX8DX" + "qiLr8znWhPRpH9kCTnSpRzhYGT25FRcvdj4/q/oUIET/Tp+BWW3BxAc7WgpgqEfn" + "fa0Mv72Zbn91gf4JAwITijME9IlFBGAwH6YmBtWIlnDiRbsq/Pxozuhbnes831il" + "KmdpUKXkiIfHY0MqrEWl3Dfn6PMJGTnhgqXMrDxx3uHrq0Jl2swRnAWIIO8gID7j" + "uPetUqEviPiwAYeJAEwEGBECAAwFAkEcraYFGwwAAAAACgkQ9P5W+Cv/YhShrgCg" + "+JW8m5nF3R/oZGuG87bXQBszkjMAoLhGPncuGKowJXMRVc70/8qwXQJLsAFn"); private static readonly char[] sec8pass = "qwertyui".ToCharArray(); private static readonly byte[] sec9 = Base64.Decode( "lQGqBEHCokERBAC9rh5SzC1sX1y1zoFuBB/v0SGhoKMEvLYf8Qv/j4deAMrc" + "w5dxasYoD9oxivIUfTbZKo8cqr+dKLgu8tycigTM5b/T2ms69SUAxSBtj2uR" + "LZrh4vjC/93kF+vzYJ4fNaBs9DGfCnsTouKjXqmfN3SlPMKNcGutO7FaUC3d" + "zcpYfwCg7qyONHvXPhS0Iw4QL3mJ/6wMl0UD/0PaonqW0lfGeSjJSM9Jx5Bt" + "fTSlwl6GmvYmI8HKvOBXAUSTZSbEkMsMVcIgf577iupzgWCgNF6WsNqQpKaq" + "QIq1Kjdd0Y00xU1AKflOkhl6eufTigjviM+RdDlRYsOO5rzgwDTRTu9giErs" + "XIyJAIZIdu2iaBHX1zHTfJ1r7nlAA/9H4T8JIhppUk/fLGsoPNZzypzVip8O" + "mFb9PgvLn5GmuIC2maiocT7ibbPa7XuXTO6+k+323v7PoOUaKD3uD93zHViY" + "Ma4Q5pL5Ajc7isnLXJgJb/hvvB1oo+wSDo9vJX8OCSq1eUPUERs4jm90/oqy" + "3UG2QVqs5gcKKR4o48jTiv4DZQJHTlUBtB1mb28ga2V5IDxmb28ua2V5QGlu" + "dmFsaWQuY29tPoheBBMRAgAeBQJBwqJCAhsDBgsJCAcDAgMVAgMDFgIBAh4B" + "AheAAAoJEOKcXvehtw4ajJMAoK9nLfsrRY6peq56l/KzmjzuaLacAKCXnmiU" + "waI7+uITZ0dihJ3puJgUz50BWARBwqJDEAQA0DPcNIn1BQ4CDEzIiQkegNPY" + "mkYyYWDQjb6QFUXkuk1WEB73TzMoemsA0UKXwNuwrUgVhdpkB1+K0OR/e5ik" + "GhlFdrDCqyT+mw6dRWbJ2i4AmFXZaRKO8AozZeWojsfP1/AMxQoIiBEteMFv" + "iuXnZ3pGxSfZYm2+33IuPAV8KKMAAwUD/0C2xZQXgVWTiVz70HUviOmeTQ+f" + "b1Hj0U9NMXWB383oQRBZCvQDM12cqGsvPZuZZ0fkGehGAIoyXtIjJ9lejzZN" + "1TE9fnXZ9okXI4yCl7XLSE26OAbNsis4EtKTNScNaU9Dk3CS5XD/pkRjrkPN" + "2hdUFtshuGmYkqhb9BIlrwE7/gMDAglbVSwecr9mYJcDYCH62U9TScWDTzsQ" + "NFEfhMez3hGnNHNfHe+7yN3+Q9/LIhbba3IJEN5LsE5BFvudLbArp56EusIn" + "JCxgiEkEGBECAAkFAkHCokMCGwwACgkQ4pxe96G3Dho2UQCeN3VPwx3dROZ+" + "4Od8Qj+cLrBndGEAn0vaQdy6eIGeDw2I9u3Quwy6JnROnQHhBEHCozMRBADH" + "ZBlB6xsAnqFYtYQOHr4pX6Q8TrqXCiHHc/q56G2iGbI9IlbfykQzaPHgWqZw" + "9P0QGgF/QZh8TitiED+imLlGDqj3nhzpazqDh5S6sg6LYkQPqhwG/wT5sZQQ" + "fzdeupxupjI5YN8RdIqkWF+ILOjk0+awZ4z0TSY/f6OSWpOXlwCgjIquR3KR" + "tlCLk+fBlPnOXaOjX+kEAJw7umykNIHNaoY/2sxNhQhjqHVxKyN44y6FCSv9" + "jRyW8Q/Qc8YhqBIHdmlcXoNWkDtlvErjdYMvOKFqKB1e2bGpjvhtIhNVQWdk" + "oHap9ZuM1nV0+fD/7g/NM6D9rOOVCahBG2fEEeIwxa2CQ7zHZYfg9Umn3vbh" + "TYi68R3AmgLOA/wKIVkfFKioI7iX4crQviQHJK3/A90SkrjdMQwLoiUjdgtk" + "s7hJsTP1OPb2RggS1wCsh4sv9nOyDULj0T0ySGv7cpyv5Nq0FY8gw2oogHs5" + "fjUnG4VeYW0zcIzI8KCaJT4UhR9An0A1jF6COrYCcjuzkflFbQLtQb9uNj8a" + "hCpU4/4DAwIUxXlRMYE8uWCranzPo83FnBPRnGJ2aC9SqZWJYVUKIn4Vf2nu" + "pVvCGFja0usl1WfV72hqlNKEONq7lohJBBgRAgAJBQJBwqMzAhsCAAoJEOKc" + "Xvehtw4afisAoME/t8xz/rj/N7QRN9p8Ji8VPGSqAJ9K8eFJ+V0mxR+octJr" + "6neEEX/i1Q=="); public char[] sec9pass = "foo".ToCharArray(); // version 4 keys with expiry dates private static readonly byte[] pub10 = Base64.Decode( "mQGiBEKqia0RBACc3hkufmscRSC4UvPZqMDsHm4+d/GXIr+3iNMSSEySJu8yk+k0" + "Xs11C/K+n+v1rnn2jGGknv+1lDY6w75TIcTE6o6HGKeIDxsAm8P3MhoGU1GNPamA" + "eTDeNybtrN/g6C65fCY9uI11hsUboYgQZ8ND22PB0VtvdOgq9D85qNUzxwCg1BbJ" + "ycAKd4VqEvQ2Zglp3dCSrFMD/Ambq1kZqYa69sp3b9BPKuAgUgUPoytOArEej3Bk" + "easAgAxNhWJy4GxigES3vk50rVi7w8XBuqbD1mQCzldF0HX0/A7PxLBv6od5uqqF" + "HFxIyxg/KBZLd9ZOrsSaoUWH58jZq98X/sFtJtRi5VuJagMxCIJD4mLgtMv7Unlb" + "/GrsA/9DEnObA/fNTgK70T+ZmPIS5tSt+bio30Aw4YGpPCGqpnm1u73b5kqX3U3B" + "P+vGDvFuqZYpqQA8byAueH0MbaDHI4CFugvShXvgysJxN7ov7/8qsZZUMfK1t2Nr" + "SAsPuKRbcY4gNKXIElKeXbyaET7vX7uAEKuxEwdYGFp/lNTkHLQgdGVzdCBrZXkg" + "KHRlc3QpIDx0ZXN0QHRlc3QudGVzdD6IZAQTEQIAJAUCQqqJrQIbAwUJACTqAAYL" + "CQgHAwIDFQIDAxYCAQIeAQIXgAAKCRDjDROQZRqIzDzLAJ42AeCRIBBjv8r8qw9y" + "laNj2GZ1sACgiWYHVXMA6B1H9I1kS3YsCd3Oq7qwAgAAuM0EQqqJrhADAKWkix8l" + "pJN7MMTXob4xFF1TvGll0UD1bDGOMMbes6aeXSbT9QXee/fH3GnijLY7wB+qTPv9" + "ohubrSpnv3yen3CEBW6Q2YK+NlCskma42Py8YMV2idmYjtJi1ckvHFWt5wADBQL/" + "fkB5Q5xSGgspMaTZmtmX3zG7ZDeZ0avP8e8mRL8UszCTpqs6vMZrXwyQLZPbtMYv" + "PQpuRGEeKj0ysimwYRA5rrLQjnRER3nyuuEUUgc4j+aeRxPf9WVsJ/a1FCHtaAP1" + "iE8EGBECAA8FAkKqia4CGwwFCQAk6gAACgkQ4w0TkGUaiMzdqgCfd66H7DL7kFGd" + "IoS+NIp8JO+noxAAn25si4QAF7og8+4T5YQUuhIhx/NesAIAAA=="); private static readonly byte[] sec10 = Base64.Decode( "lQHhBEKqia0RBACc3hkufmscRSC4UvPZqMDsHm4+d/GXIr+3iNMSSEySJu8yk+k0" + "Xs11C/K+n+v1rnn2jGGknv+1lDY6w75TIcTE6o6HGKeIDxsAm8P3MhoGU1GNPamA" + "eTDeNybtrN/g6C65fCY9uI11hsUboYgQZ8ND22PB0VtvdOgq9D85qNUzxwCg1BbJ" + "ycAKd4VqEvQ2Zglp3dCSrFMD/Ambq1kZqYa69sp3b9BPKuAgUgUPoytOArEej3Bk" + "easAgAxNhWJy4GxigES3vk50rVi7w8XBuqbD1mQCzldF0HX0/A7PxLBv6od5uqqF" + "HFxIyxg/KBZLd9ZOrsSaoUWH58jZq98X/sFtJtRi5VuJagMxCIJD4mLgtMv7Unlb" + "/GrsA/9DEnObA/fNTgK70T+ZmPIS5tSt+bio30Aw4YGpPCGqpnm1u73b5kqX3U3B" + "P+vGDvFuqZYpqQA8byAueH0MbaDHI4CFugvShXvgysJxN7ov7/8qsZZUMfK1t2Nr" + "SAsPuKRbcY4gNKXIElKeXbyaET7vX7uAEKuxEwdYGFp/lNTkHP4DAwLssmOjVC+d" + "mWB783Lpzjb9evKzsxisTdx8/jHpUSS+r//6/Guyx3aA/zUw5bbftItW57mhuNNb" + "JTu7WrQgdGVzdCBrZXkgKHRlc3QpIDx0ZXN0QHRlc3QudGVzdD6IZAQTEQIAJAUC" + "QqqJrQIbAwUJACTqAAYLCQgHAwIDFQIDAxYCAQIeAQIXgAAKCRDjDROQZRqIzDzL" + "AJ0cYPwKeoSReY14LqJtAjnkX7URHACgsRZWfpbalrSyDnq3TtZeGPUqGX+wAgAA" + "nQEUBEKqia4QAwClpIsfJaSTezDE16G+MRRdU7xpZdFA9WwxjjDG3rOmnl0m0/UF" + "3nv3x9xp4oy2O8Afqkz7/aIbm60qZ798np9whAVukNmCvjZQrJJmuNj8vGDFdonZ" + "mI7SYtXJLxxVrecAAwUC/35AeUOcUhoLKTGk2ZrZl98xu2Q3mdGrz/HvJkS/FLMw" + "k6arOrzGa18MkC2T27TGLz0KbkRhHio9MrIpsGEQOa6y0I50REd58rrhFFIHOI/m" + "nkcT3/VlbCf2tRQh7WgD9f4DAwLssmOjVC+dmWDXVLRopzxbBGOvodp/LZoSDb56" + "gNJjDMJ1aXqWW9qTAg1CFjBq73J3oFpVzInXZ8+Q8inxv7bnWiHbiE8EGBECAA8F" + "AkKqia4CGwwFCQAk6gAACgkQ4w0TkGUaiMzdqgCgl2jw5hfk/JsyjulQqe1Nps1q" + "Lx0AoMdnFMZmTMLHn8scUW2j9XO312tmsAIAAA=="); // private static readonly char[] sec10pass = "test".ToCharArray(); private static readonly byte[] subKeyBindingKey = Base64.Decode( "mQGiBDWagYwRBAD7UcH4TAIp7tmUoHBNxVxCVz2ZrNo79M6fV63riOiH2uDxfIpr" + "IrL0cM4ehEKoqlhngjDhX60eJrOw1nC5BpYZRnDnyDYT4wTWRguxObzGq9pqA1dM" + "oPTJhkFZVIBgFY99/ULRqaUYIhFGgBtnwS70J8/L/PGVc3DmWRLMkTDjSQCg/5Nh" + "MCjMK++MdYMcMl/ziaKRT6EEAOtw6PnU9afdohbpx9CK4UvCCEagfbnUtkSCQKSk" + "6cUp6VsqyzY0pai/BwJ3h4apFMMMpVrtBAtchVgqo4xTr0Sve2j0k+ase6FSImiB" + "g+AR7hvTUTcBjwtIExBc8TuCTqmn4GG8F7UMdl5Z0AZYj/FfAQYaRVZYP/pRVFNx" + "Lw65BAC/Fi3qgiGCJFvXnHIckTfcAmZnKSEXWY9NJ4YQb4+/nH7Vsw0wR/ZObUHR" + "bWgTc9Vw1uZIMe0XVj6Yk1dhGRehUnrm3mE7UJxu7pgkBCbFECFSlSSqP4MEJwZV" + "09YP/msu50kjoxyoTpt+16uX/8B4at24GF1aTHBxwDLd8X0QWrQsTWVycmlsbCBM" + "eW5jaCBDTEVBUiBzeXN0ZW0gREggPGNsZWFyQG1sLmNvbT6JAEsEEBECAAsFAjWa" + "gYwECwMBAgAKCRDyAGjiP47/XanfAKCs6BPURWVQlGh635VgL+pdkUVNUwCdFcNa" + "1isw+eAcopXPMj6ACOapepu5Ag0ENZqBlBAIAPZCV7cIfwgXcqK61qlC8wXo+VMR" + "OU+28W65Szgg2gGnVqMU6Y9AVfPQB8bLQ6mUrfdMZIZJ+AyDvWXpF9Sh01D49Vlf" + "3HZSTz09jdvOmeFXklnN/biudE/F/Ha8g8VHMGHOfMlm/xX5u/2RXscBqtNbno2g" + "pXI61Brwv0YAWCvl9Ij9WE5J280gtJ3kkQc2azNsOA1FHQ98iLMcfFstjvbzySPA" + "Q/ClWxiNjrtVjLhdONM0/XwXV0OjHRhs3jMhLLUq/zzhsSlAGBGNfISnCnLWhsQD" + "GcgHKXrKlQzZlp+r0ApQmwJG0wg9ZqRdQZ+cfL2JSyIZJrqrol7DVekyCzsAAgIH" + "/RYtVo+HROZ6jrNjrATEwQm1fUQrk6n5+2dniN881lF0CNkB4NkHw1Xxz4Ejnu/0" + "iLg8fkOAsmanOsKpOkRtqUnVpsVL5mLJpFEyCY5jbcfj+KY9/25bs0ga7kLHNZia" + "zbCxJdF+W179z3nudQxRaXG/0XISIH7ziZbSVni69sKc1osk1+OoOMbSuZ86z535" + "Pln4fXclkFE927HxfbWoO+60hkOLKh7x+8fC82b3x9vCETujEaxrscO2xS7/MYXP" + "8t1ffriTDmhuIuQS2q4fLgeWdqrODrMhrD8Dq7e558gzp30ZCqpiS7EmKGczL7B8" + "gXxbBCVSTxYMJheXt2xMXsuJAD8DBRg1moGU8gBo4j+O/10RAgWdAKCPhaFIXuC8" + "/cdiNMxTDw9ug3De5QCfYXmDzRSFUu/nrCi8yz/l09wsnxo="); // private static readonly byte[] subKeyBindingCheckSum = Base64.Decode("3HU+"); // // PGP8 with SHA1 checksum. // private static readonly byte[] rewrapKey = Base64.Decode( "lQOWBEUPOQgBCADdjPTtl8oOwqJFA5WU8p7oDK5KRWfmXeXUZr+ZJipemY5RSvAM" + "rxqsM47LKYbmXOJznXCQ8+PPa+VxXAsI1CXFHIFqrXSwvB/DUmb4Ec9EuvNd18Zl" + "hJAybzmV2KMkaUp9oG/DUvxZJqkpUddNfwqZu0KKKZWF5gwW5Oy05VCpaJxQVXFS" + "whdbRfwEENJiNx4RB3OlWhIjY2p+TgZfgQjiGB9i15R+37sV7TqzBUZF4WWcnIRQ" + "DnpUfxHgxQ0wO/h/aooyRHSpIx5i4oNpMYq9FNIyakEx/Bomdbs5hW9dFxhrE8Es" + "UViAYITgTsyROxmgGatGG09dcmVDJVYF4i7JAAYpAAf/VnVyUDs8HrxYTOIt4rYY" + "jIHToBsV0IiLpA8fEA7k078L1MwSwERVVe6oHVTjeR4A9OxE52Vroh2eOLnF3ftf" + "6QThVVZr+gr5qeG3yvQ36N7PXNEVOlkyBzGmFQNe4oCA+NR2iqnAIspnekVmwJV6" + "xVvPCjWw/A7ZArDARpfthspwNcJAp4SWfoa2eKzvUTznTyqFu2PSS5fwQZUgOB0P" + "Y2FNaKeqV8vEZu4SUWwLOqXBQIZXiaLvdKNgwFvUe3kSHdCNsrVzW7SYxFwaEog2" + "o6YLKPVPqjlGX1cMOponGp+7n9nDYkQjtEsGSSMQkQRDAcBdSVJmLO07kFOQSOhL" + "WQQA49BcgTZyhyH6TnDBMBHsGCYj43FnBigypGT9FrQHoWybfX47yZaZFROAaaMa" + "U6man50YcYZPwzDzXHrK2MoGALY+DzB3mGeXVB45D/KYtlMHPLgntV9T5b14Scbc" + "w1ES2OUtsSIUs0zelkoXqjLuKnSIYK3mMb67Au7AEp6LXM8EAPj2NypvC86VEnn+" + "FH0QHvUwBpmDw0EZe25xQs0brvAG00uIbiZnTH66qsIfRhXV/gbKK9J5DTGIqQ15" + "DuPpz7lcxg/n2+SmjQLNfXCnG8hmtBjhTe+udXAUrmIcfafXyu68SAtebgm1ga56" + "zUfqsgN3FFuMUffLl3myjyGsg5DnA/oCFWL4WCNClOgL6A5VkNIUait8QtSdCACT" + "Y7jdSOguSNXfln0QT5lTv+q1AjU7zjRl/LsFNmIJ5g2qdDyK937FOXM44FEEjZty" + "/4P2dzYpThUI4QUohIj8Qi9f2pZQueC5ztH6rpqANv9geZKcciAeAbZ8Md0K2TEU" + "RD3Lh+RSBzILtBtUZXN0IEtleSA8dGVzdEBleGFtcGxlLmNvbT6JATYEEwECACAF" + "AkUPOQgCGwMGCwkIBwMCBBUCCAMEFgIDAQIeAQIXgAAKCRDYpknHeQaskD9NB/9W" + "EbFuLaqZAl3yjLU5+vb75BdvcfL1lUs44LZVwobNp3/0XbZdY76xVPNZURtU4u3L" + "sJfGlaF+EqZDE0Mqc+vs5SIb0OnCzNJ00KaUFraUtkByRV32T5ECHK0gMBjCs5RT" + "I0vVv+Qmzl4+X1Y2bJ2mlpBejHIrOzrBD5NTJimTAzyfnNfipmbqL8p/cxXKKzS+" + "OM++ZFNACj6lRM1W9GioXnivBRC88gFSQ4/GXc8yjcrMlKA27JxV+SZ9kRWwKH2f" + "6o6mojUQxnHr+ZFKUpo6ocvTgBDlC57d8IpwJeZ2TvqD6EdA8rZ0YriVjxGMDrX1" + "8esfw+iLchfEwXtBIRwS"); private static readonly char[] rewrapPass = "voltage123".ToCharArray(); private static readonly byte[] pubWithX509 = Base64.Decode( "mQENBERabjABCACtmfyo6Nph9MQjv4nmCWjZrRYnhXbivomAdIwYkLZUj1bjqE+j" + "uaLzjZV8xSI59odZvrmOiqlzOc4txitQ1OX7nRgbOJ7qku0dvwjtIn46+HQ+cAFn" + "2mTi81RyXEpO2uiZXfsNTxUtMi+ZuFLufiMc2kdk27GZYWEuasdAPOaPJnA+wW6i" + "ZHlt0NfXIGNz864gRwhD07fmBIr1dMFfATWxCbgMd/rH7Z/j4rvceHD2n9yrhPze" + "YN7W4Nuhsr2w/Ft5Cm9xO7vXT/cpto45uxn8f7jERep6bnUwNOhH8G+6xLQgTLD0" + "qFBGVSIneK3lobs6+xn6VaGN8W0tH3UOaxA1ABEBAAG0D0NOPXFhLWRlZXBzaWdo" + "dIkFDgQQZAIFAQUCRFpuMAUDCWdU0gMF/3gCGwPELGQBAQQwggTkMIIDzKADAgEC" + "AhBVUMV/M6rIiE+IzmnPheQWMA0GCSqGSIb3DQEBBQUAMG4xEzARBgoJkiaJk/Is" + "ZAEZFgNjb20xEjAQBgoJkiaJk/IsZAEZFgJxYTEVMBMGCgmSJomT8ixkARkWBXRt" + "czAxMRUwEwYKCZImiZPyLGQBGRYFV2ViZmUxFTATBgNVBAMTDHFhLWRlZXBzaWdo" + "dDAeFw0wNjA1MDQyMTEyMTZaFw0xMTA1MDQyMTIwMDJaMG4xEzARBgoJkiaJk/Is" + "ZAEZFgNjb20xEjAQBgoJkiaJk/IsZAEZFgJxYTEVMBMGCgmSJomT8ixkARkWBXRt" + "czAxMRUwEwYKCZImiZPyLGQBGRYFV2ViZmUxFTATBgNVBAMTDHFhLWRlZXBzaWdo" + "dDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAK2Z/Kjo2mH0xCO/ieYJ" + "aNmtFieFduK+iYB0jBiQtlSPVuOoT6O5ovONlXzFIjn2h1m+uY6KqXM5zi3GK1DU" + "5fudGBs4nuqS7R2/CO0ifjr4dD5wAWfaZOLzVHJcSk7a6Jld+w1PFS0yL5m4Uu5+" + "IxzaR2TbsZlhYS5qx0A85o8mcD7BbqJkeW3Q19cgY3PzriBHCEPTt+YEivV0wV8B" + "NbEJuAx3+sftn+Piu9x4cPaf3KuE/N5g3tbg26GyvbD8W3kKb3E7u9dP9ym2jjm7" + "Gfx/uMRF6npudTA06Efwb7rEtCBMsPSoUEZVIid4reWhuzr7GfpVoY3xbS0fdQ5r" + "EDUCAwEAAaOCAXwwggF4MAsGA1UdDwQEAwIBhjAPBgNVHRMBAf8EBTADAQH/MB0G" + "A1UdDgQWBBSmFTRv5y65DHtTYae48zl0ExNWZzCCASUGA1UdHwSCARwwggEYMIIB" + "FKCCARCgggEMhoHFbGRhcDovLy9DTj1xYS1kZWVwc2lnaHQsQ049cWEtd3VtYW4x" + "LWRjLENOPUNEUCxDTj1QdWJsaWMlMjBLZXklMjBTZXJ2aWNlcyxDTj1TZXJ2aWNl" + "cyxDTj1Db25maWd1cmF0aW9uLERDPVdlYmZlLERDPXRtczAxLERDPXFhLERDPWNv" + "bT9jZXJ0aWZpY2F0ZVJldm9jYXRpb25MaXN0P2Jhc2U/b2JqZWN0Q2xhc3M9Y1JM" + "RGlzdHJpYnV0aW9uUG9pbnSGQmh0dHA6Ly9xYS13dW1hbjEtZGMud2ViZmUudG1z" + "MDEucWEuY29tL0NlcnRFbnJvbGwvcWEtZGVlcHNpZ2h0LmNybDAQBgkrBgEEAYI3" + "FQEEAwIBADANBgkqhkiG9w0BAQUFAAOCAQEAfuZCW3XlB7Eok35zQbvYt9rhAndT" + "DNw3wPNI4ZzD1nXoYWnwhNNvWRpsOt4ExOSNdaHErfgDXAMyyg66Sro0TkAx8eAj" + "fPQsyRAh0nm0glzFmJN6TdOZbj7hqGZjc4opQ6nZo8h/ULnaEwMIUW4gcSkZt0ww" + "CuErl5NUrN3DpkREeCG/fVvQZ8ays3ibQ5ZCZnYBkLYq/i0r3NLW34WfYhjDY48J" + "oQWtvFSAxvRfz2NGmqnrCHPQZxqlfdta97kDa4VQ0zSeBaC70gZkLmD1GJMxWoXW" + "6tmEcgPY5SghInUf+L2u52V55MjyAFzVp7kTK2KY+p7qw35vzckrWkwu8AAAAAAA" + "AQE="); private static readonly byte[] secWithPersonalCertificate = Base64.Decode( "lQOYBEjGLGsBCACp1I1dZKsK4N/I0/4g02hDVNLdQkDZfefduJgyJUyBGo/I" + "/ZBpc4vT1YwVIdic4ADjtGB4+7WohN4v8siGzwRSeXardSdZVIw2va0JDsQC" + "yeoTnwVkUgn+w/MDgpL0BBhTpr9o3QYoo28/qKMni3eA8JevloZqlAbQ/sYq" + "rToMAqn0EIdeVVh6n2lRQhUJaNkH/kA5qWBpI+eI8ot/Gm9kAy3i4e0Xqr3J" + "Ff1lkGlZuV5H5p/ItZui9BDIRn4IDaeR511NQnKlxFalM/gP9R9yDVI1aXfy" + "STcp3ZcsTOTGNzACtpvMvl6LZyL42DyhlOKlJQJS81wp4dg0LNrhMFOtABEB" + "AAEAB/0QIH5UEg0pTqAG4r/3v1uKmUbKJVJ3KhJB5xeSG3dKWIqy3AaXR5ZN" + "mrJfXK7EfC5ZcSAqx5br1mzVl3PHVBKQVQxvIlmG4r/LKvPVhQYZUFyJWckZ" + "9QMR+EA0Dcran9Ds5fa4hH84jgcwalkj64XWRAKDdVh098g17HDw+IYnQanl" + "7IXbYvh+1Lr2HyPo//vHX8DxXIJBv+E4skvqGoNfCIfwcMeLsrI5EKo+D2pu" + "kAuBYI0VBiZkrJHFXWmQLW71Mc/Bj7wTG8Q1pCpu7YQ7acFSv+/IOCsB9l9S" + "vdB7pNhB3lEjYFGoTgr03VfeixA7/x8uDuSXjnBdTZqmGqkZBADNwCqlzdaQ" + "X6CjS5jc3vzwDSPgM7ovieypEL6NU3QDEUhuP6fVvD2NYOgVnAEbJzgOleZS" + "W2AFXKAf5NDxfqHnBmo/jlYb5yZV5Y+8/poLLj/m8t7sAfAmcZqGXfYMbSbe" + "tr6TGTUXcXgbRyU5oH1e4iq691LOwZ39QjL8lNQQywQA006XYEr/PS9uJkyM" + "Cg+M+nmm40goW4hU/HboFh9Ru6ataHj+CLF42O9sfMAV02UcD3Agj6w4kb5L" + "VswuwfmY+17IryT81d+dSmDLhpo6ufKoAp4qrdP+bzdlbfIim4Rdrw5vF/Yk" + "rC/Nfm3CLJxTimHJhqFx4MG7yEC89lxgdmcD/iJ3m41fwS+bPN2rrCAf7j1u" + "JNr/V/8GAnoXR8VV9150BcOneijftIIYKKyKkV5TGwcTfjaxRKp87LTeC3MV" + "szFDw04MhlIKRA6nBdU0Ay8Yu+EjXHK2VSpLG/Ny+KGuNiFzhqgBxM8KJwYA" + "ISa1UEqWjXoLU3qu1aD7cCvANPVCOASwAYe0GlBHUCBEZXNrdG9wIDxpbmZv" + "QHBncC5jb20+sAMD//+JAW4EEAECAFgFAkjGLGswFIAAAAAAIAAHcHJlZmVy" + "cmVkLWVtYWlsLWVuY29kaW5nQHBncC5jb21wZ3BtaW1lBwsJCAcDAgoCGQEF" + "GwMAAAADFgECBR4BAAAABRUCCAkKAAoJEHHHqp2m1tlWsx8H/icpHl1Nw17A" + "D6MJN6zJm+aGja+5BOFxOsntW+IV6JI+l5WwiIVE8xTDhoXW4zdH3IZTqoyY" + "frtkqLGpvsPtAQmV6eiPgE3+25ahL+MmjXKsceyhbZeCPDtM2M382VCHYCZK" + "DZ4vrHVgK/BpyTeP/mqoWra9+F5xErhody71/cLyIdImLqXgoAny6YywjuAD" + "2TrFnzPEBmZrkISHVEso+V9sge/8HsuDqSI03BAVWnxcg6aipHtxm907sdVo" + "jzl2yFbxCCCaDIKR7XVbmdX7VZgCYDvNSxX3WEOgFq9CYl4ZlXhyik6Vr4XP" + "7EgqadtfwfMcf4XrYoImSQs0gPOd4QqwAWedA5gESMYsawEIALiazFREqBfi" + "WouTjIdLuY09Ks7PCkn0eo/i40/8lEj1R6JKFQ5RlHNnabh+TLvjvb3nOSU0" + "sDg+IKK/JUc8/Fo7TBdZvARX6BmltEGakqToDC3eaF9EQgHLEhyE/4xXiE4H" + "EeIQeCHdC7k0pggEuWUn5lt6oeeiPUWhqdlUOvzjG+jqMPJL0bk9STbImHUR" + "EiugCPTekC0X0Zn0yrwyqlJQMWnh7wbSl/uo4q45K7qOhxcijo+hNNrkRAMi" + "fdNqD4s5qDERqqHdAAgpWqydo7zV5tx0YSz5fjh59Z7FxkUXpcu1WltT6uVn" + "hubiMTWpXzXOQI8wZL2fb12JmRY47BEAEQEAAQAH+wZBeanj4zne+fBHrWAS" + "2vx8LYiRV9EKg8I/PzKBVdGUnUs0vTqtXU1dXGXsAsPtu2r1bFh0TQH06gR1" + "24iq2obgwkr6x54yj+sZlE6SU0SbF/mQc0NCNAXtSKV2hNXvy+7P+sVJR1bn" + "b5ukuvkj1tgEln/0W4r20qJ60F+M5QxXg6kGh8GAlo2tetKEv1NunAyWY6iv" + "FTnSaIJ/YaKQNcudNvOJjeIakkIzfzBL+trUiI5n1LTBB6+u3CF/BdZBTxOy" + "QwjAh6epZr+GnQqeaomFxBc3mU00sjrsB1Loso84UIs6OKfjMkPoZWkQrQQW" + "+xvQ78D33YwqNfXk/5zQAxkEANZxJGNKaAeDpN2GST/tFZg0R5GPC7uWYC7T" + "pG100mir9ugRpdeIFvfAa7IX2jujxo9AJWo/b8hq0q0koUBdNAX3xxUaWy+q" + "KVCRxBifpYVBfEViD3lsbMy+vLYUrXde9087YD0c0/XUrj+oowWJavblmZtS" + "V9OjkQW9zoCigpf5BADcYV+6bkmJtstxJopJG4kD/lr1o35vOEgLkNsMLayc" + "NuzES084qP+8yXPehkzSsDB83kc7rKfQCQMZ54V7KCCz+Rr4wVG7FCrFAw4e" + "4YghfGVU/5whvbJohl/sXXCYGtVljvY/BSQrojRdP+/iZxFbeD4IKiTjV+XL" + "WKSS56Fq2QQAzeoKBJFUq8nqc8/OCmc52WHSOLnB4AuHL5tNfdE9tjqfzZAE" + "tx3QB7YGGP57tPQxPFDFJVRJDqw0YxI2tG9Pum8iriKGjHg+oEfFhxvCmPxf" + "zDKaGibkLeD7I6ATpXq9If+Nqb5QjzPjFbXBIz/q2nGjamZmp4pujKt/aZxF" + "+YRCebABh4kCQQQYAQIBKwUCSMYsbAUbDAAAAMBdIAQZAQgABgUCSMYsawAK" + "CRCrkqZshpdZSNAiB/9+5nAny2O9/lp2K2z5KVXqlNAHUmd4S/dpqtsZCbAo" + "8Lcr/VYayrNojga1U7cyhsvFky3N9wczzPHq3r9Z+R4WnRM1gpRWl+9+xxtd" + "ZxGfGzMRlxX1n5rCqltKKk6IKuBAr2DtTnxThaQiISO2hEw+P1MT2HnSzMXt" + "zse5CZ5OiOd/bm/rdvTRD/JmLqhXmOFaIwzdVP0dR9Ld4Dug2onOlIelIntC" + "cywY6AmnL0DThaTy5J8MiMSPamSmATl4Bicm8YRbHHz58gCYxI5UMLwtwR1+" + "rSEmrB6GwVHZt0/BzOpuGpvFZI5ZmC5yO/waR1hV+VYj025cIz+SNuDPyjy4" + "AAoJEHHHqp2m1tlW/w0H/3w38SkB5n9D9JL3chp+8fex03t7CQowVMdsBYNY" + "qI4QoVQkakkxzCz5eF7rijXt5eC3NE/quWhlMigT8LARiwBROBWgDRFW4WuX" + "6MwYtjKKUkZSkBKxP3lmaqZrJpF6jfhPEN76zr/NxWPC/nHRNldUdqkzSu/r" + "PeJyePMofJevzMkUzw7EVtbtWhZavCz+EZXRTZXub9M4mDMj64BG6JHMbVZI" + "1iDF2yka5RmhXz9tOhYgq80m7UQUb1ttNn86v1zVbe5lmB8NG4Ndv+JaaSuq" + "SBZOYQ0ZxtMAB3vVVLZCWxma1P5HdXloegh+hosqeu/bl0Wh90z5Bspt6eI4" + "imqwAWeVAdgESMYtmwEEAM9ZeMFxor7oSoXnhQAXD9lXLLfBky6IcIWISY4F" + "JWc8sK8+XiVzpOrefKro0QvmEGSYcDFQMHdScBLOTsiVJiqenA7fg1bkBr/M" + "bnD7vTKMJe0DARlU27tE5hsWCDYTluxIFjGcAcecY2UqHkqpctYKY0WY9EIm" + "dBA5TYaw3c0PABEBAAEAA/0Zg6318nC57cWLIp5dZiO/dRhTPZD0hI+BWZrg" + "zJtPT8rXVY+qK3Jwquig8z29/r+nppEE+xQWVWDlv4M28BDJAbGE+qWKAZqT" + "67lyKgc0c50W/lfbGvvs+F7ldCcNpFvlk79GODKxcEeTGDQKb9R6FnHFee/K" + "cZum71O3Ku3vUQIA3B3PNM+tKocIUNDHnInuLyqLORwQBNGfjU/pLMM0MkpP" + "lWeIfgUmn2zL/e0JrRoO0LQqX1LN/TlfcurDM0SEtwIA8Sba9OpDq99Yz360" + "FiePJiGNNlbj9EZsuGJyMVXL1mTLA6WHnz5XZOfYqJXHlmKvaKDbARW4+0U7" + "0/vPdYWSaQIAwYeo2Ce+b7M5ifbGMDWYBisEvGISg5xfvbe6qApmHS4QVQzE" + "Ym81rdJJ8OfvgSbHcgn37S3OBXIQvNdejF4BWqM9sAGHtCBIeW5lay1JbnRy" + "YW5ldCA8aHluZWtAYWxzb2Z0LmN6PrADA///iQDrBBABAgBVBQJIxi2bBQkB" + "mgKAMBSAAAAAACAAB3ByZWZlcnJlZC1lbWFpbC1lbmNvZGluZ0BwZ3AuY29t" + "cGdwbWltZQULBwgJAgIZAQUbAQAAAAUeAQAAAAIVAgAKCRDlTa3BE84gWVKW" + "BACcoCFKvph9r9QiHT1Z3N4wZH36Uxqu/059EFALnBkEdVudX/p6S9mynGRk" + "EfhmWFC1O6dMpnt+ZBEed/4XyFWVSLPwirML+6dxfXogdUsdFF1NCRHc3QGc" + "txnNUT/zcZ9IRIQjUhp6RkIvJPHcyfTXKSbLviI+PxzHU2Padq8pV7ABZ7kA" + "jQRIfg8tAQQAutJR/aRnfZYwlVv+KlUDYjG8YQUfHpTxpnmVu7W6N0tNg/Xr" + "5dg50wq3I4HOamRxUwHpdPkXyNF1szpDSRZmlM+VmiIvJDBnyH5YVlxT6+zO" + "8LUJ2VTbfPxoLFp539SQ0oJOm7IGMAGO7c0n/QV0N3hKUfWgCyJ+sENDa0Ft" + "JycAEQEAAbABj4kEzQQYAQIENwUCSMYtnAUJAeEzgMLFFAAAAAAAFwNleDUw" + "OWNlcnRpZmljYXRlQHBncC5jb20wggNhMIICyqADAgECAgkA1AoCoRKJCgsw" + "DQYJKoZIhvcNAQEFBQAwgakxCzAJBgNVBAYTAkNaMRcwFQYDVQQIEw5DemVj" + "aCBSZXB1YmxpYzESMBAGA1UEChQJQSYmTCBzb2Z0MSAwHgYDVQQLExdJbnRl" + "cm5hbCBEZXZlbG9wbWVudCBDQTEqMCgGA1UEAxQhQSYmTCBzb2Z0IEludGVy" + "bmFsIERldmVsb3BtZW50IENBMR8wHQYJKoZIhvcNAQkBFhBrYWRsZWNAYWxz" + "b2Z0LmN6MB4XDTA4MDcxNjE1MDkzM1oXDTA5MDcxNjE1MDkzM1owaTELMAkG" + "A1UEBhMCQ1oxFzAVBgNVBAgTDkN6ZWNoIFJlcHVibGljMRIwEAYDVQQKFAlB" + "JiZMIHNvZnQxFDASBgNVBAsTC0RldmVsb3BtZW50MRcwFQYDVQQDEw5IeW5l" + "ay1JbnRyYW5ldDCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAutJR/aRn" + "fZYwlVv+KlUDYjG8YQUfHpTxpnmVu7W6N0tNg/Xr5dg50wq3I4HOamRxUwHp" + "dPkXyNF1szpDSRZmlM+VmiIvJDBnyH5YVlxT6+zO8LUJ2VTbfPxoLFp539SQ" + "0oJOm7IGMAGO7c0n/QV0N3hKUfWgCyJ+sENDa0FtJycCAwEAAaOBzzCBzDAJ" + "BgNVHRMEAjAAMCwGCWCGSAGG+EIBDQQfFh1PcGVuU1NMIEdlbmVyYXRlZCBD" + "ZXJ0aWZpY2F0ZTAdBgNVHQ4EFgQUNaw7A6r10PtYZzAvr9CrSKeRYJgwHwYD" + "VR0jBBgwFoAUmqSRM8rN3+T1+tkGiqef8S5suYgwGgYDVR0RBBMwEYEPaHlu" + "ZWtAYWxzb2Z0LmN6MCgGA1UdHwQhMB8wHaAboBmGF2h0dHA6Ly9wZXRyazIv" + "Y2EvY2EuY3JsMAsGA1UdDwQEAwIF4DANBgkqhkiG9w0BAQUFAAOBgQCUdOWd" + "7mBLWj1/GSiYgfwgdTrgk/VZOJvMKBiiFyy1iFEzldz6Xx+mAexnFJKfZXZb" + "EMEGWHfWPmgJzAtuTT0Jz6tUwDmeLH3MP4m8uOZtmyUJ2aq41kciV3rGxF0G" + "BVlZ/bWTaOzHdm6cjylt6xxLt6MJzpPBA/9ZfybSBh1DaAUbDgAAAJ0gBBkB" + "AgAGBQJIxi2bAAoJEAdYkEWLb2R2fJED/RK+JErZ98uGo3Z81cHkdP3rk8is" + "DUL/PR3odBPFH2SIA5wrzklteLK/ZXmBUzcvxqHEgI1F7goXbsBgeTuGgZdx" + "pINErxkNpcMl9FTldWKGiapKrhkZ+G8knDizF/Y7Lg6uGd2nKVxzutLXdHJZ" + "pU89Q5nzq6aJFAZo5TBIcchQAAoJEOVNrcETziBZXvQD/1mvFqBfWqwXxoj3" + "8fHUuFrE2pcp32y3ciO2i+uNVEkNDoaVVNw5eHQaXXWpllI/Pe6LnBl4vkyc" + "n3pjONa4PKrePkEsCUhRbIySqXIHuNwZumDOlKzZHDpCUw72LaC6S6zwuoEf" + "ucOcxTeGIUViANWXyTIKkHfo7HfigixJIL8nsAFn"); [Test] public void PerformTest1() { PgpPublicKeyRingBundle pubRings = new PgpPublicKeyRingBundle(pub1); int count = 0; foreach (PgpPublicKeyRing pgpPub1 in pubRings.GetKeyRings()) { count++; int keyCount = 0; byte[] bytes = pgpPub1.GetEncoded(); PgpPublicKeyRing pgpPub2 = new PgpPublicKeyRing(bytes); foreach (PgpPublicKey pubKey in pgpPub2.GetPublicKeys()) { keyCount++; foreach (PgpSignature sig in pubKey.GetSignatures()) { if (sig == null) Fail("null signature found"); } } if (keyCount != 2) { Fail("wrong number of public keys"); } } if (count != 1) { Fail("wrong number of public keyrings"); } // // exact match // count = 0; foreach (PgpPublicKeyRing pgpPub3 in pubRings.GetKeyRings("test (Test key) <test@ubicall.com>")) { if (pgpPub3 == null) Fail("null keyring found"); count++; } if (count != 1) { Fail("wrong number of public keyrings on exact match"); } // // partial match 1 expected // count = 0; foreach (PgpPublicKeyRing pgpPub4 in pubRings.GetKeyRings("test", true)) { if (pgpPub4 == null) Fail("null keyring found"); count++; } if (count != 1) { Fail("wrong number of public keyrings on partial match 1"); } // // partial match 0 expected // count = 0; foreach (PgpPublicKeyRing pgpPub5 in pubRings.GetKeyRings("XXX", true)) { if (pgpPub5 == null) Fail("null keyring found"); count++; } if (count != 0) { Fail("wrong number of public keyrings on partial match 0"); } // // case-insensitive partial match // count = 0; foreach (PgpPublicKeyRing pgpPub6 in pubRings.GetKeyRings("TEST@ubicall.com", true, true)) { if (pgpPub6 == null) Fail("null keyring found"); count++; } if (count != 1) { Fail("wrong number of public keyrings on case-insensitive partial match"); } PgpSecretKeyRingBundle secretRings = new PgpSecretKeyRingBundle(sec1); count = 0; foreach (PgpSecretKeyRing pgpSec1 in secretRings.GetKeyRings()) { count++; int keyCount = 0; byte[] bytes = pgpSec1.GetEncoded(); PgpSecretKeyRing pgpSec2 = new PgpSecretKeyRing(bytes); foreach (PgpSecretKey k in pgpSec2.GetSecretKeys()) { keyCount++; PgpPublicKey pk = k.PublicKey; pk.GetSignatures(); byte[] pkBytes = pk.GetEncoded(); PgpPublicKeyRing pkR = new PgpPublicKeyRing(pkBytes); } if (keyCount != 2) { Fail("wrong number of secret keys"); } } if (count != 1) { Fail("wrong number of secret keyrings"); } // // exact match // count = 0; foreach (PgpSecretKeyRing o1 in secretRings.GetKeyRings("test (Test key) <test@ubicall.com>")) { if (o1 == null) Fail("null keyring found"); count++; } if (count != 1) { Fail("wrong number of secret keyrings on exact match"); } // // partial match 1 expected // count = 0; foreach (PgpSecretKeyRing o2 in secretRings.GetKeyRings("test", true)) { if (o2 == null) Fail("null keyring found"); count++; } if (count != 1) { Fail("wrong number of secret keyrings on partial match 1"); } // // exact match 0 expected // count = 0; foreach (PgpSecretKeyRing o3 in secretRings.GetKeyRings("test", false)) { if (o3 == null) Fail("null keyring found"); count++; } if (count != 0) { Fail("wrong number of secret keyrings on partial match 0"); } // // case-insensitive partial match // count = 0; foreach (PgpSecretKeyRing o4 in secretRings.GetKeyRings("TEST@ubicall.com", true, true)) { if (o4 == null) Fail("null keyring found"); count++; } if (count != 1) { Fail("wrong number of secret keyrings on case-insensitive partial match"); } } [Test] public void PerformTest2() { PgpPublicKeyRingBundle pubRings = new PgpPublicKeyRingBundle(pub2); int count = 0; byte[] encRing = pubRings.GetEncoded(); pubRings = new PgpPublicKeyRingBundle(encRing); foreach (PgpPublicKeyRing pgpPub1 in pubRings.GetKeyRings()) { count++; int keyCount = 0; byte[] bytes = pgpPub1.GetEncoded(); PgpPublicKeyRing pgpPub2 = new PgpPublicKeyRing(bytes); foreach (PgpPublicKey pk in pgpPub2.GetPublicKeys()) { byte[] pkBytes = pk.GetEncoded(); PgpPublicKeyRing pkR = new PgpPublicKeyRing(pkBytes); keyCount++; } if (keyCount != 2) { Fail("wrong number of public keys"); } } if (count != 2) { Fail("wrong number of public keyrings"); } PgpSecretKeyRingBundle secretRings2 = new PgpSecretKeyRingBundle(sec2); count = 0; encRing = secretRings2.GetEncoded(); PgpSecretKeyRingBundle secretRings = new PgpSecretKeyRingBundle(encRing); foreach (PgpSecretKeyRing pgpSec1 in secretRings2.GetKeyRings()) { count++; int keyCount = 0; byte[] bytes = pgpSec1.GetEncoded(); PgpSecretKeyRing pgpSec2 = new PgpSecretKeyRing(bytes); foreach (PgpSecretKey k in pgpSec2.GetSecretKeys()) { keyCount++; PgpPublicKey pk = k.PublicKey; if (pk.KeyId == -1413891222336124627L) { int sCount = 0; foreach (PgpSignature pgpSignature in pk.GetSignaturesOfType(PgpSignature.SubkeyBinding)) { int type = pgpSignature.SignatureType; if (type != PgpSignature.SubkeyBinding) { Fail("failed to return correct signature type"); } sCount++; } if (sCount != 1) { Fail("failed to find binding signature"); } } pk.GetSignatures(); if (k.KeyId == -4049084404703773049L || k.KeyId == -1413891222336124627L) { k.ExtractPrivateKey(sec2pass1); } else if (k.KeyId == -6498553574938125416L || k.KeyId == 59034765524361024L) { k.ExtractPrivateKey(sec2pass2); } } if (keyCount != 2) { Fail("wrong number of secret keys"); } } if (count != 2) { Fail("wrong number of secret keyrings"); } } [Test] public void PerformTest3() { PgpPublicKeyRingBundle pubRings = new PgpPublicKeyRingBundle(pub3); int count = 0; byte[] encRing = pubRings.GetEncoded(); pubRings = new PgpPublicKeyRingBundle(encRing); foreach (PgpPublicKeyRing pgpPub1 in pubRings.GetKeyRings()) { count++; int keyCount = 0; byte[] bytes = pgpPub1.GetEncoded(); PgpPublicKeyRing pgpPub2 = new PgpPublicKeyRing(bytes); foreach (PgpPublicKey pubK in pgpPub2.GetPublicKeys()) { keyCount++; pubK.GetSignatures(); } if (keyCount != 2) { Fail("wrong number of public keys"); } } if (count != 1) { Fail("wrong number of public keyrings"); } PgpSecretKeyRingBundle secretRings2 = new PgpSecretKeyRingBundle(sec3); count = 0; encRing = secretRings2.GetEncoded(); PgpSecretKeyRingBundle secretRings = new PgpSecretKeyRingBundle(encRing); foreach (PgpSecretKeyRing pgpSec1 in secretRings2.GetKeyRings()) { count++; int keyCount = 0; byte[] bytes = pgpSec1.GetEncoded(); PgpSecretKeyRing pgpSec2 = new PgpSecretKeyRing(bytes); foreach (PgpSecretKey k in pgpSec2.GetSecretKeys()) { keyCount++; k.ExtractPrivateKey(sec3pass1); } if (keyCount != 2) { Fail("wrong number of secret keys"); } } if (count != 1) { Fail("wrong number of secret keyrings"); } } [Test] public void PerformTest4() { PgpSecretKeyRingBundle secretRings1 = new PgpSecretKeyRingBundle(sec4); int count = 0; byte[] encRing = secretRings1.GetEncoded(); PgpSecretKeyRingBundle secretRings2 = new PgpSecretKeyRingBundle(encRing); foreach (PgpSecretKeyRing pgpSec1 in secretRings1.GetKeyRings()) { count++; int keyCount = 0; byte[] bytes = pgpSec1.GetEncoded(); PgpSecretKeyRing pgpSec2 = new PgpSecretKeyRing(bytes); foreach (PgpSecretKey k in pgpSec2.GetSecretKeys()) { keyCount++; k.ExtractPrivateKey(sec3pass1); } if (keyCount != 2) { Fail("wrong number of secret keys"); } } if (count != 1) { Fail("wrong number of secret keyrings"); } } [Test] public void PerformTest5() { PgpPublicKeyRingBundle pubRings = new PgpPublicKeyRingBundle(pub5); int count = 0; byte[] encRing = pubRings.GetEncoded(); pubRings = new PgpPublicKeyRingBundle(encRing); foreach (PgpPublicKeyRing pgpPub1 in pubRings.GetKeyRings()) { count++; int keyCount = 0; byte[] bytes = pgpPub1.GetEncoded(); PgpPublicKeyRing pgpPub2 = new PgpPublicKeyRing(bytes); foreach (PgpPublicKey o in pgpPub2.GetPublicKeys()) { if (o == null) Fail("null keyring found"); keyCount++; } if (keyCount != 2) { Fail("wrong number of public keys"); } } if (count != 1) { Fail("wrong number of public keyrings"); } #if INCLUDE_IDEA PgpSecretKeyRingBundle secretRings1 = new PgpSecretKeyRingBundle(sec5); count = 0; encRing = secretRings1.GetEncoded(); PgpSecretKeyRingBundle secretRings2 = new PgpSecretKeyRingBundle(encRing); foreach (PgpSecretKeyRing pgpSec1 in secretRings1.GetKeyRings()) { count++; int keyCount = 0; byte[] bytes = pgpSec1.GetEncoded(); PgpSecretKeyRing pgpSec2 = new PgpSecretKeyRing(bytes); foreach (PgpSecretKey k in pgpSec2.GetSecretKeys()) { keyCount++; k.ExtractPrivateKey(sec5pass1); } if (keyCount != 2) { Fail("wrong number of secret keys"); } } if (count != 1) { Fail("wrong number of secret keyrings"); } #endif } [Test] public void PerformTest6() { PgpPublicKeyRingBundle pubRings = new PgpPublicKeyRingBundle(pub6); foreach (PgpPublicKeyRing pgpPub in pubRings.GetKeyRings()) { foreach (PgpPublicKey k in pgpPub.GetPublicKeys()) { if (k.KeyId == 0x5ce086b5b5a18ff4L) { int count = 0; foreach (PgpSignature sig in k.GetSignaturesOfType(PgpSignature.SubkeyRevocation)) { if (sig == null) Fail("null signature found"); count++; } if (count != 1) { Fail("wrong number of revocations in test6."); } } } } byte[] encRing = pubRings.GetEncoded(); } [Test, Explicit] public void PerformTest7() { PgpPublicKeyRing pgpPub = new PgpPublicKeyRing(pub7); PgpPublicKey masterKey = null; foreach (PgpPublicKey k in pgpPub.GetPublicKeys()) { if (k.IsMasterKey) { masterKey = k; continue; } int count = 0; PgpSignature sig = null; foreach (PgpSignature sigTemp in k.GetSignaturesOfType(PgpSignature.SubkeyRevocation)) { sig = sigTemp; count++; } if (count != 1) { Fail("wrong number of revocations in test7."); } sig.InitVerify(masterKey); if (!sig.VerifyCertification(k)) { Fail("failed to verify revocation certification"); } } } [Test] public void PerformTest8() { PgpPublicKeyRingBundle pubRings = new PgpPublicKeyRingBundle(pub8); int count = 0; byte[] encRing = pubRings.GetEncoded(); pubRings = new PgpPublicKeyRingBundle(encRing); foreach (PgpPublicKeyRing pgpPub1 in pubRings.GetKeyRings()) { count++; int keyCount = 0; byte[] bytes = pgpPub1.GetEncoded(); PgpPublicKeyRing pgpPub2 = new PgpPublicKeyRing(bytes); foreach (PgpPublicKey o in pgpPub2.GetPublicKeys()) { if (o == null) Fail("null key found"); keyCount++; } if (keyCount != 2) { Fail("wrong number of public keys"); } } if (count != 2) { Fail("wrong number of public keyrings"); } PgpSecretKeyRingBundle secretRings1 = new PgpSecretKeyRingBundle(sec8); count = 0; encRing = secretRings1.GetEncoded(); PgpSecretKeyRingBundle secretRings2 = new PgpSecretKeyRingBundle(encRing); foreach (PgpSecretKeyRing pgpSec1 in secretRings1.GetKeyRings()) { count++; int keyCount = 0; byte[] bytes = pgpSec1.GetEncoded(); PgpSecretKeyRing pgpSec2 = new PgpSecretKeyRing(bytes); foreach (PgpSecretKey k in pgpSec2.GetSecretKeys()) { keyCount++; k.ExtractPrivateKey(sec8pass); } if (keyCount != 2) { Fail("wrong number of secret keys"); } } if (count != 1) { Fail("wrong number of secret keyrings"); } } [Test] public void PerformTest9() { PgpSecretKeyRingBundle secretRings1 = new PgpSecretKeyRingBundle(sec9); int count = 0; byte[] encRing = secretRings1.GetEncoded(); PgpSecretKeyRingBundle secretRings2 = new PgpSecretKeyRingBundle(encRing); foreach (PgpSecretKeyRing pgpSec1 in secretRings1.GetKeyRings()) { count++; int keyCount = 0; byte[] bytes = pgpSec1.GetEncoded(); PgpSecretKeyRing pgpSec2 = new PgpSecretKeyRing(bytes); foreach (PgpSecretKey k in pgpSec2.GetSecretKeys()) { keyCount++; PgpPrivateKey pKey = k.ExtractPrivateKey(sec9pass); if (keyCount == 1 && pKey != null) { Fail("primary secret key found, null expected"); } } if (keyCount != 3) { Fail("wrong number of secret keys"); } } if (count != 1) { Fail("wrong number of secret keyrings"); } } [Test] public void PerformTest10() { PgpSecretKeyRing secretRing = new PgpSecretKeyRing(sec10); foreach (PgpSecretKey secretKey in secretRing.GetSecretKeys()) { PgpPublicKey pubKey = secretKey.PublicKey; if (pubKey.ValidDays != 28) { Fail("days wrong on secret key ring"); } if (pubKey.GetValidSeconds() != 28 * 24 * 60 * 60) { Fail("seconds wrong on secret key ring"); } } PgpPublicKeyRing publicRing = new PgpPublicKeyRing(pub10); foreach (PgpPublicKey pubKey in publicRing.GetPublicKeys()) { if (pubKey.ValidDays != 28) { Fail("days wrong on public key ring"); } if (pubKey.GetValidSeconds() != 28 * 24 * 60 * 60) { Fail("seconds wrong on public key ring"); } } } [Test] public void PerformTest11() { PgpPublicKeyRing pubRing = new PgpPublicKeyRing(subKeyBindingKey); foreach (PgpPublicKey key in pubRing.GetPublicKeys()) { if (key.GetValidSeconds() != 0) { Fail("expiration time non-zero"); } } } [Test] public void GenerateTest() { char[] passPhrase = "hello".ToCharArray(); DsaParametersGenerator pGen = new DsaParametersGenerator(); pGen.Init(512, 80, new SecureRandom()); DsaParameters dsaParams = pGen.GenerateParameters(); DsaKeyGenerationParameters dsaKgp = new DsaKeyGenerationParameters(new SecureRandom(), dsaParams); IAsymmetricCipherKeyPairGenerator dsaKpg = GeneratorUtilities.GetKeyPairGenerator("DSA"); dsaKpg.Init(dsaKgp); // // this takes a while as the key generator has to Generate some DSA parameters // before it Generates the key. // AsymmetricCipherKeyPair dsaKp = dsaKpg.GenerateKeyPair(); IAsymmetricCipherKeyPairGenerator elgKpg = GeneratorUtilities.GetKeyPairGenerator("ELGAMAL"); BigInteger g = new BigInteger("153d5d6172adb43045b68ae8e1de1070b6137005686d29d3d73a7749199681ee5b212c9b96bfdcfa5b20cd5e3fd2044895d609cf9b410b7a0f12ca1cb9a428cc", 16); BigInteger p = new BigInteger("9494fec095f3b85ee286542b3836fc81a5dd0a0349b4c239dd38744d488cf8e31db8bcb7d33b41abb9e5a33cca9144b1cef332c94bf0573bf047a3aca98cdf3b", 16); ElGamalParameters elParams = new ElGamalParameters(p, g); ElGamalKeyGenerationParameters elKgp = new ElGamalKeyGenerationParameters(new SecureRandom(), elParams); elgKpg.Init(elKgp); // // this is quicker because we are using preGenerated parameters. // AsymmetricCipherKeyPair elgKp = elgKpg.GenerateKeyPair(); PgpKeyPair dsaKeyPair = new PgpKeyPair(PublicKeyAlgorithmTag.Dsa, dsaKp, DateTime.UtcNow); PgpKeyPair elgKeyPair = new PgpKeyPair(PublicKeyAlgorithmTag.ElGamalEncrypt, elgKp, DateTime.UtcNow); PgpKeyRingGenerator keyRingGen = new PgpKeyRingGenerator(PgpSignature.PositiveCertification, dsaKeyPair, "test", SymmetricKeyAlgorithmTag.Aes256, passPhrase, null, null, new SecureRandom()); keyRingGen.AddSubKey(elgKeyPair); PgpSecretKeyRing keyRing = keyRingGen.GenerateSecretKeyRing(); keyRing.GetSecretKey().ExtractPrivateKey(passPhrase); PgpPublicKeyRing pubRing = keyRingGen.GeneratePublicKeyRing(); PgpPublicKey vKey = null; PgpPublicKey sKey = null; foreach (PgpPublicKey pk in pubRing.GetPublicKeys()) { if (pk.IsMasterKey) { vKey = pk; } else { sKey = pk; } } foreach (PgpSignature sig in sKey.GetSignatures()) { if (sig.KeyId == vKey.KeyId && sig.SignatureType == PgpSignature.SubkeyBinding) { sig.InitVerify(vKey); if (!sig.VerifyCertification(vKey, sKey)) { Fail("failed to verify sub-key signature."); } } } } [Test] public void InsertMasterTest() { SecureRandom random = new SecureRandom(); char[] passPhrase = "hello".ToCharArray(); IAsymmetricCipherKeyPairGenerator rsaKpg = GeneratorUtilities.GetKeyPairGenerator("RSA"); rsaKpg.Init(new KeyGenerationParameters(random, 512)); // // this is quicker because we are using pregenerated parameters. // AsymmetricCipherKeyPair rsaKp = rsaKpg.GenerateKeyPair(); PgpKeyPair rsaKeyPair1 = new PgpKeyPair(PublicKeyAlgorithmTag.RsaGeneral, rsaKp, DateTime.UtcNow); rsaKp = rsaKpg.GenerateKeyPair(); PgpKeyPair rsaKeyPair2 = new PgpKeyPair(PublicKeyAlgorithmTag.RsaGeneral, rsaKp, DateTime.UtcNow); PgpKeyRingGenerator keyRingGen = new PgpKeyRingGenerator(PgpSignature.PositiveCertification, rsaKeyPair1, "test", SymmetricKeyAlgorithmTag.Aes256, passPhrase, null, null, random); PgpSecretKeyRing secRing1 = keyRingGen.GenerateSecretKeyRing(); PgpPublicKeyRing pubRing1 = keyRingGen.GeneratePublicKeyRing(); keyRingGen = new PgpKeyRingGenerator(PgpSignature.PositiveCertification, rsaKeyPair2, "test", SymmetricKeyAlgorithmTag.Aes256, passPhrase, null, null, random); PgpSecretKeyRing secRing2 = keyRingGen.GenerateSecretKeyRing(); PgpPublicKeyRing pubRing2 = keyRingGen.GeneratePublicKeyRing(); try { PgpPublicKeyRing.InsertPublicKey(pubRing1, pubRing2.GetPublicKey()); Fail("adding second master key (public) should throw an ArgumentException"); } catch (ArgumentException e) { if (!e.Message.Equals("cannot add a master key to a ring that already has one")) { Fail("wrong message in public test"); } } try { PgpSecretKeyRing.InsertSecretKey(secRing1, secRing2.GetSecretKey()); Fail("adding second master key (secret) should throw an ArgumentException"); } catch (ArgumentException e) { if (!e.Message.Equals("cannot add a master key to a ring that already has one")) { Fail("wrong message in secret test"); } } } [Test] public void GenerateSha1Test() { char[] passPhrase = "hello".ToCharArray(); IAsymmetricCipherKeyPairGenerator dsaKpg = GeneratorUtilities.GetKeyPairGenerator("DSA"); DsaParametersGenerator pGen = new DsaParametersGenerator(); pGen.Init(512, 80, new SecureRandom()); DsaParameters dsaParams = pGen.GenerateParameters(); DsaKeyGenerationParameters kgp = new DsaKeyGenerationParameters(new SecureRandom(), dsaParams); dsaKpg.Init(kgp); // // this takes a while as the key generator has to generate some DSA params // before it generates the key. // AsymmetricCipherKeyPair dsaKp = dsaKpg.GenerateKeyPair(); IAsymmetricCipherKeyPairGenerator elgKpg = GeneratorUtilities.GetKeyPairGenerator("ELGAMAL"); BigInteger g = new BigInteger("153d5d6172adb43045b68ae8e1de1070b6137005686d29d3d73a7749199681ee5b212c9b96bfdcfa5b20cd5e3fd2044895d609cf9b410b7a0f12ca1cb9a428cc", 16); BigInteger p = new BigInteger("9494fec095f3b85ee286542b3836fc81a5dd0a0349b4c239dd38744d488cf8e31db8bcb7d33b41abb9e5a33cca9144b1cef332c94bf0573bf047a3aca98cdf3b", 16); ElGamalParameters elParams = new ElGamalParameters(p, g); ElGamalKeyGenerationParameters elKgp = new ElGamalKeyGenerationParameters(new SecureRandom(), elParams); elgKpg.Init(elKgp); // // this is quicker because we are using preGenerated parameters. // AsymmetricCipherKeyPair elgKp = elgKpg.GenerateKeyPair(); PgpKeyPair dsaKeyPair = new PgpKeyPair(PublicKeyAlgorithmTag.Dsa, dsaKp, DateTime.UtcNow); PgpKeyPair elgKeyPair = new PgpKeyPair(PublicKeyAlgorithmTag.ElGamalEncrypt, elgKp, DateTime.UtcNow); PgpKeyRingGenerator keyRingGen = new PgpKeyRingGenerator(PgpSignature.PositiveCertification, dsaKeyPair, "test", SymmetricKeyAlgorithmTag.Aes256, passPhrase, true, null, null, new SecureRandom()); keyRingGen.AddSubKey(elgKeyPair); PgpSecretKeyRing keyRing = keyRingGen.GenerateSecretKeyRing(); keyRing.GetSecretKey().ExtractPrivateKey(passPhrase); PgpPublicKeyRing pubRing = keyRingGen.GeneratePublicKeyRing(); PgpPublicKey vKey = null; PgpPublicKey sKey = null; foreach (PgpPublicKey pk in pubRing.GetPublicKeys()) { if (pk.IsMasterKey) { vKey = pk; } else { sKey = pk; } } foreach (PgpSignature sig in sKey.GetSignatures()) { if (sig.KeyId == vKey.KeyId && sig.SignatureType == PgpSignature.SubkeyBinding) { sig.InitVerify(vKey); if (!sig.VerifyCertification(vKey, sKey)) { Fail("failed to verify sub-key signature."); } } } } [Test] public void RewrapTest() { SecureRandom rand = new SecureRandom(); // Read the secret key rings PgpSecretKeyRingBundle privRings = new PgpSecretKeyRingBundle( new MemoryStream(rewrapKey, false)); foreach (PgpSecretKeyRing pgpPrivEnum in privRings.GetKeyRings()) { foreach (PgpSecretKey pgpKeyEnum in pgpPrivEnum.GetSecretKeys()) { // re-encrypt the key with an empty password PgpSecretKeyRing pgpPriv = PgpSecretKeyRing.RemoveSecretKey(pgpPrivEnum, pgpKeyEnum); PgpSecretKey pgpKey = PgpSecretKey.CopyWithNewPassword( pgpKeyEnum, rewrapPass, null, SymmetricKeyAlgorithmTag.Null, rand); pgpPriv = PgpSecretKeyRing.InsertSecretKey(pgpPriv, pgpKey); // this should succeed PgpPrivateKey privTmp = pgpKey.ExtractPrivateKey(null); } } } [Test] public void PublicKeyRingWithX509Test() { checkPublicKeyRingWithX509(pubWithX509); PgpPublicKeyRing pubRing = new PgpPublicKeyRing(pubWithX509); checkPublicKeyRingWithX509(pubRing.GetEncoded()); } [Test] public void SecretKeyRingWithPersonalCertificateTest() { checkSecretKeyRingWithPersonalCertificate(secWithPersonalCertificate); PgpSecretKeyRingBundle secRing = new PgpSecretKeyRingBundle(secWithPersonalCertificate); checkSecretKeyRingWithPersonalCertificate(secRing.GetEncoded()); } private void checkSecretKeyRingWithPersonalCertificate( byte[] keyRing) { PgpSecretKeyRingBundle secCol = new PgpSecretKeyRingBundle(keyRing); int count = 0; foreach (PgpSecretKeyRing ring in secCol.GetKeyRings()) { IEnumerator e = ring.GetExtraPublicKeys().GetEnumerator(); while (e.MoveNext()) { ++count; } } if (count != 1) { Fail("personal certificate data subkey not found - count = " + count); } } private void checkPublicKeyRingWithX509( byte[] keyRing) { PgpPublicKeyRing pubRing = new PgpPublicKeyRing(keyRing); IEnumerator en = pubRing.GetPublicKeys().GetEnumerator(); if (en.MoveNext()) { PgpPublicKey key = (PgpPublicKey) en.Current; IEnumerator sEn = key.GetSignatures().GetEnumerator(); if (sEn.MoveNext()) { PgpSignature sig = (PgpSignature) sEn.Current; if (sig.KeyAlgorithm != PublicKeyAlgorithmTag.Experimental_1) { Fail("experimental signature not found"); } if (!AreEqual(sig.GetSignature(), Hex.Decode("000101"))) { Fail("experimental encoding check failed"); } } else { Fail("no signature found"); } } else { Fail("no key found"); } } public override void PerformTest() { PerformTest1(); PerformTest2(); PerformTest3(); PerformTest4(); PerformTest5(); PerformTest6(); // NB: This was commented out in the original Java source //PerformTest7(); PerformTest8(); PerformTest9(); PerformTest10(); PerformTest11(); GenerateTest(); GenerateSha1Test(); RewrapTest(); PublicKeyRingWithX509Test(); SecretKeyRingWithPersonalCertificateTest(); InsertMasterTest(); } public override string Name { get { return "PgpKeyRingTest"; } } public static void Main( string[] args) { RunTest(new PgpKeyRingTest()); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Reflection; using System.Runtime.InteropServices; using Xunit; namespace System.Runtime.Serialization.Formatters.Tests { public partial class FormatterServicesTests { [Fact] public void CheckTypeSecurity_Nop() { FormatterServices.CheckTypeSecurity(typeof(int), TypeFilterLevel.Full); FormatterServices.CheckTypeSecurity(typeof(int), TypeFilterLevel.Low); } [Fact] public void GetSerializableMembers_InvalidArguments_ThrowsException() { AssertExtensions.Throws<ArgumentNullException>("type", () => FormatterServices.GetSerializableMembers(null)); } [Fact] public void GetSerializableMembers_Interface() { Assert.Equal<MemberInfo>(new MemberInfo[0], FormatterServices.GetSerializableMembers(typeof(IDisposable))); } [Fact] public void GetUninitializedObject_NullType_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("type", () => FormatterServices.GetUninitializedObject(null)); AssertExtensions.Throws<ArgumentNullException>("type", () => FormatterServices.GetSafeUninitializedObject(null)); } [Fact] public void GetUninitializedObject_NonRuntimeType_ThrowsSerializationException() { Assert.Throws<SerializationException>(() => FormatterServices.GetUninitializedObject(new NonRuntimeType())); Assert.Throws<SerializationException>(() => FormatterServices.GetSafeUninitializedObject(new NonRuntimeType())); } public static IEnumerable<object[]> GetUninitializedObject_NotSupportedType_TestData() { yield return new object[] { typeof(int[]) }; yield return new object[] { typeof(int[,]) }; yield return new object[] { typeof(int).MakePointerType() }; yield return new object[] { typeof(int).MakeByRefType() }; yield return new object[] { typeof(GenericClass<>).GetTypeInfo().GenericTypeParameters[0] }; } [Theory] [MemberData(nameof(GetUninitializedObject_NotSupportedType_TestData))] public void GetUninitializedObject_NotSupportedType_ThrowsArgumentException(Type type) { AssertExtensions.Throws<ArgumentException>(null, () => FormatterServices.GetUninitializedObject(type)); AssertExtensions.Throws<ArgumentException>(null, () => FormatterServices.GetSafeUninitializedObject(type)); } [Theory] [InlineData(typeof(AbstractClass))] [InlineData(typeof(StaticClass))] [InlineData(typeof(Interface))] [InlineData(typeof(Array))] public void GetUninitializedObject_AbstractClass_ThrowsMemberAccessException(Type type) { Assert.Throws<MemberAccessException>(() => FormatterServices.GetUninitializedObject(type)); Assert.Throws<MemberAccessException>(() => FormatterServices.GetSafeUninitializedObject(type)); } public abstract class AbstractClass { } public static class StaticClass { } public interface Interface { } public static IEnumerable<object[]> GetUninitializedObject_OpenGenericClass_TestData() { yield return new object[] { typeof(GenericClass<>) }; yield return new object[] { typeof(GenericClass<>).MakeGenericType(typeof(GenericClass<>)) }; } [Theory] [MemberData(nameof(GetUninitializedObject_OpenGenericClass_TestData))] public void GetUninitializedObject_OpenGenericClass_ThrowsMemberAccessException(Type type) { Assert.Throws<MemberAccessException>(() => FormatterServices.GetUninitializedObject(type)); Assert.Throws<MemberAccessException>(() => FormatterServices.GetSafeUninitializedObject(type)); } public interface IGenericClass { int Value { get; set; } } public class GenericClass<T> : IGenericClass { public int Value { get; set; } } public static IEnumerable<object[]> GetUninitializedObject_ByRefLikeType_TestData() { yield return new object[] { typeof(TypedReference) }; yield return new object[] { typeof(RuntimeArgumentHandle) }; // .NET Standard 2.0 doesn't have ArgIterator, but .NET Core 2.0 does Type argIterator = typeof(object).Assembly.GetType("System.ArgIterator"); if (argIterator != null) { yield return new object[] { argIterator }; } } public static IEnumerable<object[]> GetUninitializedObject_ByRefLikeType_NetCore_TestData() { yield return new object[] { typeof(Span<int>) }; yield return new object[] { typeof(ReadOnlySpan<int>) }; yield return new object[] { typeof(StructWithSpanField) }; } #pragma warning disable 0169 // The private field 'class member' is never used private ref struct StructWithSpanField { Span<byte> _bytes; int _position; } #pragma warning restore 0169 [Theory] [MemberData(nameof(GetUninitializedObject_ByRefLikeType_NetCore_TestData))] [SkipOnTargetFramework(~TargetFrameworkMonikers.Netcoreapp, "Some runtimes don't support or recognise Span<T>, ReadOnlySpan<T> or ByReference<T> as ref types.")] public void GetUninitializedObject_ByRefLikeType_NetCore_ThrowsNotSupportedException(Type type) { Assert.Throws<NotSupportedException>(() => FormatterServices.GetUninitializedObject(type)); Assert.Throws<NotSupportedException>(() => FormatterServices.GetSafeUninitializedObject(type)); } [Theory] [MemberData(nameof(GetUninitializedObject_ByRefLikeType_TestData))] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "full .NET Framework has bug that allows allocating instances of byref-like types.")] public void GetUninitializedObject_ByRefLikeType_NonNetfx_ThrowsNotSupportedException(Type type) { Assert.Throws<NotSupportedException>(() => FormatterServices.GetUninitializedObject(type)); Assert.Throws<NotSupportedException>(() => FormatterServices.GetSafeUninitializedObject(type)); } [Fact] [SkipOnTargetFramework(~TargetFrameworkMonikers.Netcoreapp, "The coreclr doesn't support GetUninitializedObject for shared generic instances")] public void GetUninitializedObject_SharedGenericInstance_NetCore_ThrowsNotSupportedException() { Type canonType = Type.GetType("System.__Canon"); Assert.NotNull(canonType); Type sharedGenericInstance = typeof(GenericClass<>).MakeGenericType(canonType); Assert.Throws<NotSupportedException>(() => FormatterServices.GetUninitializedObject(sharedGenericInstance)); Assert.Throws<NotSupportedException>(() => FormatterServices.GetSafeUninitializedObject(sharedGenericInstance)); } [Fact] public void GetUninitializedObject_NullableType_InitializesValue() { int? nullableUnsafe = (int?)FormatterServices.GetUninitializedObject(typeof(int?)); Assert.True(nullableUnsafe.HasValue); Assert.Equal(0, nullableUnsafe.Value); int? nullableSafe = (int?)FormatterServices.GetSafeUninitializedObject(typeof(int?)); Assert.True(nullableSafe.HasValue); Assert.Equal(0, nullableSafe.Value); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "The full .NET Framework doesn't support GetUninitializedObject for subclasses of ContextBoundObject")] public void GetUninitializedObject_ContextBoundObjectSubclass_NetCore_InitializesValue() { Assert.Equal(0, ((ContextBoundSubclass)FormatterServices.GetUninitializedObject(typeof(ContextBoundSubclass))).Value); Assert.Equal(0, ((ContextBoundSubclass)FormatterServices.GetSafeUninitializedObject(typeof(ContextBoundSubclass))).Value); } public class ContextBoundSubclass : ContextBoundObject { public int Value { get; set; } } [Fact] public void GetUninitializedObject_TypeHasDefaultConstructor_DoesNotRunConstructor() { Assert.Equal(42, new ObjectWithDefaultConstructor().Value); Assert.Equal(0, ((ObjectWithDefaultConstructor)FormatterServices.GetUninitializedObject(typeof(ObjectWithDefaultConstructor))).Value); Assert.Equal(0, ((ObjectWithDefaultConstructor)FormatterServices.GetSafeUninitializedObject(typeof(ObjectWithDefaultConstructor))).Value); } private class ObjectWithDefaultConstructor { public ObjectWithDefaultConstructor() { Value = 42; } public int Value; } [Fact] public void GetUninitializedObject_StaticConstructor_CallsStaticConstructor() { Assert.Equal(2, ((ObjectWithStaticConstructor)FormatterServices.GetUninitializedObject(typeof(ObjectWithStaticConstructor))).GetValue()); } private class ObjectWithStaticConstructor { private static int s_value = 1; static ObjectWithStaticConstructor() { s_value = 2; } public int GetValue() => s_value; } [Fact] public void GetUninitializedObject_StaticField_InitializesStaticFields() { Assert.Equal(1, ((ObjectWithStaticField)FormatterServices.GetUninitializedObject(typeof(ObjectWithStaticField))).GetValue()); } private class ObjectWithStaticField { private static int s_value = 1; public int GetValue() => s_value; } [Fact] public void GetUninitializedObject_StaticConstructorThrows_ThrowsTypeInitializationException() { TypeInitializationException ex = Assert.Throws<TypeInitializationException>(() => FormatterServices.GetUninitializedObject(typeof(StaticConstructorThrows))); Assert.IsType<DivideByZeroException>(ex.InnerException); } private class StaticConstructorThrows { static StaticConstructorThrows() { throw new DivideByZeroException(); } } [Fact] public void GetUninitializedObject_ClassFieldWithDefaultValue_DefaultValueIgnored() { Assert.Equal(42, new ObjectWithStructDefaultField().Value); Assert.Null(((ObjectWithClassDefaultField)FormatterServices.GetUninitializedObject(typeof(ObjectWithClassDefaultField))).Value); Assert.Null(((ObjectWithClassDefaultField)FormatterServices.GetSafeUninitializedObject(typeof(ObjectWithClassDefaultField))).Value); } private class ObjectWithClassDefaultField { public string Value = "abc"; } [Fact] public void GetUninitializedObject_StructFieldWithDefaultValue_DefaultValueIgnored() { Assert.Equal(42, new ObjectWithStructDefaultField().Value); Assert.Equal(0, ((ObjectWithStructDefaultField)FormatterServices.GetUninitializedObject(typeof(ObjectWithStructDefaultField))).Value); Assert.Equal(0, ((ObjectWithStructDefaultField)FormatterServices.GetSafeUninitializedObject(typeof(ObjectWithStructDefaultField))).Value); } private class ObjectWithStructDefaultField { public int Value = 42; } [Fact] public void PopulateObjectMembers_InvalidArguments_ThrowsException() { AssertExtensions.Throws<ArgumentNullException>("obj", () => FormatterServices.PopulateObjectMembers(null, new MemberInfo[0], new object[0])); AssertExtensions.Throws<ArgumentNullException>("members", () => FormatterServices.PopulateObjectMembers(new object(), null, new object[0])); AssertExtensions.Throws<ArgumentNullException>("data", () => FormatterServices.PopulateObjectMembers(new object(), new MemberInfo[0], null)); AssertExtensions.Throws<ArgumentException>(null, () => FormatterServices.PopulateObjectMembers(new object(), new MemberInfo[1], new object[2])); AssertExtensions.Throws<ArgumentNullException>("members", () => FormatterServices.PopulateObjectMembers(new object(), new MemberInfo[1], new object[1])); Assert.Throws<SerializationException>(() => FormatterServices.PopulateObjectMembers(new object(), new MemberInfo[] { typeof(object).GetMethod("GetHashCode") }, new object[] { new object() })); } [Fact] public void GetObjectData_InvalidArguments_ThrowsException() { AssertExtensions.Throws<ArgumentNullException>("obj", () => FormatterServices.GetObjectData(null, new MemberInfo[0])); AssertExtensions.Throws<ArgumentNullException>("members", () => FormatterServices.GetObjectData(new object(), null)); AssertExtensions.Throws<ArgumentNullException>("members", () => FormatterServices.GetObjectData(new object(), new MemberInfo[1])); Assert.Throws<SerializationException>(() => FormatterServices.GetObjectData(new object(), new MethodInfo[] { typeof(object).GetMethod("GetHashCode") })); } [Fact] public void GetSurrogateForCyclicalReference_InvalidArguments_ThrowsException() { AssertExtensions.Throws<ArgumentNullException>("innerSurrogate", () => FormatterServices.GetSurrogateForCyclicalReference(null)); } [Fact] public void GetSurrogateForCyclicalReference_ValidSurrogate_GetsObject() { var surrogate = new NonSerializablePairSurrogate(); ISerializationSurrogate newSurrogate = FormatterServices.GetSurrogateForCyclicalReference(surrogate); Assert.NotNull(newSurrogate); Assert.NotSame(surrogate, newSurrogate); } [Fact] public void GetTypeFromAssembly_InvalidArguments_ThrowsException() { AssertExtensions.Throws<ArgumentNullException>("assem", () => FormatterServices.GetTypeFromAssembly(null, "name")); Assert.Null(FormatterServices.GetTypeFromAssembly(GetType().Assembly, Guid.NewGuid().ToString("N"))); // non-existing type doesn't throw } } } namespace System.Runtime.CompilerServices { // Local definition of IsByRefLikeAttribute while the real one becomes available in corefx [AttributeUsage(AttributeTargets.Struct)] public sealed class IsByRefLikeAttribute : Attribute { public IsByRefLikeAttribute() { } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Text; using JetBrains.Annotations; using osu.Game.Audio; using osu.Game.Beatmaps.ControlPoints; using osu.Game.Beatmaps.Legacy; using osu.Game.Rulesets.Objects; using osu.Game.Rulesets.Objects.Legacy; using osu.Game.Rulesets.Objects.Types; using osu.Game.Skinning; using osuTK; using osuTK.Graphics; namespace osu.Game.Beatmaps.Formats { public class LegacyBeatmapEncoder { public const int LATEST_VERSION = 128; /// <summary> /// osu! is generally slower than taiko, so a factor is added to increase /// speed. This must be used everywhere slider length or beat length is used. /// </summary> public const float LEGACY_TAIKO_VELOCITY_MULTIPLIER = 1.4f; private readonly IBeatmap beatmap; [CanBeNull] private readonly ISkin skin; /// <summary> /// Creates a new <see cref="LegacyBeatmapEncoder"/>. /// </summary> /// <param name="beatmap">The beatmap to encode.</param> /// <param name="skin">The beatmap's skin, used for encoding combo colours.</param> public LegacyBeatmapEncoder(IBeatmap beatmap, [CanBeNull] ISkin skin) { this.beatmap = beatmap; this.skin = skin; if (beatmap.BeatmapInfo.RulesetID < 0 || beatmap.BeatmapInfo.RulesetID > 3) throw new ArgumentException("Only beatmaps in the osu, taiko, catch, or mania rulesets can be encoded to the legacy beatmap format.", nameof(beatmap)); } public void Encode(TextWriter writer) { writer.WriteLine($"osu file format v{LATEST_VERSION}"); writer.WriteLine(); handleGeneral(writer); writer.WriteLine(); handleEditor(writer); writer.WriteLine(); handleMetadata(writer); writer.WriteLine(); handleDifficulty(writer); writer.WriteLine(); handleEvents(writer); writer.WriteLine(); handleControlPoints(writer); writer.WriteLine(); handleColours(writer); writer.WriteLine(); handleHitObjects(writer); } private void handleGeneral(TextWriter writer) { writer.WriteLine("[General]"); if (beatmap.Metadata.AudioFile != null) writer.WriteLine(FormattableString.Invariant($"AudioFilename: {Path.GetFileName(beatmap.Metadata.AudioFile)}")); writer.WriteLine(FormattableString.Invariant($"AudioLeadIn: {beatmap.BeatmapInfo.AudioLeadIn}")); writer.WriteLine(FormattableString.Invariant($"PreviewTime: {beatmap.Metadata.PreviewTime}")); writer.WriteLine(FormattableString.Invariant($"Countdown: {(int)beatmap.BeatmapInfo.Countdown}")); writer.WriteLine(FormattableString.Invariant($"SampleSet: {toLegacySampleBank((beatmap.HitObjects.FirstOrDefault()?.SampleControlPoint ?? SampleControlPoint.DEFAULT).SampleBank)}")); writer.WriteLine(FormattableString.Invariant($"StackLeniency: {beatmap.BeatmapInfo.StackLeniency}")); writer.WriteLine(FormattableString.Invariant($"Mode: {beatmap.BeatmapInfo.RulesetID}")); writer.WriteLine(FormattableString.Invariant($"LetterboxInBreaks: {(beatmap.BeatmapInfo.LetterboxInBreaks ? '1' : '0')}")); // if (beatmap.BeatmapInfo.UseSkinSprites) // writer.WriteLine(@"UseSkinSprites: 1"); // if (b.AlwaysShowPlayfield) // writer.WriteLine(@"AlwaysShowPlayfield: 1"); // if (b.OverlayPosition != OverlayPosition.NoChange) // writer.WriteLine(@"OverlayPosition: " + b.OverlayPosition); // if (!string.IsNullOrEmpty(b.SkinPreference)) // writer.WriteLine(@"SkinPreference:" + b.SkinPreference); if (beatmap.BeatmapInfo.EpilepsyWarning) writer.WriteLine(@"EpilepsyWarning: 1"); if (beatmap.BeatmapInfo.CountdownOffset > 0) writer.WriteLine(FormattableString.Invariant($@"CountdownOffset: {beatmap.BeatmapInfo.CountdownOffset}")); if (beatmap.BeatmapInfo.RulesetID == 3) writer.WriteLine(FormattableString.Invariant($"SpecialStyle: {(beatmap.BeatmapInfo.SpecialStyle ? '1' : '0')}")); writer.WriteLine(FormattableString.Invariant($"WidescreenStoryboard: {(beatmap.BeatmapInfo.WidescreenStoryboard ? '1' : '0')}")); if (beatmap.BeatmapInfo.SamplesMatchPlaybackRate) writer.WriteLine(@"SamplesMatchPlaybackRate: 1"); } private void handleEditor(TextWriter writer) { writer.WriteLine("[Editor]"); if (beatmap.BeatmapInfo.Bookmarks.Length > 0) writer.WriteLine(FormattableString.Invariant($"Bookmarks: {string.Join(',', beatmap.BeatmapInfo.Bookmarks)}")); writer.WriteLine(FormattableString.Invariant($"DistanceSpacing: {beatmap.BeatmapInfo.DistanceSpacing}")); writer.WriteLine(FormattableString.Invariant($"BeatDivisor: {beatmap.BeatmapInfo.BeatDivisor}")); writer.WriteLine(FormattableString.Invariant($"GridSize: {beatmap.BeatmapInfo.GridSize}")); writer.WriteLine(FormattableString.Invariant($"TimelineZoom: {beatmap.BeatmapInfo.TimelineZoom}")); } private void handleMetadata(TextWriter writer) { writer.WriteLine("[Metadata]"); writer.WriteLine(FormattableString.Invariant($"Title: {beatmap.Metadata.Title}")); if (beatmap.Metadata.TitleUnicode != null) writer.WriteLine(FormattableString.Invariant($"TitleUnicode: {beatmap.Metadata.TitleUnicode}")); writer.WriteLine(FormattableString.Invariant($"Artist: {beatmap.Metadata.Artist}")); if (beatmap.Metadata.ArtistUnicode != null) writer.WriteLine(FormattableString.Invariant($"ArtistUnicode: {beatmap.Metadata.ArtistUnicode}")); writer.WriteLine(FormattableString.Invariant($"Creator: {beatmap.Metadata.AuthorString}")); writer.WriteLine(FormattableString.Invariant($"Version: {beatmap.BeatmapInfo.Version}")); if (beatmap.Metadata.Source != null) writer.WriteLine(FormattableString.Invariant($"Source: {beatmap.Metadata.Source}")); if (beatmap.Metadata.Tags != null) writer.WriteLine(FormattableString.Invariant($"Tags: {beatmap.Metadata.Tags}")); if (beatmap.BeatmapInfo.OnlineBeatmapID != null) writer.WriteLine(FormattableString.Invariant($"BeatmapID: {beatmap.BeatmapInfo.OnlineBeatmapID}")); if (beatmap.BeatmapInfo.BeatmapSet?.OnlineBeatmapSetID != null) writer.WriteLine(FormattableString.Invariant($"BeatmapSetID: {beatmap.BeatmapInfo.BeatmapSet.OnlineBeatmapSetID}")); } private void handleDifficulty(TextWriter writer) { writer.WriteLine("[Difficulty]"); writer.WriteLine(FormattableString.Invariant($"HPDrainRate: {beatmap.Difficulty.DrainRate}")); writer.WriteLine(FormattableString.Invariant($"CircleSize: {beatmap.Difficulty.CircleSize}")); writer.WriteLine(FormattableString.Invariant($"OverallDifficulty: {beatmap.Difficulty.OverallDifficulty}")); writer.WriteLine(FormattableString.Invariant($"ApproachRate: {beatmap.Difficulty.ApproachRate}")); // Taiko adjusts the slider multiplier (see: LEGACY_TAIKO_VELOCITY_MULTIPLIER) writer.WriteLine(beatmap.BeatmapInfo.RulesetID == 1 ? FormattableString.Invariant($"SliderMultiplier: {beatmap.Difficulty.SliderMultiplier / LEGACY_TAIKO_VELOCITY_MULTIPLIER}") : FormattableString.Invariant($"SliderMultiplier: {beatmap.Difficulty.SliderMultiplier}")); writer.WriteLine(FormattableString.Invariant($"SliderTickRate: {beatmap.Difficulty.SliderTickRate}")); } private void handleEvents(TextWriter writer) { writer.WriteLine("[Events]"); if (!string.IsNullOrEmpty(beatmap.BeatmapInfo.Metadata.BackgroundFile)) writer.WriteLine(FormattableString.Invariant($"{(int)LegacyEventType.Background},0,\"{beatmap.BeatmapInfo.Metadata.BackgroundFile}\",0,0")); foreach (var b in beatmap.Breaks) writer.WriteLine(FormattableString.Invariant($"{(int)LegacyEventType.Break},{b.StartTime},{b.EndTime}")); } private void handleControlPoints(TextWriter writer) { if (beatmap.ControlPointInfo.Groups.Count == 0) return; var legacyControlPoints = new LegacyControlPointInfo(); foreach (var point in beatmap.ControlPointInfo.AllControlPoints) legacyControlPoints.Add(point.Time, point.DeepClone()); writer.WriteLine("[TimingPoints]"); SampleControlPoint lastRelevantSamplePoint = null; DifficultyControlPoint lastRelevantDifficultyPoint = null; bool isOsuRuleset = beatmap.BeatmapInfo.RulesetID == 0; // iterate over hitobjects and pull out all required sample and difficulty changes extractDifficultyControlPoints(beatmap.HitObjects); extractSampleControlPoints(beatmap.HitObjects); // handle scroll speed, which is stored as "slider velocity" in legacy formats. // this is relevant for scrolling ruleset beatmaps. if (!isOsuRuleset) { foreach (var point in legacyControlPoints.EffectPoints) legacyControlPoints.Add(point.Time, new DifficultyControlPoint { SliderVelocity = point.ScrollSpeed }); } foreach (var group in legacyControlPoints.Groups) { var groupTimingPoint = group.ControlPoints.OfType<TimingControlPoint>().FirstOrDefault(); // If the group contains a timing control point, it needs to be output separately. if (groupTimingPoint != null) { writer.Write(FormattableString.Invariant($"{groupTimingPoint.Time},")); writer.Write(FormattableString.Invariant($"{groupTimingPoint.BeatLength},")); outputControlPointAt(groupTimingPoint.Time, true); } // Output any remaining effects as secondary non-timing control point. var difficultyPoint = legacyControlPoints.DifficultyPointAt(group.Time); writer.Write(FormattableString.Invariant($"{group.Time},")); writer.Write(FormattableString.Invariant($"{-100 / difficultyPoint.SliderVelocity},")); outputControlPointAt(group.Time, false); } void outputControlPointAt(double time, bool isTimingPoint) { var samplePoint = legacyControlPoints.SamplePointAt(time); var effectPoint = legacyControlPoints.EffectPointAt(time); // Apply the control point to a hit sample to uncover legacy properties (e.g. suffix) HitSampleInfo tempHitSample = samplePoint.ApplyTo(new ConvertHitObjectParser.LegacyHitSampleInfo(string.Empty)); // Convert effect flags to the legacy format LegacyEffectFlags effectFlags = LegacyEffectFlags.None; if (effectPoint.KiaiMode) effectFlags |= LegacyEffectFlags.Kiai; if (effectPoint.OmitFirstBarLine) effectFlags |= LegacyEffectFlags.OmitFirstBarLine; writer.Write(FormattableString.Invariant($"{(int)legacyControlPoints.TimingPointAt(time).TimeSignature},")); writer.Write(FormattableString.Invariant($"{(int)toLegacySampleBank(tempHitSample.Bank)},")); writer.Write(FormattableString.Invariant($"{toLegacyCustomSampleBank(tempHitSample)},")); writer.Write(FormattableString.Invariant($"{tempHitSample.Volume},")); writer.Write(FormattableString.Invariant($"{(isTimingPoint ? '1' : '0')},")); writer.Write(FormattableString.Invariant($"{(int)effectFlags}")); writer.WriteLine(); } IEnumerable<DifficultyControlPoint> collectDifficultyControlPoints(IEnumerable<HitObject> hitObjects) { if (!isOsuRuleset) yield break; foreach (var hitObject in hitObjects) { yield return hitObject.DifficultyControlPoint; foreach (var nested in collectDifficultyControlPoints(hitObject.NestedHitObjects)) yield return nested; } } void extractDifficultyControlPoints(IEnumerable<HitObject> hitObjects) { foreach (var hDifficultyPoint in collectDifficultyControlPoints(hitObjects).OrderBy(dp => dp.Time)) { if (!hDifficultyPoint.IsRedundant(lastRelevantDifficultyPoint)) { legacyControlPoints.Add(hDifficultyPoint.Time, hDifficultyPoint); lastRelevantDifficultyPoint = hDifficultyPoint; } } } IEnumerable<SampleControlPoint> collectSampleControlPoints(IEnumerable<HitObject> hitObjects) { foreach (var hitObject in hitObjects) { yield return hitObject.SampleControlPoint; foreach (var nested in collectSampleControlPoints(hitObject.NestedHitObjects)) yield return nested; } } void extractSampleControlPoints(IEnumerable<HitObject> hitObject) { foreach (var hSamplePoint in collectSampleControlPoints(hitObject).OrderBy(sp => sp.Time)) { if (!hSamplePoint.IsRedundant(lastRelevantSamplePoint)) { legacyControlPoints.Add(hSamplePoint.Time, hSamplePoint); lastRelevantSamplePoint = hSamplePoint; } } } } private void handleColours(TextWriter writer) { var colours = skin?.GetConfig<GlobalSkinColours, IReadOnlyList<Color4>>(GlobalSkinColours.ComboColours)?.Value; if (colours == null || colours.Count == 0) return; writer.WriteLine("[Colours]"); for (var i = 0; i < colours.Count; i++) { var comboColour = colours[i]; writer.Write(FormattableString.Invariant($"Combo{i}: ")); writer.Write(FormattableString.Invariant($"{(byte)(comboColour.R * byte.MaxValue)},")); writer.Write(FormattableString.Invariant($"{(byte)(comboColour.G * byte.MaxValue)},")); writer.Write(FormattableString.Invariant($"{(byte)(comboColour.B * byte.MaxValue)},")); writer.Write(FormattableString.Invariant($"{(byte)(comboColour.A * byte.MaxValue)}")); writer.WriteLine(); } } private void handleHitObjects(TextWriter writer) { writer.WriteLine("[HitObjects]"); if (beatmap.HitObjects.Count == 0) return; foreach (var h in beatmap.HitObjects) handleHitObject(writer, h); } private void handleHitObject(TextWriter writer, HitObject hitObject) { Vector2 position = new Vector2(256, 192); switch (beatmap.BeatmapInfo.RulesetID) { case 0: case 2: position = ((IHasPosition)hitObject).Position; break; case 3: int totalColumns = (int)Math.Max(1, beatmap.Difficulty.CircleSize); position.X = (int)Math.Ceiling(((IHasXPosition)hitObject).X * (512f / totalColumns)); break; } writer.Write(FormattableString.Invariant($"{position.X},")); writer.Write(FormattableString.Invariant($"{position.Y},")); writer.Write(FormattableString.Invariant($"{hitObject.StartTime},")); writer.Write(FormattableString.Invariant($"{(int)getObjectType(hitObject)},")); writer.Write(FormattableString.Invariant($"{(int)toLegacyHitSoundType(hitObject.Samples)},")); if (hitObject is IHasPath path) { addPathData(writer, path, position); writer.Write(getSampleBank(hitObject.Samples)); } else { if (hitObject is IHasDuration) addEndTimeData(writer, hitObject); writer.Write(getSampleBank(hitObject.Samples)); } writer.WriteLine(); } private LegacyHitObjectType getObjectType(HitObject hitObject) { LegacyHitObjectType type = 0; if (hitObject is IHasCombo combo) { type = (LegacyHitObjectType)(combo.ComboOffset << 4); if (combo.NewCombo) type |= LegacyHitObjectType.NewCombo; } switch (hitObject) { case IHasPath _: type |= LegacyHitObjectType.Slider; break; case IHasDuration _: if (beatmap.BeatmapInfo.RulesetID == 3) type |= LegacyHitObjectType.Hold; else type |= LegacyHitObjectType.Spinner; break; default: type |= LegacyHitObjectType.Circle; break; } return type; } private void addPathData(TextWriter writer, IHasPath pathData, Vector2 position) { PathType? lastType = null; for (int i = 0; i < pathData.Path.ControlPoints.Count; i++) { PathControlPoint point = pathData.Path.ControlPoints[i]; if (point.Type != null) { // We've reached a new (explicit) segment! // Explicit segments have a new format in which the type is injected into the middle of the control point string. // To preserve compatibility with osu-stable as much as possible, explicit segments with the same type are converted to use implicit segments by duplicating the control point. // One exception are consecutive perfect curves, which aren't supported in osu!stable and can lead to decoding issues if encoded as implicit segments bool needsExplicitSegment = point.Type != lastType || point.Type == PathType.PerfectCurve; // Another exception to this is when the last two control points of the last segment were duplicated. This is not a scenario supported by osu!stable. // Lazer does not add implicit segments for the last two control points of _any_ explicit segment, so an explicit segment is forced in order to maintain consistency with the decoder. if (i > 1) { // We need to use the absolute control point position to determine equality, otherwise floating point issues may arise. Vector2 p1 = position + pathData.Path.ControlPoints[i - 1].Position; Vector2 p2 = position + pathData.Path.ControlPoints[i - 2].Position; if ((int)p1.X == (int)p2.X && (int)p1.Y == (int)p2.Y) needsExplicitSegment = true; } if (needsExplicitSegment) { switch (point.Type) { case PathType.Bezier: writer.Write("B|"); break; case PathType.Catmull: writer.Write("C|"); break; case PathType.PerfectCurve: writer.Write("P|"); break; case PathType.Linear: writer.Write("L|"); break; } lastType = point.Type; } else { // New segment with the same type - duplicate the control point writer.Write(FormattableString.Invariant($"{position.X + point.Position.X}:{position.Y + point.Position.Y}|")); } } if (i != 0) { writer.Write(FormattableString.Invariant($"{position.X + point.Position.X}:{position.Y + point.Position.Y}")); writer.Write(i != pathData.Path.ControlPoints.Count - 1 ? "|" : ","); } } var curveData = pathData as IHasPathWithRepeats; writer.Write(FormattableString.Invariant($"{(curveData?.RepeatCount ?? 0) + 1},")); writer.Write(FormattableString.Invariant($"{pathData.Path.Distance},")); if (curveData != null) { for (int i = 0; i < curveData.NodeSamples.Count; i++) { writer.Write(FormattableString.Invariant($"{(int)toLegacyHitSoundType(curveData.NodeSamples[i])}")); writer.Write(i != curveData.NodeSamples.Count - 1 ? "|" : ","); } for (int i = 0; i < curveData.NodeSamples.Count; i++) { writer.Write(getSampleBank(curveData.NodeSamples[i], true)); writer.Write(i != curveData.NodeSamples.Count - 1 ? "|" : ","); } } } private void addEndTimeData(TextWriter writer, HitObject hitObject) { var endTimeData = (IHasDuration)hitObject; var type = getObjectType(hitObject); char suffix = ','; // Holds write the end time as if it's part of sample data. if (type == LegacyHitObjectType.Hold) suffix = ':'; writer.Write(FormattableString.Invariant($"{endTimeData.EndTime}{suffix}")); } private string getSampleBank(IList<HitSampleInfo> samples, bool banksOnly = false) { LegacySampleBank normalBank = toLegacySampleBank(samples.SingleOrDefault(s => s.Name == HitSampleInfo.HIT_NORMAL)?.Bank); LegacySampleBank addBank = toLegacySampleBank(samples.FirstOrDefault(s => !string.IsNullOrEmpty(s.Name) && s.Name != HitSampleInfo.HIT_NORMAL)?.Bank); StringBuilder sb = new StringBuilder(); sb.Append(FormattableString.Invariant($"{(int)normalBank}:")); sb.Append(FormattableString.Invariant($"{(int)addBank}")); if (!banksOnly) { string customSampleBank = toLegacyCustomSampleBank(samples.FirstOrDefault(s => !string.IsNullOrEmpty(s.Name))); string sampleFilename = samples.FirstOrDefault(s => string.IsNullOrEmpty(s.Name))?.LookupNames.First() ?? string.Empty; int volume = samples.FirstOrDefault()?.Volume ?? 100; sb.Append(':'); sb.Append(FormattableString.Invariant($"{customSampleBank}:")); sb.Append(FormattableString.Invariant($"{volume}:")); sb.Append(FormattableString.Invariant($"{sampleFilename}")); } return sb.ToString(); } private LegacyHitSoundType toLegacyHitSoundType(IList<HitSampleInfo> samples) { LegacyHitSoundType type = LegacyHitSoundType.None; foreach (var sample in samples) { switch (sample.Name) { case HitSampleInfo.HIT_WHISTLE: type |= LegacyHitSoundType.Whistle; break; case HitSampleInfo.HIT_FINISH: type |= LegacyHitSoundType.Finish; break; case HitSampleInfo.HIT_CLAP: type |= LegacyHitSoundType.Clap; break; } } return type; } private LegacySampleBank toLegacySampleBank(string sampleBank) { switch (sampleBank?.ToLowerInvariant()) { case "normal": return LegacySampleBank.Normal; case "soft": return LegacySampleBank.Soft; case "drum": return LegacySampleBank.Drum; default: return LegacySampleBank.None; } } private string toLegacyCustomSampleBank(HitSampleInfo hitSampleInfo) { if (hitSampleInfo is ConvertHitObjectParser.LegacyHitSampleInfo legacy) return legacy.CustomSampleBank.ToString(CultureInfo.InvariantCulture); return "0"; } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using Elasticsearch.Net; using FluentAssertions; using Tests.Framework.MockResponses; using System.Net; namespace Tests.Framework { public class VirtualClusterConnection : InMemoryConnection { private static readonly object _lock = new object(); private class State { public int Pinged = 0; public int Sniffed = 0; public int Called = 0; public int Successes = 0; public int Failures = 0; } private IDictionary<int, State> Calls = new Dictionary<int, State> { }; private VirtualCluster _cluster; private TestableDateTimeProvider _dateTimeProvider; public VirtualClusterConnection(VirtualCluster cluster, TestableDateTimeProvider dateTimeProvider) { this.UpdateCluster(cluster); this._dateTimeProvider = dateTimeProvider; } public void UpdateCluster(VirtualCluster cluster) { if (cluster == null) return; lock (_lock) { this._cluster = cluster; this.Calls = cluster.Nodes.ToDictionary(n => n.Uri.Port, v => new State()); } } public bool IsSniffRequest(RequestData requestData) => requestData.Path.StartsWith("_nodes/_all/settings", StringComparison.Ordinal); public bool IsPingRequest(RequestData requestData) => requestData.Path == "/" && requestData.Method == HttpMethod.HEAD; public override ElasticsearchResponse<TReturn> Request<TReturn>(RequestData requestData) { this.Calls.Should().ContainKey(requestData.Uri.Port); try { var state = this.Calls[requestData.Uri.Port]; if (IsSniffRequest(requestData)) { var sniffed = Interlocked.Increment(ref state.Sniffed); return HandleRules<TReturn, ISniffRule>( requestData, this._cluster.SniffingRules, requestData.RequestTimeout, (r) => this.UpdateCluster(r.NewClusterState), (r) => SniffResponse.Create(this._cluster.Nodes, this._cluster.SniffShouldReturnFqnd) ); } if (IsPingRequest(requestData)) { var pinged = Interlocked.Increment(ref state.Pinged); return HandleRules<TReturn, IRule>( requestData, this._cluster.PingingRules, requestData.PingTimeout, (r) => { }, (r) => null //HEAD request ); } var called = Interlocked.Increment(ref state.Called); return HandleRules<TReturn, IClientCallRule>( requestData, this._cluster.ClientCallRules, requestData.RequestTimeout, (r) => { }, CallResponse ); } #if DOTNETCORE catch (System.Net.Http.HttpRequestException e) #else catch (WebException e) #endif { var builder = new ResponseBuilder<TReturn>(requestData); builder.Exception = e; return builder.ToResponse(); } } private ElasticsearchResponse<TReturn> HandleRules<TReturn, TRule>( RequestData requestData, IEnumerable<TRule> rules, TimeSpan timeout, Action<TRule> beforeReturn, Func<TRule, byte[]> successResponse ) where TReturn : class where TRule : IRule { var state = this.Calls[requestData.Uri.Port]; foreach (var rule in rules.Where(s => s.OnPort.HasValue)) { var always = rule.Times.Match(t => true, t => false); var times = rule.Times.Match(t => -1, t => t); if (rule.OnPort.Value == requestData.Uri.Port) { if (always) return Always<TReturn, TRule>(requestData, timeout, beforeReturn, successResponse, rule); return Sometimes<TReturn, TRule>(requestData, timeout, beforeReturn, successResponse, state, rule, times); } } foreach (var rule in rules.Where(s => !s.OnPort.HasValue)) { var always = rule.Times.Match(t => true, t => false); var times = rule.Times.Match(t => -1, t => t); if (always) return Always<TReturn, TRule>(requestData, timeout, beforeReturn, successResponse, rule); return Sometimes<TReturn, TRule>(requestData, timeout, beforeReturn, successResponse, state, rule, times); } return this.ReturnConnectionStatus<TReturn>(requestData, successResponse(default(TRule))); } private ElasticsearchResponse<TReturn> Always<TReturn, TRule>(RequestData requestData, TimeSpan timeout, Action<TRule> beforeReturn, Func<TRule, byte[]> successResponse, TRule rule) where TReturn : class where TRule : IRule { if (rule.Takes.HasValue) { var time = timeout < rule.Takes.Value ? timeout: rule.Takes.Value; this._dateTimeProvider.ChangeTime(d=> d.Add(time)); if (rule.Takes.Value > requestData.RequestTimeout) #if DOTNETCORE throw new System.Net.Http.HttpRequestException($"Request timed out after {time} : call configured to take {rule.Takes.Value} while requestTimeout was: {timeout}"); #else throw new WebException($"Request timed out after {time} : call configured to take {rule.Takes.Value} while requestTimeout was: {timeout}"); #endif } return rule.Succeeds ? Success<TReturn, TRule>(requestData, beforeReturn, successResponse, rule) : Fail<TReturn, TRule>(requestData, rule); } private ElasticsearchResponse<TReturn> Sometimes<TReturn, TRule>(RequestData requestData, TimeSpan timeout, Action<TRule> beforeReturn, Func<TRule, byte[]> successResponse, State state, TRule rule, int times) where TReturn : class where TRule : IRule { if (rule.Takes.HasValue) { var time = timeout < rule.Takes.Value ? timeout : rule.Takes.Value; this._dateTimeProvider.ChangeTime(d=> d.Add(time)); if (rule.Takes.Value > requestData.RequestTimeout) #if DOTNETCORE throw new System.Net.Http.HttpRequestException($"Request timed out after {time} : call configured to take {rule.Takes.Value} while requestTimeout was: {timeout}"); #else throw new WebException($"Request timed out after {time} : call configured to take {rule.Takes.Value} while requestTimeout was: {timeout}"); #endif } if (rule.Succeeds && times >= state.Successes) return Success<TReturn, TRule>(requestData, beforeReturn, successResponse, rule); else if (rule.Succeeds) return Fail<TReturn, TRule>(requestData, rule); if (!rule.Succeeds && times >= state.Failures) return Fail<TReturn, TRule>(requestData, rule); return Success<TReturn, TRule>(requestData, beforeReturn, successResponse, rule); } private ElasticsearchResponse<TReturn> Fail<TReturn, TRule>(RequestData requestData, TRule rule) where TReturn : class where TRule : IRule { var state = this.Calls[requestData.Uri.Port]; var failed = Interlocked.Increment(ref state.Failures); if (rule.Return == null) #if DOTNETCORE throw new System.Net.Http.HttpRequestException(); #else throw new WebException(); #endif return rule.Return.Match( (e) => { throw e; }, (statusCode) => this.ReturnConnectionStatus<TReturn>(requestData, CallResponse(rule), statusCode) ); } private ElasticsearchResponse<TReturn> Success<TReturn, TRule>(RequestData requestData, Action<TRule> beforeReturn, Func<TRule, byte[]> successResponse, TRule rule) where TReturn : class where TRule : IRule { var state = this.Calls[requestData.Uri.Port]; var succeeded = Interlocked.Increment(ref state.Successes); beforeReturn?.Invoke(rule); return this.ReturnConnectionStatus<TReturn>(requestData, successResponse(rule)); } private byte[] CallResponse<TRule>(TRule rule) where TRule : IRule { if (rule?.ReturnResponse != null) return rule.ReturnResponse; var response = DefaultResponse; using (var ms = new MemoryStream()) { new ElasticsearchDefaultSerializer().Serialize(response, ms); return ms.ToArray(); } } private static object DefaultResponse { get { var response = new { name = "Razor Fist", cluster_name = "elasticsearch-test-cluster", version = new { number = "2.0.0", build_hash = "af1dc6d8099487755c3143c931665b709de3c764", build_timestamp = "2015-07-07T11:28:47Z", build_snapshot = true, lucene_version = "5.2.1" }, tagline = "You Know, for Search" }; return response; } } public override Task<ElasticsearchResponse<TReturn>> RequestAsync<TReturn>(RequestData requestData) { return Task.FromResult(this.Request<TReturn>(requestData)); } } }
/* * 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.Runtime.Remoting.Lifetime; using System.Threading; using System.Reflection; using System.Collections; using System.Collections.Generic; using OpenSim.Region.ScriptEngine.Interfaces; using OpenSim.Region.ScriptEngine.Shared.Api.Interfaces; using LSL_Float = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLFloat; using LSL_Integer = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLInteger; using LSL_Key = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLString; using LSL_List = OpenSim.Region.ScriptEngine.Shared.LSL_Types.list; using LSL_Rotation = OpenSim.Region.ScriptEngine.Shared.LSL_Types.Quaternion; using LSL_String = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLString; using LSL_Vector = OpenSim.Region.ScriptEngine.Shared.LSL_Types.Vector3; namespace OpenSim.Region.ScriptEngine.Shared.ScriptBase { public partial class ScriptBaseClass : MarshalByRefObject { public ILSL_Api m_LSL_Functions; public void ApiTypeLSL(IScriptApi api) { if (!(api is ILSL_Api)) return; m_LSL_Functions = (ILSL_Api)api; } public void state(string newState) { m_LSL_Functions.state(newState); } // // Script functions // public LSL_Integer llAbs(int i) { return m_LSL_Functions.llAbs(i); } public LSL_Float llAcos(double val) { return m_LSL_Functions.llAcos(val); } public void llAddToLandBanList(string avatar, double hours) { m_LSL_Functions.llAddToLandBanList(avatar, hours); } public void llAddToLandPassList(string avatar, double hours) { m_LSL_Functions.llAddToLandPassList(avatar, hours); } public void llAdjustSoundVolume(double volume) { m_LSL_Functions.llAdjustSoundVolume(volume); } public void llAllowInventoryDrop(int add) { m_LSL_Functions.llAllowInventoryDrop(add); } public LSL_Float llAngleBetween(LSL_Rotation a, LSL_Rotation b) { return m_LSL_Functions.llAngleBetween(a, b); } public void llApplyImpulse(LSL_Vector force, int local) { m_LSL_Functions.llApplyImpulse(force, local); } public void llApplyRotationalImpulse(LSL_Vector force, int local) { m_LSL_Functions.llApplyRotationalImpulse(force, local); } public LSL_Float llAsin(double val) { return m_LSL_Functions.llAsin(val); } public LSL_Float llAtan2(double x, double y) { return m_LSL_Functions.llAtan2(x, y); } public void llAttachToAvatar(int attachment) { m_LSL_Functions.llAttachToAvatar(attachment); } public LSL_Key llAvatarOnSitTarget() { return m_LSL_Functions.llAvatarOnSitTarget(); } public LSL_Key llAvatarOnLinkSitTarget(int linknum) { return m_LSL_Functions.llAvatarOnLinkSitTarget(linknum); } public LSL_Rotation llAxes2Rot(LSL_Vector fwd, LSL_Vector left, LSL_Vector up) { return m_LSL_Functions.llAxes2Rot(fwd, left, up); } public LSL_Rotation llAxisAngle2Rot(LSL_Vector axis, double angle) { return m_LSL_Functions.llAxisAngle2Rot(axis, angle); } public LSL_Integer llBase64ToInteger(string str) { return m_LSL_Functions.llBase64ToInteger(str); } public LSL_String llBase64ToString(string str) { return m_LSL_Functions.llBase64ToString(str); } public void llBreakAllLinks() { m_LSL_Functions.llBreakAllLinks(); } public void llBreakLink(int linknum) { m_LSL_Functions.llBreakLink(linknum); } public LSL_Integer llCeil(double f) { return m_LSL_Functions.llCeil(f); } public void llClearCameraParams() { m_LSL_Functions.llClearCameraParams(); } public void llCloseRemoteDataChannel(string channel) { m_LSL_Functions.llCloseRemoteDataChannel(channel); } public LSL_Float llCloud(LSL_Vector offset) { return m_LSL_Functions.llCloud(offset); } public void llCollisionFilter(string name, string id, int accept) { m_LSL_Functions.llCollisionFilter(name, id, accept); } public void llCollisionSound(string impact_sound, double impact_volume) { m_LSL_Functions.llCollisionSound(impact_sound, impact_volume); } public void llCollisionSprite(string impact_sprite) { m_LSL_Functions.llCollisionSprite(impact_sprite); } public LSL_Float llCos(double f) { return m_LSL_Functions.llCos(f); } public void llCreateLink(string target, int parent) { m_LSL_Functions.llCreateLink(target, parent); } public LSL_List llCSV2List(string src) { return m_LSL_Functions.llCSV2List(src); } public LSL_List llDeleteSubList(LSL_List src, int start, int end) { return m_LSL_Functions.llDeleteSubList(src, start, end); } public LSL_String llDeleteSubString(string src, int start, int end) { return m_LSL_Functions.llDeleteSubString(src, start, end); } public void llDetachFromAvatar() { m_LSL_Functions.llDetachFromAvatar(); } public LSL_Vector llDetectedGrab(int number) { return m_LSL_Functions.llDetectedGrab(number); } public LSL_Integer llDetectedGroup(int number) { return m_LSL_Functions.llDetectedGroup(number); } public LSL_Key llDetectedKey(int number) { return m_LSL_Functions.llDetectedKey(number); } public LSL_Integer llDetectedLinkNumber(int number) { return m_LSL_Functions.llDetectedLinkNumber(number); } public LSL_String llDetectedName(int number) { return m_LSL_Functions.llDetectedName(number); } public LSL_Key llDetectedOwner(int number) { return m_LSL_Functions.llDetectedOwner(number); } public LSL_Vector llDetectedPos(int number) { return m_LSL_Functions.llDetectedPos(number); } public LSL_Rotation llDetectedRot(int number) { return m_LSL_Functions.llDetectedRot(number); } public LSL_Integer llDetectedType(int number) { return m_LSL_Functions.llDetectedType(number); } public LSL_Vector llDetectedTouchBinormal(int index) { return m_LSL_Functions.llDetectedTouchBinormal(index); } public LSL_Integer llDetectedTouchFace(int index) { return m_LSL_Functions.llDetectedTouchFace(index); } public LSL_Vector llDetectedTouchNormal(int index) { return m_LSL_Functions.llDetectedTouchNormal(index); } public LSL_Vector llDetectedTouchPos(int index) { return m_LSL_Functions.llDetectedTouchPos(index); } public LSL_Vector llDetectedTouchST(int index) { return m_LSL_Functions.llDetectedTouchST(index); } public LSL_Vector llDetectedTouchUV(int index) { return m_LSL_Functions.llDetectedTouchUV(index); } public LSL_Vector llDetectedVel(int number) { return m_LSL_Functions.llDetectedVel(number); } public void llDialog(string avatar, string message, LSL_List buttons, int chat_channel) { m_LSL_Functions.llDialog(avatar, message, buttons, chat_channel); } public void llDie() { m_LSL_Functions.llDie(); } public LSL_String llDumpList2String(LSL_List src, string seperator) { return m_LSL_Functions.llDumpList2String(src, seperator); } public LSL_Integer llEdgeOfWorld(LSL_Vector pos, LSL_Vector dir) { return m_LSL_Functions.llEdgeOfWorld(pos, dir); } public void llEjectFromLand(string pest) { m_LSL_Functions.llEjectFromLand(pest); } public void llEmail(string address, string subject, string message) { m_LSL_Functions.llEmail(address, subject, message); } public LSL_String llEscapeURL(string url) { return m_LSL_Functions.llEscapeURL(url); } public LSL_Rotation llEuler2Rot(LSL_Vector v) { return m_LSL_Functions.llEuler2Rot(v); } public LSL_Float llFabs(double f) { return m_LSL_Functions.llFabs(f); } public LSL_Integer llFloor(double f) { return m_LSL_Functions.llFloor(f); } public void llForceMouselook(int mouselook) { m_LSL_Functions.llForceMouselook(mouselook); } public LSL_Float llFrand(double mag) { return m_LSL_Functions.llFrand(mag); } public LSL_Key llGenerateKey() { return m_LSL_Functions.llGenerateKey(); } public LSL_Vector llGetAccel() { return m_LSL_Functions.llGetAccel(); } public LSL_Integer llGetAgentInfo(string id) { return m_LSL_Functions.llGetAgentInfo(id); } public LSL_String llGetAgentLanguage(string id) { return m_LSL_Functions.llGetAgentLanguage(id); } public LSL_List llGetAgentList(LSL_Integer scope, LSL_List options) { return m_LSL_Functions.llGetAgentList(scope, options); } public LSL_Vector llGetAgentSize(string id) { return m_LSL_Functions.llGetAgentSize(id); } public LSL_Float llGetAlpha(int face) { return m_LSL_Functions.llGetAlpha(face); } public LSL_Float llGetAndResetTime() { return m_LSL_Functions.llGetAndResetTime(); } public LSL_String llGetAnimation(string id) { return m_LSL_Functions.llGetAnimation(id); } public LSL_List llGetAnimationList(string id) { return m_LSL_Functions.llGetAnimationList(id); } public LSL_Integer llGetAttached() { return m_LSL_Functions.llGetAttached(); } public LSL_List llGetBoundingBox(string obj) { return m_LSL_Functions.llGetBoundingBox(obj); } public LSL_Vector llGetCameraPos() { return m_LSL_Functions.llGetCameraPos(); } public LSL_Rotation llGetCameraRot() { return m_LSL_Functions.llGetCameraRot(); } public LSL_Vector llGetCenterOfMass() { return m_LSL_Functions.llGetCenterOfMass(); } public LSL_Vector llGetColor(int face) { return m_LSL_Functions.llGetColor(face); } public LSL_String llGetCreator() { return m_LSL_Functions.llGetCreator(); } public LSL_String llGetDate() { return m_LSL_Functions.llGetDate(); } public LSL_Float llGetEnergy() { return m_LSL_Functions.llGetEnergy(); } public LSL_Vector llGetForce() { return m_LSL_Functions.llGetForce(); } public LSL_Integer llGetFreeMemory() { return m_LSL_Functions.llGetFreeMemory(); } public LSL_Integer llGetFreeURLs() { return m_LSL_Functions.llGetFreeURLs(); } public LSL_Vector llGetGeometricCenter() { return m_LSL_Functions.llGetGeometricCenter(); } public LSL_Float llGetGMTclock() { return m_LSL_Functions.llGetGMTclock(); } public LSL_String llGetHTTPHeader(LSL_Key request_id, string header) { return m_LSL_Functions.llGetHTTPHeader(request_id, header); } public LSL_Key llGetInventoryCreator(string item) { return m_LSL_Functions.llGetInventoryCreator(item); } public LSL_Key llGetInventoryKey(string name) { return m_LSL_Functions.llGetInventoryKey(name); } public LSL_String llGetInventoryName(int type, int number) { return m_LSL_Functions.llGetInventoryName(type, number); } public LSL_Integer llGetInventoryNumber(int type) { return m_LSL_Functions.llGetInventoryNumber(type); } public LSL_Integer llGetInventoryPermMask(string item, int mask) { return m_LSL_Functions.llGetInventoryPermMask(item, mask); } public LSL_Integer llGetInventoryType(string name) { return m_LSL_Functions.llGetInventoryType(name); } public LSL_Key llGetKey() { return m_LSL_Functions.llGetKey(); } public LSL_Key llGetLandOwnerAt(LSL_Vector pos) { return m_LSL_Functions.llGetLandOwnerAt(pos); } public LSL_Key llGetLinkKey(int linknum) { return m_LSL_Functions.llGetLinkKey(linknum); } public LSL_String llGetLinkName(int linknum) { return m_LSL_Functions.llGetLinkName(linknum); } public LSL_Integer llGetLinkNumber() { return m_LSL_Functions.llGetLinkNumber(); } public LSL_Integer llGetLinkNumberOfSides(int link) { return m_LSL_Functions.llGetLinkNumberOfSides(link); } public void llSetKeyframedMotion(LSL_List frames, LSL_List options) { m_LSL_Functions.llSetKeyframedMotion(frames, options); } public LSL_Integer llGetListEntryType(LSL_List src, int index) { return m_LSL_Functions.llGetListEntryType(src, index); } public LSL_Integer llGetListLength(LSL_List src) { return m_LSL_Functions.llGetListLength(src); } public LSL_Vector llGetLocalPos() { return m_LSL_Functions.llGetLocalPos(); } public LSL_Rotation llGetLocalRot() { return m_LSL_Functions.llGetLocalRot(); } public LSL_Float llGetMass() { return m_LSL_Functions.llGetMass(); } public LSL_Float llGetMassMKS() { return m_LSL_Functions.llGetMassMKS(); } public LSL_Integer llGetMemoryLimit() { return m_LSL_Functions.llGetMemoryLimit(); } public void llGetNextEmail(string address, string subject) { m_LSL_Functions.llGetNextEmail(address, subject); } public LSL_String llGetNotecardLine(string name, int line) { return m_LSL_Functions.llGetNotecardLine(name, line); } public LSL_Key llGetNumberOfNotecardLines(string name) { return m_LSL_Functions.llGetNumberOfNotecardLines(name); } public LSL_Integer llGetNumberOfPrims() { return m_LSL_Functions.llGetNumberOfPrims(); } public LSL_Integer llGetNumberOfSides() { return m_LSL_Functions.llGetNumberOfSides(); } public LSL_String llGetObjectDesc() { return m_LSL_Functions.llGetObjectDesc(); } public LSL_List llGetObjectDetails(string id, LSL_List args) { return m_LSL_Functions.llGetObjectDetails(id, args); } public LSL_Float llGetObjectMass(string id) { return m_LSL_Functions.llGetObjectMass(id); } public LSL_String llGetObjectName() { return m_LSL_Functions.llGetObjectName(); } public LSL_Integer llGetObjectPermMask(int mask) { return m_LSL_Functions.llGetObjectPermMask(mask); } public LSL_Integer llGetObjectPrimCount(string object_id) { return m_LSL_Functions.llGetObjectPrimCount(object_id); } public LSL_Vector llGetOmega() { return m_LSL_Functions.llGetOmega(); } public LSL_Key llGetOwner() { return m_LSL_Functions.llGetOwner(); } public LSL_Key llGetOwnerKey(string id) { return m_LSL_Functions.llGetOwnerKey(id); } public LSL_List llGetParcelDetails(LSL_Vector pos, LSL_List param) { return m_LSL_Functions.llGetParcelDetails(pos, param); } public LSL_Integer llGetParcelFlags(LSL_Vector pos) { return m_LSL_Functions.llGetParcelFlags(pos); } public LSL_Integer llGetParcelMaxPrims(LSL_Vector pos, int sim_wide) { return m_LSL_Functions.llGetParcelMaxPrims(pos, sim_wide); } public LSL_String llGetParcelMusicURL() { return m_LSL_Functions.llGetParcelMusicURL(); } public LSL_Integer llGetParcelPrimCount(LSL_Vector pos, int category, int sim_wide) { return m_LSL_Functions.llGetParcelPrimCount(pos, category, sim_wide); } public LSL_List llGetParcelPrimOwners(LSL_Vector pos) { return m_LSL_Functions.llGetParcelPrimOwners(pos); } public LSL_Integer llGetPermissions() { return m_LSL_Functions.llGetPermissions(); } public LSL_Key llGetPermissionsKey() { return m_LSL_Functions.llGetPermissionsKey(); } public LSL_Vector llGetPos() { return m_LSL_Functions.llGetPos(); } public LSL_List llGetPrimitiveParams(LSL_List rules) { return m_LSL_Functions.llGetPrimitiveParams(rules); } public LSL_List llGetLinkPrimitiveParams(int linknum, LSL_List rules) { return m_LSL_Functions.llGetLinkPrimitiveParams(linknum, rules); } public LSL_Integer llGetRegionAgentCount() { return m_LSL_Functions.llGetRegionAgentCount(); } public LSL_Vector llGetRegionCorner() { return m_LSL_Functions.llGetRegionCorner(); } public LSL_Integer llGetRegionFlags() { return m_LSL_Functions.llGetRegionFlags(); } public LSL_Float llGetRegionFPS() { return m_LSL_Functions.llGetRegionFPS(); } public LSL_String llGetRegionName() { return m_LSL_Functions.llGetRegionName(); } public LSL_Float llGetRegionTimeDilation() { return m_LSL_Functions.llGetRegionTimeDilation(); } public LSL_Vector llGetRootPosition() { return m_LSL_Functions.llGetRootPosition(); } public LSL_Rotation llGetRootRotation() { return m_LSL_Functions.llGetRootRotation(); } public LSL_Rotation llGetRot() { return m_LSL_Functions.llGetRot(); } public LSL_Vector llGetScale() { return m_LSL_Functions.llGetScale(); } public LSL_String llGetScriptName() { return m_LSL_Functions.llGetScriptName(); } public LSL_Integer llGetScriptState(string name) { return m_LSL_Functions.llGetScriptState(name); } public LSL_String llGetSimulatorHostname() { return m_LSL_Functions.llGetSimulatorHostname(); } public LSL_Integer llGetSPMaxMemory() { return m_LSL_Functions.llGetSPMaxMemory(); } public LSL_Integer llGetStartParameter() { return m_LSL_Functions.llGetStartParameter(); } public LSL_Integer llGetStatus(int status) { return m_LSL_Functions.llGetStatus(status); } public LSL_String llGetSubString(string src, int start, int end) { return m_LSL_Functions.llGetSubString(src, start, end); } public LSL_Vector llGetSunDirection() { return m_LSL_Functions.llGetSunDirection(); } public LSL_String llGetTexture(int face) { return m_LSL_Functions.llGetTexture(face); } public LSL_Vector llGetTextureOffset(int face) { return m_LSL_Functions.llGetTextureOffset(face); } public LSL_Float llGetTextureRot(int side) { return m_LSL_Functions.llGetTextureRot(side); } public LSL_Vector llGetTextureScale(int side) { return m_LSL_Functions.llGetTextureScale(side); } public LSL_Float llGetTime() { return m_LSL_Functions.llGetTime(); } public LSL_Float llGetTimeOfDay() { return m_LSL_Functions.llGetTimeOfDay(); } public LSL_String llGetTimestamp() { return m_LSL_Functions.llGetTimestamp(); } public LSL_Vector llGetTorque() { return m_LSL_Functions.llGetTorque(); } public LSL_Integer llGetUnixTime() { return m_LSL_Functions.llGetUnixTime(); } public LSL_Integer llGetUsedMemory() { return m_LSL_Functions.llGetUsedMemory(); } public LSL_Vector llGetVel() { return m_LSL_Functions.llGetVel(); } public LSL_Float llGetWallclock() { return m_LSL_Functions.llGetWallclock(); } public void llGiveInventory(string destination, string inventory) { m_LSL_Functions.llGiveInventory(destination, inventory); } public void llGiveInventoryList(string destination, string category, LSL_List inventory) { m_LSL_Functions.llGiveInventoryList(destination, category, inventory); } public void llGiveMoney(string destination, int amount) { m_LSL_Functions.llGiveMoney(destination, amount); } public LSL_String llTransferLindenDollars(string destination, int amount) { return m_LSL_Functions.llTransferLindenDollars(destination, amount); } public void llGodLikeRezObject(string inventory, LSL_Vector pos) { m_LSL_Functions.llGodLikeRezObject(inventory, pos); } public LSL_Float llGround(LSL_Vector offset) { return m_LSL_Functions.llGround(offset); } public LSL_Vector llGroundContour(LSL_Vector offset) { return m_LSL_Functions.llGroundContour(offset); } public LSL_Vector llGroundNormal(LSL_Vector offset) { return m_LSL_Functions.llGroundNormal(offset); } public void llGroundRepel(double height, int water, double tau) { m_LSL_Functions.llGroundRepel(height, water, tau); } public LSL_Vector llGroundSlope(LSL_Vector offset) { return m_LSL_Functions.llGroundSlope(offset); } public LSL_String llHTTPRequest(string url, LSL_List parameters, string body) { return m_LSL_Functions.llHTTPRequest(url, parameters, body); } public void llHTTPResponse(LSL_Key id, int status, string body) { m_LSL_Functions.llHTTPResponse(id, status, body); } public LSL_String llInsertString(string dst, int position, string src) { return m_LSL_Functions.llInsertString(dst, position, src); } public void llInstantMessage(string user, string message) { m_LSL_Functions.llInstantMessage(user, message); } public LSL_String llIntegerToBase64(int number) { return m_LSL_Functions.llIntegerToBase64(number); } public LSL_String llKey2Name(string id) { return m_LSL_Functions.llKey2Name(id); } public LSL_String llGetUsername(string id) { return m_LSL_Functions.llGetUsername(id); } public LSL_String llRequestUsername(string id) { return m_LSL_Functions.llRequestUsername(id); } public LSL_String llGetDisplayName(string id) { return m_LSL_Functions.llGetDisplayName(id); } public LSL_String llRequestDisplayName(string id) { return m_LSL_Functions.llRequestDisplayName(id); } public LSL_List llCastRay(LSL_Vector start, LSL_Vector end, LSL_List options) { return m_LSL_Functions.llCastRay(start, end, options); } public void llLinkParticleSystem(int linknum, LSL_List rules) { m_LSL_Functions.llLinkParticleSystem(linknum, rules); } public LSL_String llList2CSV(LSL_List src) { return m_LSL_Functions.llList2CSV(src); } public LSL_Float llList2Float(LSL_List src, int index) { return m_LSL_Functions.llList2Float(src, index); } public LSL_Integer llList2Integer(LSL_List src, int index) { return m_LSL_Functions.llList2Integer(src, index); } public LSL_Key llList2Key(LSL_List src, int index) { return m_LSL_Functions.llList2Key(src, index); } public LSL_List llList2List(LSL_List src, int start, int end) { return m_LSL_Functions.llList2List(src, start, end); } public LSL_List llList2ListStrided(LSL_List src, int start, int end, int stride) { return m_LSL_Functions.llList2ListStrided(src, start, end, stride); } public LSL_Rotation llList2Rot(LSL_List src, int index) { return m_LSL_Functions.llList2Rot(src, index); } public LSL_String llList2String(LSL_List src, int index) { return m_LSL_Functions.llList2String(src, index); } public LSL_Vector llList2Vector(LSL_List src, int index) { return m_LSL_Functions.llList2Vector(src, index); } public LSL_Integer llListen(int channelID, string name, string ID, string msg) { return m_LSL_Functions.llListen(channelID, name, ID, msg); } public void llListenControl(int number, int active) { m_LSL_Functions.llListenControl(number, active); } public void llListenRemove(int number) { m_LSL_Functions.llListenRemove(number); } public LSL_Integer llListFindList(LSL_List src, LSL_List test) { return m_LSL_Functions.llListFindList(src, test); } public LSL_List llListInsertList(LSL_List dest, LSL_List src, int start) { return m_LSL_Functions.llListInsertList(dest, src, start); } public LSL_List llListRandomize(LSL_List src, int stride) { return m_LSL_Functions.llListRandomize(src, stride); } public LSL_List llListReplaceList(LSL_List dest, LSL_List src, int start, int end) { return m_LSL_Functions.llListReplaceList(dest, src, start, end); } public LSL_List llListSort(LSL_List src, int stride, int ascending) { return m_LSL_Functions.llListSort(src, stride, ascending); } public LSL_Float llListStatistics(int operation, LSL_List src) { return m_LSL_Functions.llListStatistics(operation, src); } public void llLoadURL(string avatar_id, string message, string url) { m_LSL_Functions.llLoadURL(avatar_id, message, url); } public LSL_Float llLog(double val) { return m_LSL_Functions.llLog(val); } public LSL_Float llLog10(double val) { return m_LSL_Functions.llLog10(val); } public void llLookAt(LSL_Vector target, double strength, double damping) { m_LSL_Functions.llLookAt(target, strength, damping); } public void llLoopSound(string sound, double volume) { m_LSL_Functions.llLoopSound(sound, volume); } public void llLoopSoundMaster(string sound, double volume) { m_LSL_Functions.llLoopSoundMaster(sound, volume); } public void llLoopSoundSlave(string sound, double volume) { m_LSL_Functions.llLoopSoundSlave(sound, volume); } public LSL_Integer llManageEstateAccess(int action, string avatar) { return m_LSL_Functions.llManageEstateAccess(action, avatar); } public void llMakeExplosion(int particles, double scale, double vel, double lifetime, double arc, string texture, LSL_Vector offset) { m_LSL_Functions.llMakeExplosion(particles, scale, vel, lifetime, arc, texture, offset); } public void llMakeFire(int particles, double scale, double vel, double lifetime, double arc, string texture, LSL_Vector offset) { m_LSL_Functions.llMakeFire(particles, scale, vel, lifetime, arc, texture, offset); } public void llMakeFountain(int particles, double scale, double vel, double lifetime, double arc, int bounce, string texture, LSL_Vector offset, double bounce_offset) { m_LSL_Functions.llMakeFountain(particles, scale, vel, lifetime, arc, bounce, texture, offset, bounce_offset); } public void llMakeSmoke(int particles, double scale, double vel, double lifetime, double arc, string texture, LSL_Vector offset) { m_LSL_Functions.llMakeSmoke(particles, scale, vel, lifetime, arc, texture, offset); } public void llMapDestination(string simname, LSL_Vector pos, LSL_Vector look_at) { m_LSL_Functions.llMapDestination(simname, pos, look_at); } public LSL_String llMD5String(string src, int nonce) { return m_LSL_Functions.llMD5String(src, nonce); } public LSL_String llSHA1String(string src) { return m_LSL_Functions.llSHA1String(src); } public void llMessageLinked(int linknum, int num, string str, string id) { m_LSL_Functions.llMessageLinked(linknum, num, str, id); } public void llMinEventDelay(double delay) { m_LSL_Functions.llMinEventDelay(delay); } public void llModifyLand(int action, int brush) { m_LSL_Functions.llModifyLand(action, brush); } public LSL_Integer llModPow(int a, int b, int c) { return m_LSL_Functions.llModPow(a, b, c); } public void llMoveToTarget(LSL_Vector target, double tau) { m_LSL_Functions.llMoveToTarget(target, tau); } public void llOffsetTexture(double u, double v, int face) { m_LSL_Functions.llOffsetTexture(u, v, face); } public void llOpenRemoteDataChannel() { m_LSL_Functions.llOpenRemoteDataChannel(); } public LSL_Integer llOverMyLand(string id) { return m_LSL_Functions.llOverMyLand(id); } public void llOwnerSay(string msg) { m_LSL_Functions.llOwnerSay(msg); } public void llParcelMediaCommandList(LSL_List commandList) { m_LSL_Functions.llParcelMediaCommandList(commandList); } public LSL_List llParcelMediaQuery(LSL_List aList) { return m_LSL_Functions.llParcelMediaQuery(aList); } public LSL_List llParseString2List(string str, LSL_List separators, LSL_List spacers) { return m_LSL_Functions.llParseString2List(str, separators, spacers); } public LSL_List llParseStringKeepNulls(string src, LSL_List seperators, LSL_List spacers) { return m_LSL_Functions.llParseStringKeepNulls(src, seperators, spacers); } public void llParticleSystem(LSL_List rules) { m_LSL_Functions.llParticleSystem(rules); } public void llPassCollisions(int pass) { m_LSL_Functions.llPassCollisions(pass); } public void llPassTouches(int pass) { m_LSL_Functions.llPassTouches(pass); } public void llPlaySound(string sound, double volume) { m_LSL_Functions.llPlaySound(sound, volume); } public void llPlaySoundSlave(string sound, double volume) { m_LSL_Functions.llPlaySoundSlave(sound, volume); } public void llPointAt(LSL_Vector pos) { m_LSL_Functions.llPointAt(pos); } public LSL_Float llPow(double fbase, double fexponent) { return m_LSL_Functions.llPow(fbase, fexponent); } public void llPreloadSound(string sound) { m_LSL_Functions.llPreloadSound(sound); } public void llPushObject(string target, LSL_Vector impulse, LSL_Vector ang_impulse, int local) { m_LSL_Functions.llPushObject(target, impulse, ang_impulse, local); } public void llRefreshPrimURL() { m_LSL_Functions.llRefreshPrimURL(); } public void llRegionSay(int channelID, string text) { m_LSL_Functions.llRegionSay(channelID, text); } public void llRegionSayTo(string key, int channelID, string text) { m_LSL_Functions.llRegionSayTo(key, channelID, text); } public void llReleaseCamera(string avatar) { m_LSL_Functions.llReleaseCamera(avatar); } public void llReleaseURL(string url) { m_LSL_Functions.llReleaseURL(url); } public void llReleaseControls() { m_LSL_Functions.llReleaseControls(); } public void llRemoteDataReply(string channel, string message_id, string sdata, int idata) { m_LSL_Functions.llRemoteDataReply(channel, message_id, sdata, idata); } public void llRemoteDataSetRegion() { m_LSL_Functions.llRemoteDataSetRegion(); } public void llRemoteLoadScript(string target, string name, int running, int start_param) { m_LSL_Functions.llRemoteLoadScript(target, name, running, start_param); } public void llRemoteLoadScriptPin(string target, string name, int pin, int running, int start_param) { m_LSL_Functions.llRemoteLoadScriptPin(target, name, pin, running, start_param); } public void llRemoveFromLandBanList(string avatar) { m_LSL_Functions.llRemoveFromLandBanList(avatar); } public void llRemoveFromLandPassList(string avatar) { m_LSL_Functions.llRemoveFromLandPassList(avatar); } public void llRemoveInventory(string item) { m_LSL_Functions.llRemoveInventory(item); } public void llRemoveVehicleFlags(int flags) { m_LSL_Functions.llRemoveVehicleFlags(flags); } public LSL_Key llRequestAgentData(string id, int data) { return m_LSL_Functions.llRequestAgentData(id, data); } public LSL_Key llRequestInventoryData(string name) { return m_LSL_Functions.llRequestInventoryData(name); } public void llRequestPermissions(string agent, int perm) { m_LSL_Functions.llRequestPermissions(agent, perm); } public LSL_String llRequestSecureURL() { return m_LSL_Functions.llRequestSecureURL(); } public LSL_Key llRequestSimulatorData(string simulator, int data) { return m_LSL_Functions.llRequestSimulatorData(simulator, data); } public LSL_Key llRequestURL() { return m_LSL_Functions.llRequestURL(); } public void llResetLandBanList() { m_LSL_Functions.llResetLandBanList(); } public void llResetLandPassList() { m_LSL_Functions.llResetLandPassList(); } public void llResetOtherScript(string name) { m_LSL_Functions.llResetOtherScript(name); } public void llResetScript() { m_LSL_Functions.llResetScript(); } public void llResetTime() { m_LSL_Functions.llResetTime(); } public void llRezAtRoot(string inventory, LSL_Vector position, LSL_Vector velocity, LSL_Rotation rot, int param) { m_LSL_Functions.llRezAtRoot(inventory, position, velocity, rot, param); } public void llRezObject(string inventory, LSL_Vector pos, LSL_Vector vel, LSL_Rotation rot, int param) { m_LSL_Functions.llRezObject(inventory, pos, vel, rot, param); } public LSL_Float llRot2Angle(LSL_Rotation rot) { return m_LSL_Functions.llRot2Angle(rot); } public LSL_Vector llRot2Axis(LSL_Rotation rot) { return m_LSL_Functions.llRot2Axis(rot); } public LSL_Vector llRot2Euler(LSL_Rotation r) { return m_LSL_Functions.llRot2Euler(r); } public LSL_Vector llRot2Fwd(LSL_Rotation r) { return m_LSL_Functions.llRot2Fwd(r); } public LSL_Vector llRot2Left(LSL_Rotation r) { return m_LSL_Functions.llRot2Left(r); } public LSL_Vector llRot2Up(LSL_Rotation r) { return m_LSL_Functions.llRot2Up(r); } public void llRotateTexture(double rotation, int face) { m_LSL_Functions.llRotateTexture(rotation, face); } public LSL_Rotation llRotBetween(LSL_Vector start, LSL_Vector end) { return m_LSL_Functions.llRotBetween(start, end); } public void llRotLookAt(LSL_Rotation target, double strength, double damping) { m_LSL_Functions.llRotLookAt(target, strength, damping); } public LSL_Integer llRotTarget(LSL_Rotation rot, double error) { return m_LSL_Functions.llRotTarget(rot, error); } public void llRotTargetRemove(int number) { m_LSL_Functions.llRotTargetRemove(number); } public LSL_Integer llRound(double f) { return m_LSL_Functions.llRound(f); } public LSL_Integer llSameGroup(string agent) { return m_LSL_Functions.llSameGroup(agent); } public void llSay(int channelID, string text) { m_LSL_Functions.llSay(channelID, text); } public void llScaleTexture(double u, double v, int face) { m_LSL_Functions.llScaleTexture(u, v, face); } public LSL_Integer llScriptDanger(LSL_Vector pos) { return m_LSL_Functions.llScriptDanger(pos); } public void llScriptProfiler(LSL_Integer flags) { m_LSL_Functions.llScriptProfiler(flags); } public LSL_Key llSendRemoteData(string channel, string dest, int idata, string sdata) { return m_LSL_Functions.llSendRemoteData(channel, dest, idata, sdata); } public void llSensor(string name, string id, int type, double range, double arc) { m_LSL_Functions.llSensor(name, id, type, range, arc); } public void llSensorRemove() { m_LSL_Functions.llSensorRemove(); } public void llSensorRepeat(string name, string id, int type, double range, double arc, double rate) { m_LSL_Functions.llSensorRepeat(name, id, type, range, arc, rate); } public void llSetAlpha(double alpha, int face) { m_LSL_Functions.llSetAlpha(alpha, face); } public void llSetBuoyancy(double buoyancy) { m_LSL_Functions.llSetBuoyancy(buoyancy); } public void llSetCameraAtOffset(LSL_Vector offset) { m_LSL_Functions.llSetCameraAtOffset(offset); } public void llSetCameraEyeOffset(LSL_Vector offset) { m_LSL_Functions.llSetCameraEyeOffset(offset); } public void llSetLinkCamera(LSL_Integer link, LSL_Vector eye, LSL_Vector at) { m_LSL_Functions.llSetLinkCamera(link, eye, at); } public void llSetCameraParams(LSL_List rules) { m_LSL_Functions.llSetCameraParams(rules); } public void llSetClickAction(int action) { m_LSL_Functions.llSetClickAction(action); } public void llSetColor(LSL_Vector color, int face) { m_LSL_Functions.llSetColor(color, face); } public void llSetContentType(LSL_Key id, LSL_Integer type) { m_LSL_Functions.llSetContentType(id, type); } public void llSetDamage(double damage) { m_LSL_Functions.llSetDamage(damage); } public void llSetForce(LSL_Vector force, int local) { m_LSL_Functions.llSetForce(force, local); } public void llSetForceAndTorque(LSL_Vector force, LSL_Vector torque, int local) { m_LSL_Functions.llSetForceAndTorque(force, torque, local); } public void llSetVelocity(LSL_Vector force, int local) { m_LSL_Functions.llSetVelocity(force, local); } public void llSetAngularVelocity(LSL_Vector force, int local) { m_LSL_Functions.llSetAngularVelocity(force, local); } public void llSetHoverHeight(double height, int water, double tau) { m_LSL_Functions.llSetHoverHeight(height, water, tau); } public void llSetInventoryPermMask(string item, int mask, int value) { m_LSL_Functions.llSetInventoryPermMask(item, mask, value); } public void llSetLinkAlpha(int linknumber, double alpha, int face) { m_LSL_Functions.llSetLinkAlpha(linknumber, alpha, face); } public void llSetLinkColor(int linknumber, LSL_Vector color, int face) { m_LSL_Functions.llSetLinkColor(linknumber, color, face); } public void llSetLinkPrimitiveParams(int linknumber, LSL_List rules) { m_LSL_Functions.llSetLinkPrimitiveParams(linknumber, rules); } public void llSetLinkTexture(int linknumber, string texture, int face) { m_LSL_Functions.llSetLinkTexture(linknumber, texture, face); } public void llSetLinkTextureAnim(int linknum, int mode, int face, int sizex, int sizey, double start, double length, double rate) { m_LSL_Functions.llSetLinkTextureAnim(linknum, mode, face, sizex, sizey, start, length, rate); } public void llSetLocalRot(LSL_Rotation rot) { m_LSL_Functions.llSetLocalRot(rot); } public LSL_Integer llSetMemoryLimit(LSL_Integer limit) { return m_LSL_Functions.llSetMemoryLimit(limit); } public void llSetObjectDesc(string desc) { m_LSL_Functions.llSetObjectDesc(desc); } public void llSetObjectName(string name) { m_LSL_Functions.llSetObjectName(name); } public void llSetObjectPermMask(int mask, int value) { m_LSL_Functions.llSetObjectPermMask(mask, value); } public void llSetParcelMusicURL(string url) { m_LSL_Functions.llSetParcelMusicURL(url); } public void llSetPayPrice(int price, LSL_List quick_pay_buttons) { m_LSL_Functions.llSetPayPrice(price, quick_pay_buttons); } public void llSetPos(LSL_Vector pos) { m_LSL_Functions.llSetPos(pos); } public void llSetPrimitiveParams(LSL_List rules) { m_LSL_Functions.llSetPrimitiveParams(rules); } public void llSetLinkPrimitiveParamsFast(int linknum, LSL_List rules) { m_LSL_Functions.llSetLinkPrimitiveParamsFast(linknum, rules); } public void llSetPrimURL(string url) { m_LSL_Functions.llSetPrimURL(url); } public LSL_Integer llSetRegionPos(LSL_Vector pos) { return m_LSL_Functions.llSetRegionPos(pos); } public void llSetRemoteScriptAccessPin(int pin) { m_LSL_Functions.llSetRemoteScriptAccessPin(pin); } public void llSetRot(LSL_Rotation rot) { m_LSL_Functions.llSetRot(rot); } public void llSetScale(LSL_Vector scale) { m_LSL_Functions.llSetScale(scale); } public void llSetScriptState(string name, int run) { m_LSL_Functions.llSetScriptState(name, run); } public void llSetSitText(string text) { m_LSL_Functions.llSetSitText(text); } public void llSetSoundQueueing(int queue) { m_LSL_Functions.llSetSoundQueueing(queue); } public void llSetSoundRadius(double radius) { m_LSL_Functions.llSetSoundRadius(radius); } public void llSetStatus(int status, int value) { m_LSL_Functions.llSetStatus(status, value); } public void llSetText(string text, LSL_Vector color, double alpha) { m_LSL_Functions.llSetText(text, color, alpha); } public void llSetTexture(string texture, int face) { m_LSL_Functions.llSetTexture(texture, face); } public void llSetTextureAnim(int mode, int face, int sizex, int sizey, double start, double length, double rate) { m_LSL_Functions.llSetTextureAnim(mode, face, sizex, sizey, start, length, rate); } public void llSetTimerEvent(double sec) { m_LSL_Functions.llSetTimerEvent(sec); } public void llSetTorque(LSL_Vector torque, int local) { m_LSL_Functions.llSetTorque(torque, local); } public void llSetTouchText(string text) { m_LSL_Functions.llSetTouchText(text); } public void llSetVehicleFlags(int flags) { m_LSL_Functions.llSetVehicleFlags(flags); } public void llSetVehicleFloatParam(int param, LSL_Float value) { m_LSL_Functions.llSetVehicleFloatParam(param, value); } public void llSetVehicleRotationParam(int param, LSL_Rotation rot) { m_LSL_Functions.llSetVehicleRotationParam(param, rot); } public void llSetVehicleType(int type) { m_LSL_Functions.llSetVehicleType(type); } public void llSetVehicleVectorParam(int param, LSL_Vector vec) { m_LSL_Functions.llSetVehicleVectorParam(param, vec); } public void llShout(int channelID, string text) { m_LSL_Functions.llShout(channelID, text); } public LSL_Float llSin(double f) { return m_LSL_Functions.llSin(f); } public void llSitTarget(LSL_Vector offset, LSL_Rotation rot) { m_LSL_Functions.llSitTarget(offset, rot); } public void llLinkSitTarget(LSL_Integer link, LSL_Vector offset, LSL_Rotation rot) { m_LSL_Functions.llLinkSitTarget(link, offset, rot); } public void llSleep(double sec) { m_LSL_Functions.llSleep(sec); } public void llSound(string sound, double volume, int queue, int loop) { m_LSL_Functions.llSound(sound, volume, queue, loop); } public void llSoundPreload(string sound) { m_LSL_Functions.llSoundPreload(sound); } public LSL_Float llSqrt(double f) { return m_LSL_Functions.llSqrt(f); } public void llStartAnimation(string anim) { m_LSL_Functions.llStartAnimation(anim); } public void llStopAnimation(string anim) { m_LSL_Functions.llStopAnimation(anim); } public void llStopHover() { m_LSL_Functions.llStopHover(); } public void llStopLookAt() { m_LSL_Functions.llStopLookAt(); } public void llStopMoveToTarget() { m_LSL_Functions.llStopMoveToTarget(); } public void llStopPointAt() { m_LSL_Functions.llStopPointAt(); } public void llStopSound() { m_LSL_Functions.llStopSound(); } public LSL_Integer llStringLength(string str) { return m_LSL_Functions.llStringLength(str); } public LSL_String llStringToBase64(string str) { return m_LSL_Functions.llStringToBase64(str); } public LSL_String llStringTrim(string src, int type) { return m_LSL_Functions.llStringTrim(src, type); } public LSL_Integer llSubStringIndex(string source, string pattern) { return m_LSL_Functions.llSubStringIndex(source, pattern); } public void llTakeCamera(string avatar) { m_LSL_Functions.llTakeCamera(avatar); } public void llTakeControls(int controls, int accept, int pass_on) { m_LSL_Functions.llTakeControls(controls, accept, pass_on); } public LSL_Float llTan(double f) { return m_LSL_Functions.llTan(f); } public LSL_Integer llTarget(LSL_Vector position, double range) { return m_LSL_Functions.llTarget(position, range); } public void llTargetOmega(LSL_Vector axis, double spinrate, double gain) { m_LSL_Functions.llTargetOmega(axis, spinrate, gain); } public void llTargetRemove(int number) { m_LSL_Functions.llTargetRemove(number); } public void llTeleportAgent(string agent, string simname, LSL_Vector pos, LSL_Vector lookAt) { m_LSL_Functions.llTeleportAgent(agent, simname, pos, lookAt); } public void llTeleportAgentGlobalCoords(string agent, LSL_Vector global, LSL_Vector pos, LSL_Vector lookAt) { m_LSL_Functions.llTeleportAgentGlobalCoords(agent, global, pos, lookAt); } public void llTeleportAgentHome(string agent) { m_LSL_Functions.llTeleportAgentHome(agent); } public void llTextBox(string avatar, string message, int chat_channel) { m_LSL_Functions.llTextBox(avatar, message, chat_channel); } public LSL_String llToLower(string source) { return m_LSL_Functions.llToLower(source); } public LSL_String llToUpper(string source) { return m_LSL_Functions.llToUpper(source); } public void llTriggerSound(string sound, double volume) { m_LSL_Functions.llTriggerSound(sound, volume); } public void llTriggerSoundLimited(string sound, double volume, LSL_Vector top_north_east, LSL_Vector bottom_south_west) { m_LSL_Functions.llTriggerSoundLimited(sound, volume, top_north_east, bottom_south_west); } public LSL_String llUnescapeURL(string url) { return m_LSL_Functions.llUnescapeURL(url); } public void llUnSit(string id) { m_LSL_Functions.llUnSit(id); } public LSL_Float llVecDist(LSL_Vector a, LSL_Vector b) { return m_LSL_Functions.llVecDist(a, b); } public LSL_Float llVecMag(LSL_Vector v) { return m_LSL_Functions.llVecMag(v); } public LSL_Vector llVecNorm(LSL_Vector v) { return m_LSL_Functions.llVecNorm(v); } public void llVolumeDetect(int detect) { m_LSL_Functions.llVolumeDetect(detect); } public LSL_Float llWater(LSL_Vector offset) { return m_LSL_Functions.llWater(offset); } public void llWhisper(int channelID, string text) { m_LSL_Functions.llWhisper(channelID, text); } public LSL_Vector llWind(LSL_Vector offset) { return m_LSL_Functions.llWind(offset); } public LSL_String llXorBase64Strings(string str1, string str2) { return m_LSL_Functions.llXorBase64Strings(str1, str2); } public LSL_String llXorBase64StringsCorrect(string str1, string str2) { return m_LSL_Functions.llXorBase64StringsCorrect(str1, str2); } public LSL_List llGetPrimMediaParams(int face, LSL_List rules) { return m_LSL_Functions.llGetPrimMediaParams(face, rules); } public LSL_List llGetLinkMedia(LSL_Integer link, LSL_Integer face, LSL_List rules) { return m_LSL_Functions.llGetLinkMedia(link, face, rules); } public LSL_Integer llSetPrimMediaParams(int face, LSL_List rules) { return m_LSL_Functions.llSetPrimMediaParams(face, rules); } public LSL_Integer llSetLinkMedia(LSL_Integer link, LSL_Integer face, LSL_List rules) { return m_LSL_Functions.llSetLinkMedia(link, face, rules); } public LSL_Integer llClearPrimMedia(LSL_Integer face) { return m_LSL_Functions.llClearPrimMedia(face); } public LSL_Integer llClearLinkMedia(LSL_Integer link, LSL_Integer face) { return m_LSL_Functions.llClearLinkMedia(link, face); } public void print(string str) { m_LSL_Functions.print(str); } } }
// // (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. // namespace Revit.SDK.Samples.ObjectViewer.CS { using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using Autodesk.Revit; using Autodesk.Revit.DB; using Autodesk.Revit.UI; using Autodesk.Revit.DB.Structure; using Element = Autodesk.Revit.DB.Element; using GeometryElement = Autodesk.Revit.DB.GeometryElement; /// <summary> /// main command class of the ObjectViewer application /// </summary> public class ObjectViewer { /// <summary> /// choose the display kinds of preview /// </summary> public enum DisplayKinds { /// <summary> /// Geometry Model /// </summary> GeometryModel, /// <summary> /// AnalyticalModel /// </summary> AnalyticalModel } private Element m_selected; // selected element to display private View m_currentView; // current View for preview // current detail level for preview private DetailLevels m_detailLevel = DetailLevels.Fine; private List<View> m_allViews = new List<View>(); // all Views in current project // current display kind for preview private DisplayKinds m_displayKind = DisplayKinds.GeometryModel; // selected element's parameters' data private SortableBindingList<Para> m_paras; // current sketch instance to draw the element private Sketch3D m_currentSketch3D = null; // indicate whether select view or detail private bool m_isSelectView = true; /// <summary> /// Current display kind for preview /// </summary> public DisplayKinds DisplayKind { get { return m_displayKind; } set { m_displayKind = value; UpdateSketch3D(); } } /// <summary> /// Current View for preview /// </summary> public View CurrentView { get { return m_currentView; } set { m_currentView = value; m_isSelectView = true; UpdateSketch3D(); } } /// <summary> /// All Views in current project /// </summary> public ReadOnlyCollection<View> AllViews { get { return new ReadOnlyCollection<View>(m_allViews); } } /// <summary> /// Current detail level for preview /// </summary> public DetailLevels DetailLevel { get { return m_detailLevel; } set { m_detailLevel = value; m_isSelectView = false; UpdateSketch3D(); } } /// <summary> /// Current sketch instance to draw the element /// </summary> public Sketch3D CurrentSketch3D { get { return m_currentSketch3D; } } /// <summary> /// Selected element's parameters' data /// </summary> public SortableBindingList<Para> Params { get { return m_paras; } } /// <summary> /// constructor /// </summary> public ObjectViewer() { UIDocument doc = Command.CommandData.Application.ActiveUIDocument; ElementSet selection = doc.Selection.Elements; // only one element should be selected if (0 == selection.Size) { throw new ErrorMessageException("Please select an element."); } if (1 < selection.Size) { throw new ErrorMessageException("Please select only one element."); } // get selected element foreach (Element e in selection) { m_selected = e; } // get current view and all views m_currentView = doc.Document.ActiveView; FilteredElementIterator itor = (new FilteredElementCollector(doc.Document)).OfClass(typeof(View)).GetElementIterator(); itor.Reset(); while (itor.MoveNext()) { View view = itor.Current as View; // Skip view templates because they're invisible in project browser, invalid for geometry elements if (null != view && !view.IsTemplate) { m_allViews.Add(view); } } // create a instance of Sketch3D GeometryData geomFactory = new GeometryData(m_selected, m_currentView); m_currentSketch3D = new Sketch3D(geomFactory.Data3D, Graphics2DData.Empty); //get a instance of ParametersFactory and then use it to create Parameters ParasFactory parasFactory = new ParasFactory(m_selected); m_paras = parasFactory.CreateParas(); } /// <summary> /// update current Sketch3D using current UCS and settings /// </summary> private void UpdateSketch3D() { if (m_displayKind == DisplayKinds.GeometryModel) { GeometryData geomFactory; if(m_isSelectView) { geomFactory = new GeometryData(m_selected, m_currentView); m_detailLevel = DetailLevels.Undefined; } else { geomFactory = new GeometryData(m_selected, m_detailLevel, m_currentView); } Graphics3DData geom3DData = geomFactory.Data3D; Graphics3DData old3DData = m_currentSketch3D.Data3D; geom3DData.CurrentUCS = old3DData.CurrentUCS; m_currentSketch3D.Data3D = geom3DData; m_currentSketch3D.Data2D = Graphics2DData.Empty; } else if (m_displayKind == DisplayKinds.AnalyticalModel) { ModelData modelFactory = new ModelData(m_selected); Graphics3DData model3DData = modelFactory.Data3D; Graphics2DData model2DData = modelFactory.Data2D; Graphics3DData old3DData = m_currentSketch3D.Data3D; model3DData.CurrentUCS = old3DData.CurrentUCS; m_currentSketch3D.Data3D = model3DData; m_currentSketch3D.Data2D = model2DData; } } } }
// 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 System.Runtime.InteropServices; using Microsoft.Scripting; using Microsoft.Scripting.Runtime; using Microsoft.Scripting.Utils; using IronPython.Runtime.Operations; using IronPython.Runtime.Types; namespace IronPython.Runtime { [PythonType] public class staticmethod : PythonTypeSlot { internal object _func; public staticmethod(CodeContext/*!*/ context, object func) { __init__(context, func); } public void __init__(CodeContext/*!*/ context, object func) { _func = func; } internal override bool TryGetValue(CodeContext context, object instance, PythonType owner, out object value) { value = __get__(instance, owner); return true; } internal override bool GetAlwaysSucceeds { get { return true; } } public object __func__ { get { return _func; } } public bool __isabstractmethod__ { get { object isabstract; if (PythonOps.TryGetBoundAttr(_func, "__isabstractmethod__", out isabstract)) { return PythonOps.IsTrue(isabstract); } return false; } } #region IDescriptor Members public object __get__(object instance) { return __get__(instance, null); } public object __get__(object instance, object owner) { return _func; } #endregion } [PythonType] public class classmethod : PythonTypeSlot { internal object _func; public void __init__(CodeContext/*!*/ context, object func) { _func = func; } internal override bool TryGetValue(CodeContext context, object instance, PythonType owner, out object value) { value = __get__(instance, owner); return true; } internal override bool GetAlwaysSucceeds => true; public object __func__ => _func; public bool __isabstractmethod__ { get { if (PythonOps.TryGetBoundAttr(_func, "__isabstractmethod__", out object isabstract)) { return PythonOps.IsTrue(isabstract); } return false; } } #region IDescriptor Members public object __get__(object instance, object owner = null) { if (owner == null) { if (instance == null) throw PythonOps.TypeError("__get__(None, None) is invalid"); if (instance is int) { // IronPython uses Int32 objects as "int" for performance reasons (GH #52) owner = DynamicHelpers.GetPythonTypeFromType(typeof(System.Numerics.BigInteger)); } else { owner = DynamicHelpers.GetPythonType(instance); } } return new Method(_func, owner); } #endregion } [PythonType("property")] public class PythonProperty : PythonTypeDataSlot { private object _fget, _fset, _fdel, _doc; public PythonProperty() { } public PythonProperty(params object[] args) { } public PythonProperty([ParamDictionary] IDictionary<object, object> dict, params object[] args) { } public void __init__(object fget = null, object fset = null, object fdel = null, object doc = null) { _fget = fget; _fset = fset; _fdel = fdel; _doc = doc; if (GetType() != typeof(PythonProperty) && _fget is PythonFunction) { // http://bugs.python.org/issue5890 PythonDictionary dict = UserTypeOps.GetDictionary((IPythonObject)this); if (dict == null) { throw PythonOps.AttributeError("{0} object has no __doc__ attribute", PythonOps.GetPythonTypeName(this)); } dict["__doc__"] = ((PythonFunction)_fget).__doc__; } } internal override bool TryGetValue(CodeContext context, object instance, PythonType owner, out object value) { value = __get__(context, instance, owner); return true; } internal override bool GetAlwaysSucceeds { get { return true; } } internal override bool TrySetValue(CodeContext context, object instance, PythonType owner, object value) { if (instance == null) { return false; } __set__(context, instance, value); return true; } internal override bool TryDeleteValue(CodeContext context, object instance, PythonType owner) { if (instance == null) { return false; } __delete__(context, instance); return true; } public bool __isabstractmethod__ { get { object isabstract; if (PythonOps.TryGetBoundAttr(_fget, "__isabstractmethod__", out isabstract)) { return PythonOps.IsTrue(isabstract); } else if(PythonOps.TryGetBoundAttr(_fset, "__isabstractmethod__", out isabstract)) { return PythonOps.IsTrue(isabstract); } else if(PythonOps.TryGetBoundAttr(_fdel, "__isabstractmethod__", out isabstract)) { return PythonOps.IsTrue(isabstract); } return false; } } [SpecialName, PropertyMethod, WrapperDescriptor] public static object Get__doc__(CodeContext context, PythonProperty self) { if (self._doc is null && PythonOps.TryGetBoundAttr(self._fget, "__doc__", out var doc)) return doc; return self._doc; } [SpecialName, PropertyMethod, WrapperDescriptor] public static void Set__doc__(PythonProperty self, object value) { self._doc = value; } public object fdel { get { return _fdel; } set { throw PythonOps.AttributeError("readonly attribute"); } } public object fset { get { return _fset; } set { throw PythonOps.AttributeError("readonly attribute"); } } public object fget { get { return _fget; } set { throw PythonOps.AttributeError("readonly attribute"); } } public override object __get__(CodeContext/*!*/ context, object instance, object owner=null) { if (instance == null) { return this; } else if (fget != null) { var site = context.LanguageContext.PropertyGetSite; return site.Target(site, context, fget, instance); } throw PythonOps.UnreadableProperty(); } public override void __set__(CodeContext/*!*/ context, object instance, object value) { if (fset != null) { var site = context.LanguageContext.PropertySetSite; site.Target(site, context, fset, instance, value); } else { throw PythonOps.UnsetableProperty(); } } public override void __delete__(CodeContext/*!*/ context, object instance) { if (fdel != null) { var site = context.LanguageContext.PropertyDeleteSite; site.Target(site, context, fdel, instance); } else { throw PythonOps.UndeletableProperty(); } } public PythonProperty getter(object fget) { PythonProperty res = new PythonProperty(); res.__init__(fget, _fset, _fdel, _doc); return res; } public PythonProperty setter(object fset) { PythonProperty res = new PythonProperty(); res.__init__(_fget, fset, _fdel, _doc); return res; } public PythonProperty deleter(object fdel) { PythonProperty res = new PythonProperty(); res.__init__(_fget, _fset, fdel, _doc); return res; } } }
#if TODO_XAML using System; using System.Collections.Generic; using System.Linq; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Media.Imaging; namespace Eto.WinRT.CustomControls { /// <summary> /// An image that supports multiple sizes depending on its own rendering size. /// </summary> /// <remarks> /// Extends the standard <see cref="Image"/> control with the functionality to /// load all the available frames in its <see cref="Image.Source"/> and render the one /// that best matches the current rendering size of the control. /// /// For example, if the Source is a TIFF file containing frames of sizes 24x24, 48x48 and 128x128 /// and the image is rendered at size 40x40, the frame with resolution 48x48 is used. /// The same control with the same source rendered at 24x24 would use the 24x24 frame. /// /// <para>Written by Isak Savo - isak.savo@gmail.com, (c) 2011-2012. Licensed under the Code Project </para> /// </remarks> public class MultiSizeImage : Image { Brush background; bool useSmallestSpace; public Brush Background { get { return background; } set { if (background != value) { background = value; InvalidateVisual (); } } } public bool UseSmallestSpace { get { return useSmallestSpace; } set { if (useSmallestSpace != value) { useSmallestSpace = value; InvalidateMeasure(); } } } static MultiSizeImage () { // Tell WPF to inform us whenever the Source dependency property is changed SourceProperty.OverrideMetadata (typeof (MultiSizeImage), new FrameworkPropertyMetadata (HandleSourceChanged)); } static void HandleSourceChanged (DependencyObject sender, DependencyPropertyChangedEventArgs e) { var img = (MultiSizeImage)sender; img.UpdateAvailableFrames (); } /// <summary> /// List containing one frame of every size available in the original file. The frame /// stored in this list is the one with the highest pixel depth for that size. /// </summary> readonly List<BitmapSource> _availableFrames = new List<BitmapSource> (); /// <summary> /// Gets the pixel depth (in bits per pixel, bpp) of the specified frame /// </summary> /// <param name="frame">The frame to get BPP for</param> /// <returns>The number of bits per pixel in the frame</returns> static int GetFramePixelDepth (BitmapFrame frame) { if (frame.Decoder.CodecInfo.ContainerFormat == new Guid("{a3a860c4-338f-4c17-919a-fba4b5628f21}") && frame.Thumbnail != null) { // Windows Icon format, original pixel depth is in the thumbnail return frame.Thumbnail.Format.BitsPerPixel; } // Other formats, just assume the frame has the correct BPP info return frame.Format.BitsPerPixel; } protected override Size ArrangeOverride (Size arrangeSize) { return MeasureArrangeHelper (arrangeSize); } protected override Size MeasureOverride (Size constraint) { return MeasureArrangeHelper (constraint); } static bool IsZero (double value) { return Math.Abs (value) < 2.2204460492503131E-15; } static Size ComputeScaleFactor (Size availableSize, Size contentSize, Stretch stretch, StretchDirection stretchDirection) { double widthFactor = 1.0; double heightFactor = 1.0; bool widthSet = !double.IsPositiveInfinity (availableSize.Width); bool heightSet = !double.IsPositiveInfinity (availableSize.Height); if ((stretch == Stretch.Uniform || stretch == Stretch.UniformToFill || stretch == Stretch.Fill) && (widthSet || heightSet)) { widthFactor = (IsZero (contentSize.Width) ? 0.0 : (availableSize.Width / contentSize.Width)); heightFactor = (IsZero (contentSize.Height) ? 0.0 : (availableSize.Height / contentSize.Height)); if (!widthSet) widthFactor = heightFactor; else { if (!heightSet) heightFactor = widthFactor; else { switch (stretch) { case Stretch.Uniform: { double num3 = (widthFactor < heightFactor) ? widthFactor : heightFactor; heightFactor = (widthFactor = num3); break; } case Stretch.UniformToFill: { double num4 = (widthFactor > heightFactor) ? widthFactor : heightFactor; heightFactor = (widthFactor = num4); break; } } } } switch (stretchDirection) { case StretchDirection.UpOnly: if (widthFactor < 1.0) widthFactor = 1.0; if (heightFactor < 1.0) heightFactor = 1.0; break; case StretchDirection.DownOnly: if (widthFactor > 1.0) widthFactor = 1.0; if (heightFactor > 1.0) heightFactor = 1.0; break; } } return new Size (widthFactor, heightFactor); } Size MeasureArrangeHelper (Size inputSize) { if (Source == null) return Size.Empty; var first = _availableFrames.LastOrDefault (); var size = new Size (Source.Width, Source.Width); if (first == null) return size; size = new Size (first.Width, first.Height); Size scale = ComputeScaleFactor(inputSize, size, Stretch, StretchDirection); if (UseSmallestSpace) { if (double.IsPositiveInfinity(inputSize.Width) && scale.Width > 1) { scale.Width = 1; scale.Height = 1; } if (double.IsPositiveInfinity(inputSize.Height) && scale.Height > 1) { scale.Width = 1; scale.Height = 1; } } return new Size (size.Width * scale.Width, size.Height * scale.Height); } /// <summary> /// Scans the ImageSource for available frames and stores /// them as individual bitmap sources. This is done once, /// when the <see cref="Image.Source"/> property is set (or changed) /// </summary> void UpdateAvailableFrames () { _availableFrames.Clear (); var bmFrame = Source as BitmapFrame; if (bmFrame == null) return; var decoder = bmFrame.Decoder; if (decoder != null && decoder.Frames != null) { var framesInSizeOrder = from frame in decoder.Frames group frame by frame.PixelHeight * frame.PixelWidth into g orderby g.Key select new { Size = g.Key, Frames = g.OrderByDescending (GetFramePixelDepth) }; _availableFrames.AddRange (framesInSizeOrder.Select (group => group.Frames.First ())); } } /// <summary> /// Renders the contents of the image /// </summary> /// <param name="dc">An instance of <see cref="T:Windows.UI.Xaml.Media.DrawingContext"/> used to render the control.</param> protected override void OnRender (DrawingContext dc) { if (background != null) dc.DrawRectangle (background, null, new Rect (0, 0, RenderSize.Width, RenderSize.Height)); if (Source == null) return; ImageSource src = Source; var ourSize = RenderSize.Width * RenderSize.Height; foreach (var frame in _availableFrames) { src = frame; if (frame.PixelWidth * frame.PixelHeight >= ourSize) break; } dc.DrawImage (src, new Rect (new Point (0, 0), RenderSize)); } } } #endif
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Diagnostics; using System.Dynamic.Utils; using System.Reflection; namespace System.Linq.Expressions.Interpreter { internal abstract class MulInstruction : Instruction { private static Instruction s_int16,s_int32,s_int64,s_UInt16,s_UInt32,s_UInt64,s_single,s_double; public override int ConsumedStack { get { return 2; } } public override int ProducedStack { get { return 1; } } public override string InstructionName { get { return "Mul"; } } private MulInstruction() { } internal sealed class MulInt32 : MulInstruction { public override int Run(InterpretedFrame frame) { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; if (l == null || r == null) { frame.Data[frame.StackIndex - 2] = null; } else { frame.Data[frame.StackIndex - 2] = ScriptingRuntimeHelpers.Int32ToObject(unchecked((Int32)l * (Int32)r)); } frame.StackIndex--; return +1; } } internal sealed class MulInt16 : MulInstruction { public override int Run(InterpretedFrame frame) { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; if (l == null || r == null) { frame.Data[frame.StackIndex - 2] = null; } else { frame.Data[frame.StackIndex - 2] = (Int16)unchecked((Int16)l * (Int16)r); } frame.StackIndex--; return +1; } } internal sealed class MulInt64 : MulInstruction { public override int Run(InterpretedFrame frame) { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; if (l == null || r == null) { frame.Data[frame.StackIndex - 2] = null; } else { frame.Data[frame.StackIndex - 2] = (Int64)unchecked((Int64)l * (Int64)r); } frame.StackIndex--; return +1; } } internal sealed class MulUInt16 : MulInstruction { public override int Run(InterpretedFrame frame) { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; if (l == null || r == null) { frame.Data[frame.StackIndex - 2] = null; } else { frame.Data[frame.StackIndex - 2] = (UInt16)unchecked((UInt16)l * (UInt16)r); } frame.StackIndex--; return +1; } } internal sealed class MulUInt32 : MulInstruction { public override int Run(InterpretedFrame frame) { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; if (l == null || r == null) { frame.Data[frame.StackIndex - 2] = null; } else { frame.Data[frame.StackIndex - 2] = (UInt32)unchecked((UInt32)l * (UInt32)r); } frame.StackIndex--; return +1; } } internal sealed class MulUInt64 : MulInstruction { public override int Run(InterpretedFrame frame) { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; if (l == null || r == null) { frame.Data[frame.StackIndex - 2] = null; } else { frame.Data[frame.StackIndex - 2] = (UInt64)unchecked((UInt64)l * (UInt64)r); } frame.StackIndex--; return +1; } } internal sealed class MulSingle : MulInstruction { public override int Run(InterpretedFrame frame) { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; if (l == null || r == null) { frame.Data[frame.StackIndex - 2] = null; } else { frame.Data[frame.StackIndex - 2] = (Single)((Single)l * (Single)r); } frame.StackIndex--; return +1; } } internal sealed class MulDouble : MulInstruction { public override int Run(InterpretedFrame frame) { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; if (l == null || r == null) { frame.Data[frame.StackIndex - 2] = null; } else { frame.Data[frame.StackIndex - 2] = (Double)l * (Double)r; } frame.StackIndex--; return +1; } } public static Instruction Create(Type type) { Debug.Assert(!type.GetTypeInfo().IsEnum); switch (System.Dynamic.Utils.TypeExtensions.GetTypeCode(TypeUtils.GetNonNullableType(type))) { case TypeCode.Int16: return s_int16 ?? (s_int16 = new MulInt16()); case TypeCode.Int32: return s_int32 ?? (s_int32 = new MulInt32()); case TypeCode.Int64: return s_int64 ?? (s_int64 = new MulInt64()); case TypeCode.UInt16: return s_UInt16 ?? (s_UInt16 = new MulUInt16()); case TypeCode.UInt32: return s_UInt32 ?? (s_UInt32 = new MulUInt32()); case TypeCode.UInt64: return s_UInt64 ?? (s_UInt64 = new MulUInt64()); case TypeCode.Single: return s_single ?? (s_single = new MulSingle()); case TypeCode.Double: return s_double ?? (s_double = new MulDouble()); default: throw Error.ExpressionNotSupportedForType("Mul", type); } } public override string ToString() { return "Mul()"; } } internal abstract class MulOvfInstruction : Instruction { private static Instruction s_int16,s_int32,s_int64,s_UInt16,s_UInt32,s_UInt64,s_single,s_double; public override int ConsumedStack { get { return 2; } } public override int ProducedStack { get { return 1; } } public override string InstructionName { get { return "MulOvf"; } } private MulOvfInstruction() { } internal sealed class MulOvfInt32 : MulOvfInstruction { public override int Run(InterpretedFrame frame) { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; if (l == null || r == null) { frame.Data[frame.StackIndex - 2] = null; } else { frame.Data[frame.StackIndex - 2] = ScriptingRuntimeHelpers.Int32ToObject(checked((Int32)l * (Int32)r)); } frame.StackIndex--; return +1; } } internal sealed class MulOvfInt16 : MulOvfInstruction { public override int Run(InterpretedFrame frame) { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; if (l == null || r == null) { frame.Data[frame.StackIndex - 2] = null; } else { frame.Data[frame.StackIndex - 2] = (Int16)checked((Int16)l * (Int16)r); } frame.StackIndex--; return +1; } } internal sealed class MulOvfInt64 : MulOvfInstruction { public override int Run(InterpretedFrame frame) { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; if (l == null || r == null) { frame.Data[frame.StackIndex - 2] = null; } else { frame.Data[frame.StackIndex - 2] = (Int64)checked((Int64)l * (Int64)r); } frame.StackIndex--; return +1; } } internal sealed class MulOvfUInt16 : MulOvfInstruction { public override int Run(InterpretedFrame frame) { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; if (l == null || r == null) { frame.Data[frame.StackIndex - 2] = null; } else { frame.Data[frame.StackIndex - 2] = (UInt16)checked((UInt16)l * (UInt16)r); } frame.StackIndex--; return +1; } } internal sealed class MulOvfUInt32 : MulOvfInstruction { public override int Run(InterpretedFrame frame) { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; if (l == null || r == null) { frame.Data[frame.StackIndex - 2] = null; } else { frame.Data[frame.StackIndex - 2] = (UInt32)checked((UInt32)l * (UInt32)r); } frame.StackIndex--; return +1; } } internal sealed class MulOvfUInt64 : MulOvfInstruction { public override int Run(InterpretedFrame frame) { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; if (l == null || r == null) { frame.Data[frame.StackIndex - 2] = null; } else { frame.Data[frame.StackIndex - 2] = (UInt64)checked((UInt64)l * (UInt64)r); } frame.StackIndex--; return +1; } } internal sealed class MulOvfSingle : MulOvfInstruction { public override int Run(InterpretedFrame frame) { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; if (l == null || r == null) { frame.Data[frame.StackIndex - 2] = null; } else { frame.Data[frame.StackIndex - 2] = (Single)((Single)l * (Single)r); } frame.StackIndex--; return +1; } } internal sealed class MulOvfDouble : MulOvfInstruction { public override int Run(InterpretedFrame frame) { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; if (l == null || r == null) { frame.Data[frame.StackIndex - 2] = null; } else { frame.Data[frame.StackIndex - 2] = (Double)l * (Double)r; } frame.StackIndex--; return +1; } } public static Instruction Create(Type type) { Debug.Assert(!type.GetTypeInfo().IsEnum); switch (System.Dynamic.Utils.TypeExtensions.GetTypeCode(TypeUtils.GetNonNullableType(type))) { case TypeCode.Int16: return s_int16 ?? (s_int16 = new MulOvfInt16()); case TypeCode.Int32: return s_int32 ?? (s_int32 = new MulOvfInt32()); case TypeCode.Int64: return s_int64 ?? (s_int64 = new MulOvfInt64()); case TypeCode.UInt16: return s_UInt16 ?? (s_UInt16 = new MulOvfUInt16()); case TypeCode.UInt32: return s_UInt32 ?? (s_UInt32 = new MulOvfUInt32()); case TypeCode.UInt64: return s_UInt64 ?? (s_UInt64 = new MulOvfUInt64()); case TypeCode.Single: return s_single ?? (s_single = new MulOvfSingle()); case TypeCode.Double: return s_double ?? (s_double = new MulOvfDouble()); default: throw Error.ExpressionNotSupportedForType("MulOvf", type); } } public override string ToString() { return "MulOvf()"; } } }
// 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.Globalization { using System.Security.Permissions; using System.Runtime.Serialization; using System.Text; using System; using System.Diagnostics.Contracts; // // Property Default Description // PositiveSign '+' Character used to indicate positive values. // NegativeSign '-' Character used to indicate negative values. // NumberDecimalSeparator '.' The character used as the decimal separator. // NumberGroupSeparator ',' The character used to separate groups of // digits to the left of the decimal point. // NumberDecimalDigits 2 The default number of decimal places. // NumberGroupSizes 3 The number of digits in each group to the // left of the decimal point. // NaNSymbol "NaN" The string used to represent NaN values. // PositiveInfinitySymbol"Infinity" The string used to represent positive // infinities. // NegativeInfinitySymbol"-Infinity" The string used to represent negative // infinities. // // // // Property Default Description // CurrencyDecimalSeparator '.' The character used as the decimal // separator. // CurrencyGroupSeparator ',' The character used to separate groups // of digits to the left of the decimal // point. // CurrencyDecimalDigits 2 The default number of decimal places. // CurrencyGroupSizes 3 The number of digits in each group to // the left of the decimal point. // CurrencyPositivePattern 0 The format of positive values. // CurrencyNegativePattern 0 The format of negative values. // CurrencySymbol "$" String used as local monetary symbol. // [Serializable] [System.Runtime.InteropServices.ComVisible(true)] sealed public partial class NumberFormatInfo : ICloneable, IFormatProvider { // invariantInfo is constant irrespective of your current culture. private static volatile NumberFormatInfo invariantInfo; // READTHIS READTHIS READTHIS // This class has an exact mapping onto a native structure defined in COMNumber.cpp // DO NOT UPDATE THIS WITHOUT UPDATING THAT STRUCTURE. IF YOU ADD BOOL, ADD THEM AT THE END. // ALSO MAKE SURE TO UPDATE mscorlib.h in the VM directory to check field offsets. // READTHIS READTHIS READTHIS internal int[] numberGroupSizes = new int[] {3}; internal int[] currencyGroupSizes = new int[] {3}; internal int[] percentGroupSizes = new int[] {3}; internal String positiveSign = "+"; internal String negativeSign = "-"; internal String numberDecimalSeparator = "."; internal String numberGroupSeparator = ","; internal String currencyGroupSeparator = ","; internal String currencyDecimalSeparator = "."; internal String currencySymbol = "\x00a4"; // U+00a4 is the symbol for International Monetary Fund. // The alternative currency symbol used in Win9x ANSI codepage, that can not roundtrip between ANSI and Unicode. // Currently, only ja-JP and ko-KR has non-null values (which is U+005c, backslash) // NOTE: The only legal values for this string are null and "\x005c" internal String ansiCurrencySymbol = null; internal String nanSymbol = "NaN"; internal String positiveInfinitySymbol = "Infinity"; internal String negativeInfinitySymbol = "-Infinity"; internal String percentDecimalSeparator = "."; internal String percentGroupSeparator = ","; internal String percentSymbol = "%"; internal String perMilleSymbol = "\u2030"; [OptionalField(VersionAdded = 2)] internal String[] nativeDigits = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9"}; // an index which points to a record in Culture Data Table. // We shouldn't be persisting dataItem (since its useless & we weren't using it), // but since COMNumber.cpp uses it and since serialization isn't implimented, its stuck for now. [OptionalField(VersionAdded = 1)] internal int m_dataItem = 0; // NEVER USED, DO NOT USE THIS! (Serialized in Everett) internal int numberDecimalDigits = 2; internal int currencyDecimalDigits = 2; internal int currencyPositivePattern = 0; internal int currencyNegativePattern = 0; internal int numberNegativePattern = 1; internal int percentPositivePattern = 0; internal int percentNegativePattern = 0; internal int percentDecimalDigits = 2; [OptionalField(VersionAdded = 2)] internal int digitSubstitution = 1; // DigitShapes.None internal bool isReadOnly=false; // We shouldn't be persisting m_useUserOverride (since its useless & we weren't using it), // but since COMNumber.cpp uses it and since serialization isn't implimented, its stuck for now. [OptionalField(VersionAdded = 1)] internal bool m_useUserOverride=false; // NEVER USED, DO NOT USE THIS! (Serialized in Everett) // Is this NumberFormatInfo for invariant culture? [OptionalField(VersionAdded = 2)] internal bool m_isInvariant=false; public NumberFormatInfo() : this(null) { } #region Serialization // Check if NumberFormatInfo was not set up ambiguously for parsing as number and currency // eg. if the NumberDecimalSeparator and the NumberGroupSeparator were the same. This check // is solely for backwards compatibility / version tolerant serialization [OptionalField(VersionAdded = 1)] internal bool validForParseAsNumber = true; // NEVER USED, DO NOT USE THIS! (Serialized in Whidbey/Everett) [OptionalField(VersionAdded = 1)] internal bool validForParseAsCurrency = true; // NEVER USED, DO NOT USE THIS! (Serialized in Whidbey/Everett) [OnSerializing] private void OnSerializing(StreamingContext ctx) { } [OnDeserializing] private void OnDeserializing(StreamingContext ctx) { } [OnDeserialized] private void OnDeserialized(StreamingContext ctx) { } #endregion Serialization static private void VerifyDecimalSeparator(String decSep, String propertyName) { if (decSep==null) { throw new ArgumentNullException(propertyName, Environment.GetResourceString("ArgumentNull_String")); } if (decSep.Length==0) { throw new ArgumentException(Environment.GetResourceString("Argument_EmptyDecString")); } Contract.EndContractBlock(); } static private void VerifyGroupSeparator(String groupSep, String propertyName) { if (groupSep==null) { throw new ArgumentNullException(propertyName, Environment.GetResourceString("ArgumentNull_String")); } Contract.EndContractBlock(); } static private void VerifyNativeDigits(String [] nativeDig, String propertyName) { if (nativeDig==null) { throw new ArgumentNullException(propertyName, Environment.GetResourceString("ArgumentNull_Array")); } if (nativeDig.Length != 10) { throw new ArgumentException(Environment.GetResourceString("Argument_InvalidNativeDigitCount"), propertyName); } Contract.EndContractBlock(); for(int i = 0; i < nativeDig.Length; i++) { if (nativeDig[i] == null) { throw new ArgumentNullException(propertyName, Environment.GetResourceString("ArgumentNull_ArrayValue")); } if (nativeDig[i].Length != 1) { if(nativeDig[i].Length != 2) { // Not 1 or 2 UTF-16 code points throw new ArgumentException(Environment.GetResourceString("Argument_InvalidNativeDigitValue"), propertyName); } else if(!char.IsSurrogatePair(nativeDig[i][0], nativeDig[i][1])) { // 2 UTF-6 code points, but not a surrogate pair throw new ArgumentException(Environment.GetResourceString("Argument_InvalidNativeDigitValue"), propertyName); } } if (CharUnicodeInfo.GetDecimalDigitValue(nativeDig[i], 0) != i && CharUnicodeInfo.GetUnicodeCategory(nativeDig[i], 0) != UnicodeCategory.PrivateUse) { // Not the appropriate digit according to the Unicode data properties // (Digit 0 must be a 0, etc.). throw new ArgumentException(Environment.GetResourceString("Argument_InvalidNativeDigitValue"), propertyName); } } } static private void VerifyDigitSubstitution(DigitShapes digitSub, String propertyName) { switch(digitSub) { case DigitShapes.Context: case DigitShapes.None: case DigitShapes.NativeNational: // Success. break; default: throw new ArgumentException(Environment.GetResourceString("Argument_InvalidDigitSubstitution"), propertyName); } } // We aren't persisting dataItem any more (since its useless & we weren't using it), // Ditto with m_useUserOverride. Don't use them, we use a local copy of everything. internal NumberFormatInfo(CultureData cultureData) { if (cultureData != null) { // We directly use fields here since these data is coming from data table or Win32, so we // don't need to verify their values (except for invalid parsing situations). cultureData.GetNFIValues(this); if (cultureData.IsInvariantCulture) { // For invariant culture this.m_isInvariant = true; } } } [Pure] private void VerifyWritable() { if (isReadOnly) { throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ReadOnly")); } Contract.EndContractBlock(); } // Returns a default NumberFormatInfo that will be universally // supported and constant irrespective of the current culture. // Used by FromString methods. // public static NumberFormatInfo InvariantInfo { get { if (invariantInfo == null) { // Lazy create the invariant info. This cannot be done in a .cctor because exceptions can // be thrown out of a .cctor stack that will need this. NumberFormatInfo nfi = new NumberFormatInfo(); nfi.m_isInvariant = true; invariantInfo = ReadOnly(nfi); } return invariantInfo; } } public static NumberFormatInfo GetInstance(IFormatProvider formatProvider) { // Fast case for a regular CultureInfo NumberFormatInfo info; CultureInfo cultureProvider = formatProvider as CultureInfo; if (cultureProvider != null && !cultureProvider.m_isInherited) { info = cultureProvider.numInfo; if (info != null) { return info; } else { return cultureProvider.NumberFormat; } } // Fast case for an NFI; info = formatProvider as NumberFormatInfo; if (info != null) { return info; } if (formatProvider != null) { info = formatProvider.GetFormat(typeof(NumberFormatInfo)) as NumberFormatInfo; if (info != null) { return info; } } return CurrentInfo; } public Object Clone() { NumberFormatInfo n = (NumberFormatInfo)MemberwiseClone(); n.isReadOnly = false; return n; } public int CurrencyDecimalDigits { get { return currencyDecimalDigits; } set { if (value < 0 || value > 99) { throw new ArgumentOutOfRangeException( nameof(CurrencyDecimalDigits), String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Range"), 0, 99)); } Contract.EndContractBlock(); VerifyWritable(); currencyDecimalDigits = value; } } public String CurrencyDecimalSeparator { get { return currencyDecimalSeparator; } set { VerifyWritable(); VerifyDecimalSeparator(value, nameof(CurrencyDecimalSeparator)); currencyDecimalSeparator = value; } } public bool IsReadOnly { get { return isReadOnly; } } // // Check the values of the groupSize array. // // Every element in the groupSize array should be between 1 and 9 // excpet the last element could be zero. // static internal void CheckGroupSize(String propName, int[] groupSize) { for (int i = 0; i < groupSize.Length; i++) { if (groupSize[i] < 1) { if (i == groupSize.Length - 1 && groupSize[i] == 0) return; throw new ArgumentException(Environment.GetResourceString("Argument_InvalidGroupSize"), propName); } else if (groupSize[i] > 9) { throw new ArgumentException(Environment.GetResourceString("Argument_InvalidGroupSize"), propName); } } } public int[] CurrencyGroupSizes { get { return ((int[])currencyGroupSizes.Clone()); } set { if (value == null) { throw new ArgumentNullException(nameof(CurrencyGroupSizes), Environment.GetResourceString("ArgumentNull_Obj")); } Contract.EndContractBlock(); VerifyWritable(); Int32[] inputSizes = (Int32[])value.Clone(); CheckGroupSize(nameof(CurrencyGroupSizes), inputSizes); currencyGroupSizes = inputSizes; } } public int[] NumberGroupSizes { get { return ((int[])numberGroupSizes.Clone()); } set { if (value == null) { throw new ArgumentNullException(nameof(NumberGroupSizes), Environment.GetResourceString("ArgumentNull_Obj")); } Contract.EndContractBlock(); VerifyWritable(); Int32[] inputSizes = (Int32[])value.Clone(); CheckGroupSize(nameof(NumberGroupSizes), inputSizes); numberGroupSizes = inputSizes; } } public int[] PercentGroupSizes { get { return ((int[])percentGroupSizes.Clone()); } set { if (value == null) { throw new ArgumentNullException(nameof(PercentGroupSizes), Environment.GetResourceString("ArgumentNull_Obj")); } Contract.EndContractBlock(); VerifyWritable(); Int32[] inputSizes = (Int32[])value.Clone(); CheckGroupSize(nameof(PercentGroupSizes), inputSizes); percentGroupSizes = inputSizes; } } public String CurrencyGroupSeparator { get { return currencyGroupSeparator; } set { VerifyWritable(); VerifyGroupSeparator(value, nameof(CurrencyGroupSeparator)); currencyGroupSeparator = value; } } public String CurrencySymbol { get { return currencySymbol; } set { if (value == null) { throw new ArgumentNullException(nameof(CurrencySymbol), Environment.GetResourceString("ArgumentNull_String")); } Contract.EndContractBlock(); VerifyWritable(); currencySymbol = value; } } // Returns the current culture's NumberFormatInfo. Used by Parse methods. // public static NumberFormatInfo CurrentInfo { get { System.Globalization.CultureInfo culture = System.Threading.Thread.CurrentThread.CurrentCulture; if (!culture.m_isInherited) { NumberFormatInfo info = culture.numInfo; if (info != null) { return info; } } return ((NumberFormatInfo)culture.GetFormat(typeof(NumberFormatInfo))); } } public String NaNSymbol { get { return nanSymbol; } set { if (value == null) { throw new ArgumentNullException(nameof(NaNSymbol), Environment.GetResourceString("ArgumentNull_String")); } Contract.EndContractBlock(); VerifyWritable(); nanSymbol = value; } } public int CurrencyNegativePattern { get { return currencyNegativePattern; } set { if (value < 0 || value > 15) { throw new ArgumentOutOfRangeException( nameof(CurrencyNegativePattern), String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Range"), 0, 15)); } Contract.EndContractBlock(); VerifyWritable(); currencyNegativePattern = value; } } public int NumberNegativePattern { get { return numberNegativePattern; } set { // // NOTENOTE: the range of value should correspond to negNumberFormats[] in vm\COMNumber.cpp. // if (value < 0 || value > 4) { throw new ArgumentOutOfRangeException( nameof(NumberNegativePattern), String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Range"), 0, 4)); } Contract.EndContractBlock(); VerifyWritable(); numberNegativePattern = value; } } public int PercentPositivePattern { get { return percentPositivePattern; } set { // // NOTENOTE: the range of value should correspond to posPercentFormats[] in vm\COMNumber.cpp. // if (value < 0 || value > 3) { throw new ArgumentOutOfRangeException( nameof(PercentPositivePattern), String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Range"), 0, 3)); } Contract.EndContractBlock(); VerifyWritable(); percentPositivePattern = value; } } public int PercentNegativePattern { get { return percentNegativePattern; } set { // // NOTENOTE: the range of value should correspond to posPercentFormats[] in vm\COMNumber.cpp. // if (value < 0 || value > 11) { throw new ArgumentOutOfRangeException( nameof(PercentNegativePattern), String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Range"), 0, 11)); } Contract.EndContractBlock(); VerifyWritable(); percentNegativePattern = value; } } public String NegativeInfinitySymbol { get { return negativeInfinitySymbol; } set { if (value == null) { throw new ArgumentNullException(nameof(NegativeInfinitySymbol), Environment.GetResourceString("ArgumentNull_String")); } Contract.EndContractBlock(); VerifyWritable(); negativeInfinitySymbol = value; } } public String NegativeSign { get { return negativeSign; } set { if (value == null) { throw new ArgumentNullException(nameof(NegativeSign), Environment.GetResourceString("ArgumentNull_String")); } Contract.EndContractBlock(); VerifyWritable(); negativeSign = value; } } public int NumberDecimalDigits { get { return numberDecimalDigits; } set { if (value < 0 || value > 99) { throw new ArgumentOutOfRangeException( nameof(NumberDecimalDigits), String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Range"), 0, 99)); } Contract.EndContractBlock(); VerifyWritable(); numberDecimalDigits = value; } } public String NumberDecimalSeparator { get { return numberDecimalSeparator; } set { VerifyWritable(); VerifyDecimalSeparator(value, nameof(NumberDecimalSeparator)); numberDecimalSeparator = value; } } public String NumberGroupSeparator { get { return numberGroupSeparator; } set { VerifyWritable(); VerifyGroupSeparator(value, nameof(NumberGroupSeparator)); numberGroupSeparator = value; } } public int CurrencyPositivePattern { get { return currencyPositivePattern; } set { if (value < 0 || value > 3) { throw new ArgumentOutOfRangeException( nameof(CurrencyPositivePattern), String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Range"), 0, 3)); } Contract.EndContractBlock(); VerifyWritable(); currencyPositivePattern = value; } } public String PositiveInfinitySymbol { get { return positiveInfinitySymbol; } set { if (value == null) { throw new ArgumentNullException(nameof(PositiveInfinitySymbol), Environment.GetResourceString("ArgumentNull_String")); } Contract.EndContractBlock(); VerifyWritable(); positiveInfinitySymbol = value; } } public String PositiveSign { get { return positiveSign; } set { if (value == null) { throw new ArgumentNullException(nameof(PositiveSign), Environment.GetResourceString("ArgumentNull_String")); } Contract.EndContractBlock(); VerifyWritable(); positiveSign = value; } } public int PercentDecimalDigits { get { return percentDecimalDigits; } set { if (value < 0 || value > 99) { throw new ArgumentOutOfRangeException( nameof(PercentDecimalDigits), String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Range"), 0, 99)); } Contract.EndContractBlock(); VerifyWritable(); percentDecimalDigits = value; } } public String PercentDecimalSeparator { get { return percentDecimalSeparator; } set { VerifyWritable(); VerifyDecimalSeparator(value, nameof(PercentDecimalSeparator)); percentDecimalSeparator = value; } } public String PercentGroupSeparator { get { return percentGroupSeparator; } set { VerifyWritable(); VerifyGroupSeparator(value, nameof(PercentGroupSeparator)); percentGroupSeparator = value; } } public String PercentSymbol { get { return percentSymbol; } set { if (value == null) { throw new ArgumentNullException(nameof(PercentSymbol), Environment.GetResourceString("ArgumentNull_String")); } Contract.EndContractBlock(); VerifyWritable(); percentSymbol = value; } } public String PerMilleSymbol { get { return perMilleSymbol; } set { if (value == null) { throw new ArgumentNullException(nameof(PerMilleSymbol), Environment.GetResourceString("ArgumentNull_String")); } Contract.EndContractBlock(); VerifyWritable(); perMilleSymbol = value; } } [System.Runtime.InteropServices.ComVisible(false)] public String[] NativeDigits { get { return (String[])nativeDigits.Clone(); } set { VerifyWritable(); VerifyNativeDigits(value, nameof(NativeDigits)); nativeDigits = value; } } [System.Runtime.InteropServices.ComVisible(false)] public DigitShapes DigitSubstitution { get { return (DigitShapes)digitSubstitution; } set { VerifyWritable(); VerifyDigitSubstitution(value, nameof(DigitSubstitution)); digitSubstitution = (int)value; } } public Object GetFormat(Type formatType) { return formatType == typeof(NumberFormatInfo)? this: null; } public static NumberFormatInfo ReadOnly(NumberFormatInfo nfi) { if (nfi == null) { throw new ArgumentNullException(nameof(nfi)); } Contract.EndContractBlock(); if (nfi.IsReadOnly) { return (nfi); } NumberFormatInfo info = (NumberFormatInfo)(nfi.MemberwiseClone()); info.isReadOnly = true; return info; } // private const NumberStyles InvalidNumberStyles = unchecked((NumberStyles) 0xFFFFFC00); private const NumberStyles InvalidNumberStyles = ~(NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite | NumberStyles.AllowLeadingSign | NumberStyles.AllowTrailingSign | NumberStyles.AllowParentheses | NumberStyles.AllowDecimalPoint | NumberStyles.AllowThousands | NumberStyles.AllowExponent | NumberStyles.AllowCurrencySymbol | NumberStyles.AllowHexSpecifier); internal static void ValidateParseStyleInteger(NumberStyles style) { // Check for undefined flags if ((style & InvalidNumberStyles) != 0) { throw new ArgumentException(Environment.GetResourceString("Argument_InvalidNumberStyles"), nameof(style)); } Contract.EndContractBlock(); if ((style & NumberStyles.AllowHexSpecifier) != 0) { // Check for hex number if ((style & ~NumberStyles.HexNumber) != 0) { throw new ArgumentException(Environment.GetResourceString("Arg_InvalidHexStyle")); } } } internal static void ValidateParseStyleFloatingPoint(NumberStyles style) { // Check for undefined flags if ((style & InvalidNumberStyles) != 0) { throw new ArgumentException(Environment.GetResourceString("Argument_InvalidNumberStyles"), nameof(style)); } Contract.EndContractBlock(); if ((style & NumberStyles.AllowHexSpecifier) != 0) { // Check for hex number throw new ArgumentException(Environment.GetResourceString("Arg_HexStyleNotSupported")); } } } // NumberFormatInfo }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void ShiftRightLogical128BitLaneUInt161() { var test = new SimpleUnaryOpTest__ShiftRightLogical128BitLaneUInt161(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local works test.RunLclFldScenario(); // Validates passing an instance member works test.RunFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleUnaryOpTest__ShiftRightLogical128BitLaneUInt161 { private const int VectorSize = 16; private const int Op1ElementCount = VectorSize / sizeof(UInt16); private const int RetElementCount = VectorSize / sizeof(UInt16); private static UInt16[] _data = new UInt16[Op1ElementCount]; private static Vector128<UInt16> _clsVar; private Vector128<UInt16> _fld; private SimpleUnaryOpTest__DataTable<UInt16, UInt16> _dataTable; static SimpleUnaryOpTest__ShiftRightLogical128BitLaneUInt161() { var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (ushort)8; } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref _clsVar), ref Unsafe.As<UInt16, byte>(ref _data[0]), VectorSize); } public SimpleUnaryOpTest__ShiftRightLogical128BitLaneUInt161() { Succeeded = true; var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (ushort)8; } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref _fld), ref Unsafe.As<UInt16, byte>(ref _data[0]), VectorSize); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (ushort)8; } _dataTable = new SimpleUnaryOpTest__DataTable<UInt16, UInt16>(_data, new UInt16[RetElementCount], VectorSize); } public bool IsSupported => Sse2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { var result = Sse2.ShiftRightLogical128BitLane( Unsafe.Read<Vector128<UInt16>>(_dataTable.inArrayPtr), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { var result = Sse2.ShiftRightLogical128BitLane( Sse2.LoadVector128((UInt16*)(_dataTable.inArrayPtr)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { var result = Sse2.ShiftRightLogical128BitLane( Sse2.LoadAlignedVector128((UInt16*)(_dataTable.inArrayPtr)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { var result = typeof(Sse2).GetMethod(nameof(Sse2.ShiftRightLogical128BitLane), new Type[] { typeof(Vector128<UInt16>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<UInt16>>(_dataTable.inArrayPtr), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt16>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { var result = typeof(Sse2).GetMethod(nameof(Sse2.ShiftRightLogical128BitLane), new Type[] { typeof(Vector128<UInt16>), typeof(byte) }) .Invoke(null, new object[] { Sse2.LoadVector128((UInt16*)(_dataTable.inArrayPtr)), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt16>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { var result = typeof(Sse2).GetMethod(nameof(Sse2.ShiftRightLogical128BitLane), new Type[] { typeof(Vector128<UInt16>), typeof(byte) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((UInt16*)(_dataTable.inArrayPtr)), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt16>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { var result = Sse2.ShiftRightLogical128BitLane( _clsVar, 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { var firstOp = Unsafe.Read<Vector128<UInt16>>(_dataTable.inArrayPtr); var result = Sse2.ShiftRightLogical128BitLane(firstOp, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { var firstOp = Sse2.LoadVector128((UInt16*)(_dataTable.inArrayPtr)); var result = Sse2.ShiftRightLogical128BitLane(firstOp, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { var firstOp = Sse2.LoadAlignedVector128((UInt16*)(_dataTable.inArrayPtr)); var result = Sse2.ShiftRightLogical128BitLane(firstOp, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclFldScenario() { var test = new SimpleUnaryOpTest__ShiftRightLogical128BitLaneUInt161(); var result = Sse2.ShiftRightLogical128BitLane(test._fld, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunFldScenario() { var result = Sse2.ShiftRightLogical128BitLane(_fld, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld, _dataTable.outArrayPtr); } public void RunUnsupportedScenario() { Succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector128<UInt16> firstOp, void* result, [CallerMemberName] string method = "") { UInt16[] inArray = new UInt16[Op1ElementCount]; UInt16[] outArray = new UInt16[RetElementCount]; Unsafe.Write(Unsafe.AsPointer(ref inArray[0]), firstOp); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray, outArray, method); } private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "") { UInt16[] inArray = new UInt16[Op1ElementCount]; UInt16[] outArray = new UInt16[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray, outArray, method); } private void ValidateResult(UInt16[] firstOp, UInt16[] result, [CallerMemberName] string method = "") { if (result[0] != 2048) { Succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if ((i == 7 ? result[i] != 0 : result[i] != 2048)) { Succeeded = false; break; } } } if (!Succeeded) { Console.WriteLine($"{nameof(Sse2)}.{nameof(Sse2.ShiftRightLogical128BitLane)}<UInt16>(Vector128<UInt16><9>): {method} failed:"); Console.WriteLine($" firstOp: ({string.Join(", ", firstOp)})"); Console.WriteLine($" result: ({string.Join(", ", result)})"); Console.WriteLine(); } } } }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #region Using directives using System; using System.Collections.Generic; using System.Globalization; using System.Management.Automation; using Microsoft.PowerShell.Commands; #endregion namespace Microsoft.Management.Infrastructure.CimCmdlets { /// <summary> /// Enables the user to subscribe to indications using Filter Expression or /// Query Expression. /// -SourceIdentifier is a name given to the subscription /// The Cmdlet should return a PS EventSubscription object that can be used to /// cancel the subscription /// Should we have the second parameter set with a -Query? /// </summary> [Alias("rcie")] [Cmdlet(VerbsLifecycle.Register, "CimIndicationEvent", DefaultParameterSetName = CimBaseCommand.ClassNameComputerSet, HelpUri = "https://go.microsoft.com/fwlink/?LinkId=227960")] public class RegisterCimIndicationCommand : ObjectEventRegistrationBase { #region parameters /// <summary> /// <para> /// The following is the definition of the input parameter "Namespace". /// Specifies the NameSpace under which to look for the specified class name. /// </para> /// <para> /// Default value is root\cimv2 /// </para> /// </summary> [Parameter] public string Namespace { get; set; } /// <summary> /// The following is the definition of the input parameter "ClassName". /// Specifies the Class Name to register the indication on. /// </summary> [Parameter( Mandatory = true, Position = 0, ParameterSetName = CimBaseCommand.ClassNameSessionSet)] [Parameter(Mandatory = true, Position = 0, ParameterSetName = CimBaseCommand.ClassNameComputerSet)] public string ClassName { get { return className; } set { className = value; this.SetParameter(value, nameClassName); } } private string className; /// <summary> /// The following is the definition of the input parameter "Query". /// The Query Expression to pass. /// </summary> [Parameter( Mandatory = true, Position = 0, ParameterSetName = CimBaseCommand.QueryExpressionSessionSet)] [Parameter( Mandatory = true, Position = 0, ParameterSetName = CimBaseCommand.QueryExpressionComputerSet)] public string Query { get { return query; } set { query = value; this.SetParameter(value, nameQuery); } } private string query; /// <summary> /// <para> /// The following is the definition of the input parameter "QueryDialect". /// Specifies the dialect used by the query Engine that interprets the Query /// string. /// </para> /// </summary> [Parameter(ParameterSetName = CimBaseCommand.QueryExpressionComputerSet)] [Parameter(ParameterSetName = CimBaseCommand.QueryExpressionSessionSet)] public string QueryDialect { get { return queryDialect; } set { queryDialect = value; this.SetParameter(value, nameQueryDialect); } } private string queryDialect; /// <summary> /// The following is the definition of the input parameter "OperationTimeoutSec". /// Enables the user to specify the operation timeout in Seconds. This value /// overwrites the value specified by the CimSession Operation timeout. /// </summary> [Alias(CimBaseCommand.AliasOT)] [Parameter] public uint OperationTimeoutSec { get; set; } /// <summary> /// The following is the definition of the input parameter "Session". /// Uses a CimSession context. /// </summary> [Parameter( Mandatory = true, ParameterSetName = CimBaseCommand.QueryExpressionSessionSet)] [Parameter( Mandatory = true, ParameterSetName = CimBaseCommand.ClassNameSessionSet)] public CimSession CimSession { get { return cimSession; } set { cimSession = value; this.SetParameter(value, nameCimSession); } } private CimSession cimSession; /// <summary> /// The following is the definition of the input parameter "ComputerName". /// Specifies the computer on which the commands associated with this session /// will run. The default value is LocalHost. /// </summary> [Alias(CimBaseCommand.AliasCN, CimBaseCommand.AliasServerName)] [Parameter(ParameterSetName = CimBaseCommand.QueryExpressionComputerSet)] [Parameter(ParameterSetName = CimBaseCommand.ClassNameComputerSet)] public string ComputerName { get { return computername; } set { computername = value; this.SetParameter(value, nameComputerName); } } private string computername; #endregion /// <summary> /// Returns the object that generates events to be monitored. /// </summary> protected override object GetSourceObject() { CimIndicationWatcher watcher = null; string parameterSetName = null; try { parameterSetName = this.parameterBinder.GetParameterSet(); } finally { this.parameterBinder.reset(); } string tempQueryExpression = string.Empty; switch (parameterSetName) { case CimBaseCommand.QueryExpressionSessionSet: case CimBaseCommand.QueryExpressionComputerSet: tempQueryExpression = this.Query; break; case CimBaseCommand.ClassNameSessionSet: case CimBaseCommand.ClassNameComputerSet: // validate the classname this.CheckArgument(); tempQueryExpression = string.Format(CultureInfo.CurrentCulture, "Select * from {0}", this.ClassName); break; } switch (parameterSetName) { case CimBaseCommand.QueryExpressionSessionSet: case CimBaseCommand.ClassNameSessionSet: { watcher = new CimIndicationWatcher(this.CimSession, this.Namespace, this.QueryDialect, tempQueryExpression, this.OperationTimeoutSec); } break; case CimBaseCommand.QueryExpressionComputerSet: case CimBaseCommand.ClassNameComputerSet: { watcher = new CimIndicationWatcher(this.ComputerName, this.Namespace, this.QueryDialect, tempQueryExpression, this.OperationTimeoutSec); } break; } if (watcher != null) { watcher.SetCmdlet(this); } return watcher; } /// <summary> /// Returns the event name to be monitored on the input object. /// </summary> protected override string GetSourceObjectEventName() { return "CimIndicationArrived"; } /// <summary> /// EndProcessing method. /// </summary> protected override void EndProcessing() { DebugHelper.WriteLogEx(); base.EndProcessing(); // Register for the "Unsubscribed" event so that we can stop the // Cimindication event watcher. PSEventSubscriber newSubscriber = NewSubscriber; if (newSubscriber != null) { DebugHelper.WriteLog("RegisterCimIndicationCommand::EndProcessing subscribe to Unsubscribed event", 4); newSubscriber.Unsubscribed += newSubscriber_Unsubscribed; } } /// <summary> /// <para> /// Handler to handle unsubscribe event /// </para> /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private static void newSubscriber_Unsubscribed( object sender, PSEventUnsubscribedEventArgs e) { DebugHelper.WriteLogEx(); CimIndicationWatcher watcher = sender as CimIndicationWatcher; if (watcher != null) { watcher.Stop(); } } #region private members /// <summary> /// Check argument value. /// </summary> private void CheckArgument() { this.className = ValidationHelper.ValidateArgumentIsValidName(nameClassName, this.className); } /// <summary> /// Parameter binder used to resolve parameter set name. /// </summary> private readonly ParameterBinder parameterBinder = new( parameters, parameterSets); /// <summary> /// Set the parameter. /// </summary> /// <param name="parameterName"></param> private void SetParameter(object value, string parameterName) { if (value == null) { return; } this.parameterBinder.SetParameter(parameterName, true); } #region const string of parameter names internal const string nameClassName = "ClassName"; internal const string nameQuery = "Query"; internal const string nameQueryDialect = "QueryDialect"; internal const string nameCimSession = "CimSession"; internal const string nameComputerName = "ComputerName"; #endregion /// <summary> /// Static parameter definition entries. /// </summary> private static readonly Dictionary<string, HashSet<ParameterDefinitionEntry>> parameters = new() { { nameClassName, new HashSet<ParameterDefinitionEntry> { new ParameterDefinitionEntry(CimBaseCommand.ClassNameSessionSet, true), new ParameterDefinitionEntry(CimBaseCommand.ClassNameComputerSet, true), } }, { nameQuery, new HashSet<ParameterDefinitionEntry> { new ParameterDefinitionEntry(CimBaseCommand.QueryExpressionSessionSet, true), new ParameterDefinitionEntry(CimBaseCommand.QueryExpressionComputerSet, true), } }, { nameQueryDialect, new HashSet<ParameterDefinitionEntry> { new ParameterDefinitionEntry(CimBaseCommand.QueryExpressionSessionSet, false), new ParameterDefinitionEntry(CimBaseCommand.QueryExpressionComputerSet, false), } }, { nameCimSession, new HashSet<ParameterDefinitionEntry> { new ParameterDefinitionEntry(CimBaseCommand.QueryExpressionSessionSet, true), new ParameterDefinitionEntry(CimBaseCommand.ClassNameSessionSet, true), } }, { nameComputerName, new HashSet<ParameterDefinitionEntry> { new ParameterDefinitionEntry(CimBaseCommand.QueryExpressionComputerSet, false), new ParameterDefinitionEntry(CimBaseCommand.ClassNameComputerSet, false), } }, }; /// <summary> /// Static parameter set entries. /// </summary> private static readonly Dictionary<string, ParameterSetEntry> parameterSets = new() { { CimBaseCommand.QueryExpressionSessionSet, new ParameterSetEntry(2) }, { CimBaseCommand.QueryExpressionComputerSet, new ParameterSetEntry(1) }, { CimBaseCommand.ClassNameSessionSet, new ParameterSetEntry(2) }, { CimBaseCommand.ClassNameComputerSet, new ParameterSetEntry(1, true) }, }; #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 Xunit; namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclassregmeth.genclassregmeth { using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclassregmeth.genclassregmeth; using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass001.genclass001; using System; using System.Collections.Generic; public class C { } public interface I { } public class MyClass { public int Field = 0; } public struct MyStruct { public int Number; } public enum MyEnum { First = 1, Second = 2, Third = 3 } public class MemberClass<T> { #region Instance methods public bool Method_ReturnBool() { return false; } public T Method_ReturnsT() { return default(T); } public T Method_ReturnsT(T t) { return t; } public T Method_ReturnsT(out T t) { t = default(T); return t; } public T Method_ReturnsT(ref T t, T tt) { t = default(T); return t; } public T Method_ReturnsT(params T[] t) { return default(T); } public T Method_ReturnsT(float x, T t) { return default(T); } public int Method_ReturnsInt(T t) { return 1; } public float Method_ReturnsFloat(T t, dynamic d) { return 3.4f; } public float Method_ReturnsFloat(T t, dynamic d, ref decimal dec) { dec = 3m; return 3.4f; } public dynamic Method_ReturnsDynamic(T t) { return t; } public dynamic Method_ReturnsDynamic(T t, dynamic d) { return t; } public dynamic Method_ReturnsDynamic(T t, int x, dynamic d) { return t; } // Multiple params // Constraints // Nesting #endregion #region Static methods public static bool? StaticMethod_ReturnBoolNullable() { return (bool?)false; } #endregion } public class MemberClassMultipleParams<T, U, V> { public T Method_ReturnsT(V v, U u) { return default(T); } } public class MemberClassWithClassConstraint<T> where T : class { public int Method_ReturnsInt() { return 1; } public T Method_ReturnsT(decimal dec, dynamic d) { return null; } } public class MemberClassWithNewConstraint<T> where T : new() { public T Method_ReturnsT() { return new T(); } public dynamic Method_ReturnsDynamic(T t) { return new T(); } } public class MemberClassWithAnotherTypeConstraint<T, U> where T : U { public U Method_ReturnsU(dynamic d) { return default(U); } public dynamic Method_ReturnsDynamic(int x, U u, dynamic d) { return default(T); } } #region Negative tests - you should not be able to construct this with a dynamic object public class MemberClassWithUDClassConstraint<T> where T : C, new() { public C Method_ReturnsC() { return new T(); } } public class MemberClassWithStructConstraint<T> where T : struct { public dynamic Method_ReturnsDynamic(int x) { return x; } } public class MemberClassWithInterfaceConstraint<T> where T : I { public dynamic Method_ReturnsDynamic(int x, T v) { return default(T); } } #endregion } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass001.genclass001 { using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclassregmeth.genclassregmeth; using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass001.genclass001; // <Title> Tests generic class regular method used in regular method body.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System; public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { Test t = new Test(); if (t.TestMethod() == true) return 1; return 0; } public bool TestMethod() { dynamic mc = new MemberClass<string>(); return (bool)mc.Method_ReturnBool(); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass002.genclass002 { using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclassregmeth.genclassregmeth; using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass002.genclass002; // <Title> Tests generic class regular method used in argements of method invocation.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System; public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { Test t = new Test(); dynamic mc1 = new MemberClass<int>(); int result1 = t.TestMethod((int)mc1.Method_ReturnsT()); dynamic mc2 = new MemberClass<string>(); int result2 = Test.TestMethod((string)mc2.Method_ReturnsT()); if (result1 == 0 && result2 == 0) return 0; else return 1; } public int TestMethod(int i) { if (i == default(int)) { return 0; } else { return 1; } } public static int TestMethod(string s) { if (s == default(string)) { return 0; } else { return 1; } } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass003.genclass003 { using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclassregmeth.genclassregmeth; using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass003.genclass003; // <Title> Tests generic class regular method used in static variable.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System; public class Test { private static dynamic s_mc = new MemberClass<string>(); private static float s_loc = (float)s_mc.Method_ReturnsFloat(null, 1); [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { if (s_loc != 3.4f) return 1; return 0; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass005.genclass005 { using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclassregmeth.genclassregmeth; using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass005.genclass005; // <Title> Tests generic class regular method used in unsafe.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> //using System; //[TestClass]public class Test //{ //[Test][Priority(Priority.Priority1)]public void DynamicCSharpRunTest(){Assert.AreEqual(0, MainMethod());} public static unsafe int MainMethod() //{ //dynamic dy = new MemberClass<int>(); //int value = 1; //int* valuePtr = &value; //int result = dy.Method_ReturnsT(out *valuePtr); //if (result == 0 && value == 0) //return 0; //return 1; //} //} //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass006.genclass006 { using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclassregmeth.genclassregmeth; using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass006.genclass006; // <Title> Tests generic class regular method used in generic method body.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System; public class Test { public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { Test t = new Test(); string s1 = ""; string s2 = ""; string result = t.TestMethod<string>(ref s1, s2); if (result == null && s1 == null) return 0; return 1; } public T TestMethod<T>(ref T t1, T t2) { dynamic mc = new MemberClass<T>(); return (T)mc.Method_ReturnsT(ref t1, t2); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass008.genclass008 { using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclassregmeth.genclassregmeth; using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass008.genclass008; // <Title> Tests generic class regular method used in extension method body.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System; public class Test { public int Field = 10; [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { Test t = 1.ExReturnTest(); if (t.Field == 1) return 0; return 1; } } static public class Extension { public static Test ExReturnTest(this int t) { dynamic dy = new MemberClass<int>(); float x = 3.3f; int i = -1; return new Test() { Field = t + (int)dy.Method_ReturnsT(x, i) } ; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass009.genclass009 { using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclassregmeth.genclassregmeth; using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass009.genclass009; // <Title> Tests generic class regular method used in for loop.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System; public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic dy = new MemberClass<MyEnum>(); int result = 0; for (int i = (int)dy.Method_ReturnsInt(MyEnum.Third); i < 10; i++) { result += (int)dy.Method_ReturnsInt((MyEnum)(i % 3 + 1)); } if (result == 9) return 0; return 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass009a.genclass009a { using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclassregmeth.genclassregmeth; using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass009a.genclass009a; // <Title> Tests generic class regular method used in for loop.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System; public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic dy = new MemberClass<MyEnum>(); int result = 0; for (int i = dy.Method_ReturnsInt(MyEnum.Third); i < 10; i++) { result += dy.Method_ReturnsInt((MyEnum)(i % 3 + 1)); } if (result == 9) return 0; return 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass010.genclass010 { using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclassregmeth.genclassregmeth; using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass010.genclass010; // <Title> Tests generic class regular method used in static constructor.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System; public class Test : I { private static decimal s_dec = 0M; private static float s_result = 0f; static Test() { dynamic dy = new MemberClass<I>(); s_result = (float)dy.Method_ReturnsFloat(new Test(), dy, ref s_dec); } public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { if (Test.s_dec == 3M && Test.s_result == 3.4f) return 0; return 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass012.genclass012 { using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclassregmeth.genclassregmeth; using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass012.genclass012; // <Title> Tests generic class regular method used in lambda.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System; using System.Collections.Generic; public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic dy = new MemberClass<string>(); dynamic d1 = 3; dynamic d2 = "Test"; Func<string, string, string> fun = (x, y) => (y + x.ToString()); string result = fun((string)dy.Method_ReturnsDynamic("foo", d1), (string)dy.Method_ReturnsDynamic("bar", d2)); if (result == "barfoo") return 0; return 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass013.genclass013 { using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclassregmeth.genclassregmeth; using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass013.genclass013; // <Title> Tests generic class regular method used in array initializer list.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System; using System.Collections.Generic; public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic dy = new MemberClass<string>(); string[] array = new string[] { (string)dy.Method_ReturnsDynamic(string.Empty, 1, dy), (string)dy.Method_ReturnsDynamic(null, 0, dy), (string)dy.Method_ReturnsDynamic("a", -1, dy)} ; if (array.Length == 3 && array[0] == string.Empty && array[1] == null && array[2] == "a") return 0; return 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass014.genclass014 { using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclassregmeth.genclassregmeth; using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass014.genclass014; // <Title> Tests generic class regular method used in null coalescing operator.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System; using System.Collections.Generic; public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic dy = MemberClass<string>.StaticMethod_ReturnBoolNullable(); if (!((bool?)dy ?? false)) return 0; return 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass015.genclass015 { using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclassregmeth.genclassregmeth; using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass015.genclass015; // <Title> Tests generic class regular method used in static method body.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System; using System.Collections.Generic; public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic dy = new MemberClassMultipleParams<MyEnum, MyStruct, MyClass>(); MyEnum me = dy.Method_ReturnsT(null, new MyStruct()); return (int)me; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass016.genclass016 { using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclassregmeth.genclassregmeth; using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass016.genclass016; // <Title> Tests generic class regular method used in query expression.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System; using System.Linq; using System.Collections.Generic; public class Test { private class M { public int Field1; public int Field2; } [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic dy = new MemberClassWithClassConstraint<MyClass>(); var list = new List<M>() { new M() { Field1 = 1, Field2 = 2 } , new M() { Field1 = 2, Field2 = 1 } } ; return list.Any(p => p.Field1 == (int)dy.Method_ReturnsInt()) ? 0 : 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass017.genclass017 { using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclassregmeth.genclassregmeth; using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass017.genclass017; // <Title> Tests generic class regular method used in ternary operator expression.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System; using System.Linq; using System.Collections.Generic; public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic dy = new MemberClassWithClassConstraint<string>(); string result = (string)dy.Method_ReturnsT(decimal.MaxValue, dy) == null ? string.Empty : (string)dy.Method_ReturnsT(decimal.MaxValue, dy); return result == string.Empty ? 0 : 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass018.genclass018 { using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclassregmeth.genclassregmeth; using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass018.genclass018; // <Title> Tests generic class regular method used in lock expression.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System; using System.Linq; using System.Collections.Generic; public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic dy = new MemberClassWithNewConstraint<C>(); int result = 1; lock (dy.Method_ReturnsT()) { result = 0; } return result; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass019.genclass019 { using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclassregmeth.genclassregmeth; using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass019.genclass019; // <Title> Tests generic class regular method used in switch section statement list.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System; using System.Linq; using System.Collections.Generic; public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic dy1 = new MemberClassWithNewConstraint<C>(); dynamic dy2 = new MemberClassWithAnotherTypeConstraint<int, int>(); C result = new C(); int result2 = -1; switch ((int)dy2.Method_ReturnsU(dy1)) // 0 { case 0: result = (C)dy1.Method_ReturnsDynamic(result); // called break; default: result2 = (int)dy2.Method_ReturnsDynamic(0, 0, dy2); // not called break; } return (result.GetType() == typeof(C) && result2 == -1) ? 0 : 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.implicit01.implicit01 { using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.implicit01.implicit01; // <Title> Tests generic class regular method used in regular method body.</Title> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System; using System.Collections.Generic; public class Ta { public static int i = 2; } public class A<T> { public static implicit operator A<List<string>>(A<T> x) { return new A<List<string>>(); } } public class B { public static void Foo<T>(A<List<T>> x, string y) { Ta.i--; } public static void Foo<T>(object x, string y) { Ta.i++; } [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { var x = new A<Action<object>>(); Foo<string>(x, ""); Foo<string>(x, (dynamic)""); return Ta.i; } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Reflection; using System.Text; using log4net; namespace OpenSim.Framework.Monitoring { /// <summary> /// Static class used to register/deregister checks on runtime conditions. /// </summary> public static class ChecksManager { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); // Subcommand used to list other stats. public const string ListSubCommand = "list"; // All subcommands public static HashSet<string> SubCommands = new HashSet<string> { ListSubCommand }; /// <summary> /// Checks categorized by category/container/shortname /// </summary> /// <remarks> /// Do not add or remove directly from this dictionary. /// </remarks> private static SortedDictionary<string, SortedDictionary<string, SortedDictionary<string, Check>>> RegisteredChecks = new SortedDictionary<string, SortedDictionary<string, SortedDictionary<string, Check>>>(); private static ReaderWriterLock RegisteredChecksRwLock = new ReaderWriterLock(); public static void RegisterConsoleCommands(ICommandConsole console) { console.Commands.AddCommand( "General", false, "show checks", "show checks", "Show checks configured for this server", "If no argument is specified then info on all checks will be shown.\n" + "'list' argument will show check categories.\n" + "THIS FACILITY IS EXPERIMENTAL", HandleShowchecksCommand); } public static void HandleShowchecksCommand(string module, string[] cmd) { ICommandConsole con = MainConsole.Instance; if (cmd.Length > 2) { foreach (string name in cmd.Skip(2)) { string[] components = name.Split('.'); string categoryName = components[0]; // string containerName = components.Length > 1 ? components[1] : null; if (categoryName == ListSubCommand) { con.Output("check categories available are:"); foreach (string category in RegisteredChecks.Keys) con.OutputFormat(" {0}", category); } // else // { // SortedDictionary<string, SortedDictionary<string, Check>> category; // if (!Registeredchecks.TryGetValue(categoryName, out category)) // { // con.OutputFormat("No such category as {0}", categoryName); // } // else // { // if (String.IsNullOrEmpty(containerName)) // { // OutputConfiguredToConsole(con, category); // } // else // { // SortedDictionary<string, Check> container; // if (category.TryGetValue(containerName, out container)) // { // OutputContainerChecksToConsole(con, container); // } // else // { // con.OutputFormat("No such container {0} in category {1}", containerName, categoryName); // } // } // } // } } } else { OutputAllChecksToConsole(con); } } /// <summary> /// Registers a statistic. /// </summary> /// <param name='stat'></param> /// <returns></returns> public static bool RegisterCheck(Check check) { SortedDictionary<string, SortedDictionary<string, Check>> category = null, newCategory; SortedDictionary<string, Check> container = null, newContainer; RegisteredChecksRwLock.AcquireWriterLock(-1); try { // Check name is not unique across category/container/shortname key. // XXX: For now just return false. This is to avoid problems in regression tests where all tests // in a class are run in the same instance of the VM. if (TryGetCheckParents(check, out category, out container)) return false; // We take a copy-on-write approach here of replacing dictionaries when keys are added or removed. // This means that we don't need to lock or copy them on iteration, which will be a much more // common operation after startup. if (container != null) newContainer = new SortedDictionary<string, Check>(container); else newContainer = new SortedDictionary<string, Check>(); if (category != null) newCategory = new SortedDictionary<string, SortedDictionary<string, Check>>(category); else newCategory = new SortedDictionary<string, SortedDictionary<string, Check>>(); newContainer[check.ShortName] = check; newCategory[check.Container] = newContainer; RegisteredChecks[check.Category] = newCategory; } finally { RegisteredChecksRwLock.ReleaseWriterLock(); } return true; } /// <summary> /// Deregister an check /// </summary>> /// <param name='stat'></param> /// <returns></returns> public static bool DeregisterCheck(Check check) { SortedDictionary<string, SortedDictionary<string, Check>> category = null, newCategory; SortedDictionary<string, Check> container = null, newContainer; RegisteredChecksRwLock.AcquireWriterLock(-1); try { if (!TryGetCheckParents(check, out category, out container)) return false; newContainer = new SortedDictionary<string, Check>(container); newContainer.Remove(check.ShortName); newCategory = new SortedDictionary<string, SortedDictionary<string, Check>>(category); newCategory.Remove(check.Container); newCategory[check.Container] = newContainer; RegisteredChecks[check.Category] = newCategory; return true; } finally { RegisteredChecksRwLock.ReleaseWriterLock(); } } public static bool TryGetCheckParents( Check check, out SortedDictionary<string, SortedDictionary<string, Check>> category, out SortedDictionary<string, Check> container) { category = null; container = null; RegisteredChecksRwLock.AcquireReaderLock(-1); try { if (RegisteredChecks.TryGetValue(check.Category, out category)) { if (category.TryGetValue(check.Container, out container)) { if (container.ContainsKey(check.ShortName)) return true; } } } finally { RegisteredChecksRwLock.ReleaseReaderLock(); } return false; } public static void CheckChecks() { RegisteredChecksRwLock.AcquireReaderLock(-1); try { foreach (SortedDictionary<string, SortedDictionary<string, Check>> category in RegisteredChecks.Values) { foreach (SortedDictionary<string, Check> container in category.Values) { foreach (Check check in container.Values) { if (!check.CheckIt()) m_log.WarnFormat( "[CHECKS MANAGER]: Check {0}.{1}.{2} failed with message {3}", check.Category, check.Container, check.ShortName, check.LastFailureMessage); } } } } finally { RegisteredChecksRwLock.ReleaseReaderLock(); } } private static void OutputAllChecksToConsole(ICommandConsole con) { RegisteredChecksRwLock.AcquireReaderLock(-1); try { foreach (var category in RegisteredChecks.Values) { OutputCategoryChecksToConsole(con, category); } } finally { RegisteredChecksRwLock.ReleaseReaderLock(); } } private static void OutputCategoryChecksToConsole( ICommandConsole con, SortedDictionary<string, SortedDictionary<string, Check>> category) { foreach (var container in category.Values) { OutputContainerChecksToConsole(con, container); } } private static void OutputContainerChecksToConsole(ICommandConsole con, SortedDictionary<string, Check> container) { foreach (Check check in container.Values) { con.Output(check.ToConsoleString()); } } } }
//------------------------------------------------------------------------------ // <copyright file="SqlTransaction.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // <owner current="true" primary="true">[....]</owner> // <owner current="true" primary="false">[....]</owner> //------------------------------------------------------------------------------ namespace System.Data.SqlClient { using System.Data; using System.Data.Common; using System.Data.ProviderBase; using System.Data.Sql; using System.Data.SqlTypes; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Runtime.ConstrainedExecution; using System.Threading; public sealed class SqlTransaction : DbTransaction { private static int _objectTypeCount; // Bid counter internal readonly int _objectID = System.Threading.Interlocked.Increment(ref _objectTypeCount); internal readonly IsolationLevel _isolationLevel = IsolationLevel.ReadCommitted; private SqlInternalTransaction _internalTransaction; private SqlConnection _connection; private bool _isFromAPI; internal SqlTransaction(SqlInternalConnection internalConnection, SqlConnection con, IsolationLevel iso, SqlInternalTransaction internalTransaction) { SqlConnection.VerifyExecutePermission(); _isolationLevel = iso; _connection = con; if (internalTransaction == null) { _internalTransaction = new SqlInternalTransaction(internalConnection, TransactionType.LocalFromAPI, this); } else { Debug.Assert(internalConnection.CurrentTransaction == internalTransaction, "Unexpected Parser.CurrentTransaction state!"); _internalTransaction = internalTransaction; _internalTransaction.InitParent(this); } } //////////////////////////////////////////////////////////////////////////////////////// // PROPERTIES //////////////////////////////////////////////////////////////////////////////////////// new public SqlConnection Connection { // MDAC 66655 get { if (IsZombied) { return null; } else { return _connection; } } } override protected DbConnection DbConnection { get { return Connection; } } internal SqlInternalTransaction InternalTransaction { get { return _internalTransaction; } } override public IsolationLevel IsolationLevel { get { ZombieCheck(); return _isolationLevel; } } private bool IsYukonPartialZombie { get { return (null != _internalTransaction && _internalTransaction.IsCompleted); } } internal bool IsZombied { get { return (null == _internalTransaction || _internalTransaction.IsCompleted); } } internal int ObjectID { get { return _objectID; } } internal SqlStatistics Statistics { get { if (null != _connection) { if (_connection.StatisticsEnabled) { return _connection.Statistics; } } return null; } } //////////////////////////////////////////////////////////////////////////////////////// // PUBLIC METHODS //////////////////////////////////////////////////////////////////////////////////////// override public void Commit() { SqlConnection.ExecutePermission.Demand(); // MDAC 81476 ZombieCheck(); SqlStatistics statistics = null; IntPtr hscp; Bid.ScopeEnter(out hscp, "<sc.SqlTransaction.Commit|API> %d#", ObjectID); Bid.CorrelationTrace("<sc.SqlTransaction.Commit|API|Correlation> ObjectID%d#, ActivityID %ls", ObjectID); TdsParser bestEffortCleanupTarget = null; RuntimeHelpers.PrepareConstrainedRegions(); try { #if DEBUG TdsParser.ReliabilitySection tdsReliabilitySection = new TdsParser.ReliabilitySection(); RuntimeHelpers.PrepareConstrainedRegions(); try { tdsReliabilitySection.Start(); #else { #endif //DEBUG bestEffortCleanupTarget = SqlInternalConnection.GetBestEffortCleanupTarget(_connection); statistics = SqlStatistics.StartTimer(Statistics); _isFromAPI = true; _internalTransaction.Commit(); } #if DEBUG finally { tdsReliabilitySection.Stop(); } #endif //DEBUG } catch (System.OutOfMemoryException e) { _connection.Abort(e); throw; } catch (System.StackOverflowException e) { _connection.Abort(e); throw; } catch (System.Threading.ThreadAbortException e) { _connection.Abort(e); SqlInternalConnection.BestEffortCleanup(bestEffortCleanupTarget); throw; } finally { _isFromAPI = false; SqlStatistics.StopTimer(statistics); Bid.ScopeLeave(ref hscp); } } protected override void Dispose(bool disposing) { if (disposing) { TdsParser bestEffortCleanupTarget = null; RuntimeHelpers.PrepareConstrainedRegions(); try { #if DEBUG TdsParser.ReliabilitySection tdsReliabilitySection = new TdsParser.ReliabilitySection(); RuntimeHelpers.PrepareConstrainedRegions(); try { tdsReliabilitySection.Start(); #else { #endif //DEBUG bestEffortCleanupTarget = SqlInternalConnection.GetBestEffortCleanupTarget(_connection); if (!IsZombied && !IsYukonPartialZombie) { _internalTransaction.Dispose(); } } #if DEBUG finally { tdsReliabilitySection.Stop(); } #endif //DEBUG } catch (System.OutOfMemoryException e) { _connection.Abort(e); throw; } catch (System.StackOverflowException e) { _connection.Abort(e); throw; } catch (System.Threading.ThreadAbortException e) { _connection.Abort(e); SqlInternalConnection.BestEffortCleanup(bestEffortCleanupTarget); throw; } } base.Dispose(disposing); } override public void Rollback() { if (IsYukonPartialZombie) { // Put something in the trace in case a customer has an issue if (Bid.AdvancedOn) { Bid.Trace("<sc.SqlTransaction.Rollback|ADV> %d# partial zombie no rollback required\n", ObjectID); } _internalTransaction = null; // yukon zombification } else { ZombieCheck(); SqlStatistics statistics = null; IntPtr hscp; Bid.ScopeEnter(out hscp, "<sc.SqlTransaction.Rollback|API> %d#", ObjectID); Bid.CorrelationTrace("<sc.SqlTransaction.Rollback|API|Correlation> ObjectID%d#, ActivityID %ls\n", ObjectID); TdsParser bestEffortCleanupTarget = null; RuntimeHelpers.PrepareConstrainedRegions(); try { #if DEBUG TdsParser.ReliabilitySection tdsReliabilitySection = new TdsParser.ReliabilitySection(); RuntimeHelpers.PrepareConstrainedRegions(); try { tdsReliabilitySection.Start(); #else { #endif //DEBUG bestEffortCleanupTarget = SqlInternalConnection.GetBestEffortCleanupTarget(_connection); statistics = SqlStatistics.StartTimer(Statistics); _isFromAPI = true; _internalTransaction.Rollback(); } #if DEBUG finally { tdsReliabilitySection.Stop(); } #endif //DEBUG } catch (System.OutOfMemoryException e) { _connection.Abort(e); throw; } catch (System.StackOverflowException e) { _connection.Abort(e); throw; } catch (System.Threading.ThreadAbortException e) { _connection.Abort(e); SqlInternalConnection.BestEffortCleanup(bestEffortCleanupTarget); throw; } finally { _isFromAPI = false; SqlStatistics.StopTimer(statistics); Bid.ScopeLeave(ref hscp); } } } public void Rollback(string transactionName) { SqlConnection.ExecutePermission.Demand(); // MDAC 81476 ZombieCheck(); SqlStatistics statistics = null; IntPtr hscp; Bid.ScopeEnter(out hscp, "<sc.SqlTransaction.Rollback|API> %d# transactionName='%ls'", ObjectID, transactionName); TdsParser bestEffortCleanupTarget = null; RuntimeHelpers.PrepareConstrainedRegions(); try { #if DEBUG TdsParser.ReliabilitySection tdsReliabilitySection = new TdsParser.ReliabilitySection(); RuntimeHelpers.PrepareConstrainedRegions(); try { tdsReliabilitySection.Start(); #else { #endif //DEBUG bestEffortCleanupTarget = SqlInternalConnection.GetBestEffortCleanupTarget(_connection); statistics = SqlStatistics.StartTimer(Statistics); _isFromAPI = true; _internalTransaction.Rollback(transactionName); } #if DEBUG finally { tdsReliabilitySection.Stop(); } #endif //DEBUG } catch (System.OutOfMemoryException e) { _connection.Abort(e); throw; } catch (System.StackOverflowException e) { _connection.Abort(e); throw; } catch (System.Threading.ThreadAbortException e) { _connection.Abort(e); SqlInternalConnection.BestEffortCleanup(bestEffortCleanupTarget); throw; } finally { _isFromAPI = false; SqlStatistics.StopTimer(statistics); Bid.ScopeLeave(ref hscp); } } public void Save(string savePointName) { SqlConnection.ExecutePermission.Demand(); // MDAC 81476 ZombieCheck(); SqlStatistics statistics = null; IntPtr hscp; Bid.ScopeEnter(out hscp, "<sc.SqlTransaction.Save|API> %d# savePointName='%ls'", ObjectID, savePointName); TdsParser bestEffortCleanupTarget = null; RuntimeHelpers.PrepareConstrainedRegions(); try { #if DEBUG TdsParser.ReliabilitySection tdsReliabilitySection = new TdsParser.ReliabilitySection(); RuntimeHelpers.PrepareConstrainedRegions(); try { tdsReliabilitySection.Start(); #else { #endif //DEBUG bestEffortCleanupTarget = SqlInternalConnection.GetBestEffortCleanupTarget(_connection); statistics = SqlStatistics.StartTimer(Statistics); _internalTransaction.Save(savePointName); } #if DEBUG finally { tdsReliabilitySection.Stop(); } #endif //DEBUG } catch (System.OutOfMemoryException e) { _connection.Abort(e); throw; } catch (System.StackOverflowException e) { _connection.Abort(e); throw; } catch (System.Threading.ThreadAbortException e) { _connection.Abort(e); SqlInternalConnection.BestEffortCleanup(bestEffortCleanupTarget); throw; } finally { SqlStatistics.StopTimer(statistics); Bid.ScopeLeave(ref hscp); } } //////////////////////////////////////////////////////////////////////////////////////// // INTERNAL METHODS //////////////////////////////////////////////////////////////////////////////////////// internal void Zombie() { // SQLBUDT #402544 For Yukon, we have to defer "zombification" until // we get past the users' next rollback, else we'll // throw an exception there that is a breaking change. // Of course, if the connection is aready closed, // then we're free to zombify... SqlInternalConnection internalConnection = (_connection.InnerConnection as SqlInternalConnection); if (null != internalConnection && internalConnection.IsYukonOrNewer && !_isFromAPI) { if (Bid.AdvancedOn) { Bid.Trace("<sc.SqlTransaction.Zombie|ADV> %d# yukon deferred zombie\n", ObjectID); } } else { _internalTransaction = null; // pre-yukon zombification } } //////////////////////////////////////////////////////////////////////////////////////// // PRIVATE METHODS //////////////////////////////////////////////////////////////////////////////////////// private void ZombieCheck() { // If this transaction has been completed, throw exception since it is unusable. if (IsZombied) { if (IsYukonPartialZombie) { _internalTransaction = null; // yukon zombification } throw ADP.TransactionZombied(this); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; public class ArrayIndexOf4 { private const int c_MIN_SIZE = 64; private const int c_MAX_SIZE = 1024; private const int c_MIN_STRLEN = 1; private const int c_MAX_STRLEN = 1024; public static int Main() { ArrayIndexOf4 ac = new ArrayIndexOf4(); TestLibrary.TestFramework.BeginTestCase("Array.IndexOf(T[] array, T value)"); if (ac.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; retVal = PosTest4() && retVal; retVal = PosTest5() && retVal; retVal = PosTest6() && retVal; retVal = PosTest7() && retVal; retVal = PosTest8() && retVal; retVal = PosTest9() && retVal; retVal = PosTest10() && retVal; retVal = PosTest11() && retVal; TestLibrary.TestFramework.LogInformation(""); TestLibrary.TestFramework.LogInformation("[Negative]"); retVal = NegTest1() && retVal; retVal = NegTest2() && retVal; retVal = NegTest3() && retVal; retVal = NegTest4() && retVal; retVal = NegTest5() && retVal; retVal = NegTest6() && retVal; retVal = NegTest7() && retVal; retVal = NegTest8() && retVal; retVal = NegTest9() && retVal; retVal = NegTest10() && retVal; return retVal; } public bool PosTest1() { return PosIndexOf<Int64>(1, TestLibrary.Generator.GetInt64(-55), TestLibrary.Generator.GetInt64(-55)); } public bool PosTest2() { return PosIndexOf<Int32>(2, TestLibrary.Generator.GetInt32(-55), TestLibrary.Generator.GetInt32(-55)); } public bool PosTest3() { return PosIndexOf<Int16>(3, TestLibrary.Generator.GetInt16(-55), TestLibrary.Generator.GetInt16(-55)); } public bool PosTest4() { return PosIndexOf<Byte>(4, TestLibrary.Generator.GetByte(-55), TestLibrary.Generator.GetByte(-55)); } public bool PosTest5() { return PosIndexOf<double>(5, TestLibrary.Generator.GetDouble(-55), TestLibrary.Generator.GetDouble(-55)); } public bool PosTest6() { return PosIndexOf<float>(6, TestLibrary.Generator.GetSingle(-55), TestLibrary.Generator.GetSingle(-55)); } public bool PosTest7() { return PosIndexOf<char>(7, TestLibrary.Generator.GetCharLetter(-55), TestLibrary.Generator.GetCharLetter(-55)); } public bool PosTest8() { return PosIndexOf<char>(8, TestLibrary.Generator.GetCharNumber(-55), TestLibrary.Generator.GetCharNumber(-55)); } public bool PosTest9() { return PosIndexOf<char>(9, TestLibrary.Generator.GetChar(-55), TestLibrary.Generator.GetChar(-55)); } public bool PosTest10() { return PosIndexOf<string>(10, TestLibrary.Generator.GetString(-55, false, c_MIN_STRLEN, c_MAX_STRLEN), TestLibrary.Generator.GetString(-55, false, c_MIN_STRLEN, c_MAX_STRLEN)); } public bool PosTest11() { return PosIndexOf2<Int32>(11, 1, 0, 0, 0); } public bool NegTest1() { return NegIndexOf<Int32>(1, 1); } // id, defaultValue, length, startIndex, count public bool NegTest2() { return NegIndexOf2<Int32>( 2, 1, 0, 1, 0); } public bool NegTest3() { return NegIndexOf2<Int32>( 3, 1, 0, -2, 0); } public bool NegTest4() { return NegIndexOf2<Int32>( 4, 1, 0, -1, 1); } public bool NegTest5() { return NegIndexOf2<Int32>( 5, 1, 0, 0, 1); } public bool NegTest6() { return NegIndexOf2<Int32>( 6, 1, 1, -1, 1); } public bool NegTest7() { return NegIndexOf2<Int32>( 7, 1, 1, 2, 1); } public bool NegTest8() { return NegIndexOf2<Int32>( 8, 1, 1, 0, -1); } public bool NegTest9() { return NegIndexOf2<Int32>( 9, 1, 1, 0, -1); } public bool NegTest10() { return NegIndexOf2<Int32>(10, 1, 1, 1, 2); } public bool PosIndexOf<T>(int id, T element, T otherElem) { bool retVal = true; T[] array; int length; int index; int newIndex; TestLibrary.TestFramework.BeginScenario("PosTest"+id+": Array.IndexOf(T[] array, T value, int startIndex, int count) (T=="+typeof(T)+") where value is found"); try { // creat the array length = (TestLibrary.Generator.GetInt32(-55) % (c_MAX_SIZE-c_MIN_SIZE)) + c_MIN_SIZE; array = new T[length]; // fill the array for (int i=0; i<array.Length; i++) { array[i] = otherElem; } // set the lucky index index = TestLibrary.Generator.GetInt32(-55) % length; // set the value array.SetValue( element, index); newIndex = Array.IndexOf<T>(array, element, 0, array.Length); if (index < newIndex) { TestLibrary.TestFramework.LogError("000", "Unexpected index: Expected(" + index + ") Actual(" + newIndex + ")"); retVal = false; } if (!element.Equals(array[newIndex])) { TestLibrary.TestFramework.LogError("001", "Unexpected value: Expected(" + element + ") Actual(" + array[newIndex] + ")"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosIndexOf2<T>(int id, T defaultValue, int length, int startIndex, int count) { bool retVal = true; T[] array = null; int newIndex; TestLibrary.TestFramework.BeginScenario("PosTest"+id+": Array.IndexOf(T["+length+"] array, T value, "+startIndex+", "+count+") (T == "+typeof(T)+" where array is null"); try { array = new T[ length ]; newIndex = Array.IndexOf<T>(array, defaultValue, startIndex, count); if (-1 != newIndex) { TestLibrary.TestFramework.LogError("003", "Unexpected value: Expected(-1) Actual("+newIndex+")"); retVal = false; } } catch (ArgumentOutOfRangeException) { // expected } catch (Exception e) { TestLibrary.TestFramework.LogError("004", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool NegIndexOf<T>(int id, T defaultValue) { bool retVal = true; T[] array = null; TestLibrary.TestFramework.BeginScenario("NegTest"+id+": Array.IndexOf(T[] array, T value, int startIndex, int count) (T == "+typeof(T)+" where array is null"); try { Array.IndexOf<T>(array, defaultValue, 0, 0); TestLibrary.TestFramework.LogError("005", "Exepction should have been thrown"); retVal = false; } catch (ArgumentNullException) { // expected } catch (Exception e) { TestLibrary.TestFramework.LogError("006", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool NegIndexOf2<T>(int id, T defaultValue, int length, int startIndex, int count) { bool retVal = true; T[] array = null; TestLibrary.TestFramework.BeginScenario("NegTest"+id+": Array.IndexOf(T["+length+"] array, T value, "+startIndex+", "+count+") (T == "+typeof(T)+" where array is null"); try { array = new T[ length ]; Array.IndexOf<T>(array, defaultValue, startIndex, count); TestLibrary.TestFramework.LogError("007", "Exepction should have been thrown"); retVal = false; } catch (ArgumentOutOfRangeException) { // expected } catch (Exception e) { TestLibrary.TestFramework.LogError("008", "Unexpected exception: " + e); retVal = false; } return retVal; } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Text; using Microsoft.VisualStudio.TestTools.UnitTesting; using Pchp.Core; namespace Peachpie.Runtime.Tests { [TestClass] public class OrderedDictionaryTest { //static string ToString(OrderedDictionary array) => string.Join("", array.Select(entry => entry.Item2)); static string ToString(OrderedDictionary array) { var result = new StringBuilder(); foreach (var value in array) // uses FastEnumerator { Debug.Assert(value.Value.String != null); // only string values for the test result.Append(value.Value.String); } return result.ToString(); } [TestMethod] public void Test1() { var array = new OrderedDictionary(); Assert.AreEqual(0, array.Count); array.Add("Hello"); array.Add(" "); array.Add("World"); Assert.AreEqual(3, array.Count); Assert.AreEqual("Hello World", ToString(array)); Assert.AreEqual("Hello", array[0]); Assert.AreEqual("World", array[2]); array.Remove(1); Assert.AreEqual(2, array.Count); Assert.AreEqual("HelloWorld", ToString(array)); Assert.AreEqual("World", array[2]); array.Add("!"); Assert.AreEqual(3, array.Count); Assert.AreEqual("HelloWorld!", ToString(array)); Assert.AreEqual("!", array[3]); Assert.IsTrue(array.ContainsKey(0)); Assert.IsFalse(array.ContainsKey(1)); } [TestMethod] public void Test2() { var array = new OrderedDictionary(100000); const int count = 1000000; for (int i = count; i > 0; i--) { array[i] = i.ToString("x4"); } Assert.AreEqual(count, array.Count); int removed = 0; for (int i = 1; i < count; i += 3) { Assert.IsTrue(array.Remove(i)); removed++; } Assert.AreEqual(count - removed, array.Count); } [TestMethod] public void TestPacked() { var array = new OrderedDictionary(100000); Assert.IsTrue(array.IsPacked); const int count = 1000000; for (int i = 0; i < count; i++) { array[i] = i.ToString("x4"); } Assert.IsTrue(array.IsPacked); Assert.AreEqual(count, array.Count); for (int i = count - 1; i >= 0; i--) { Assert.IsTrue(array.Remove(i)); Assert.IsTrue(array.IsPacked); } Assert.AreEqual(0, array.Count); Assert.AreEqual("", ToString(array)); // enumeration of empty array works for (int i = 0; i < count; i++) { array[i] = i.ToString("x4"); } Assert.IsTrue(array.IsPacked); array.Add("last"); Assert.IsTrue(array.IsPacked); Assert.AreEqual(count + 1, array.Count); Assert.IsTrue(array.ContainsKey(count)); Assert.AreEqual("last", array[count]); } [TestMethod] public void TestShuffle() { // create array and check shuffle var array = new OrderedDictionary(); const int count = 123; for (int i = 0; i < count; i++) { array.Add(i.ToString("x4")); } array.Remove(44); array.Remove(45); array.Remove(46); array.Remove(0); array.Shuffle(new Random()); var set = new HashSet<long>(); foreach (var pair in array) { Assert.IsTrue(set.Add(pair.Key.Integer)); } Assert.AreEqual(array.Count, set.Count); } [TestMethod] public void TestReverse() { var array = new OrderedDictionary(); const int count = 11; for (int i = 0; i < count; i++) { array.Add(i.ToString("x4")); } // reverse reverse -> must result in the same array as before var before = ToString(array); array.Reverse(); array.Reverse(); Assert.AreEqual(before, ToString(array)); // expected count Assert.AreEqual(count, array.Count); // remove items and reverse array with holes: Assert.IsTrue(array.Remove(3)); Assert.IsTrue(array.Remove(4)); Assert.IsTrue(array.Remove(7)); array.Reverse(); var last = new KeyValuePair<IntStringKey, PhpValue>(int.MaxValue, default); foreach (var pair in array) { Assert.IsTrue(last.Key.Integer > pair.Key.Integer); Assert.AreEqual(pair.Value.String, pair.Key.Integer.ToString("x4")); last = pair; } } class KeyComparer : IComparer<KeyValuePair<IntStringKey, PhpValue>> { public int Compare(KeyValuePair<IntStringKey, PhpValue> x, KeyValuePair<IntStringKey, PhpValue> y) { return x.Key.Integer.CompareTo(y.Key.Integer); } } class ValueComparer : IComparer<KeyValuePair<IntStringKey, PhpValue>> { public int Compare(KeyValuePair<IntStringKey, PhpValue> x, KeyValuePair<IntStringKey, PhpValue> y) { return StringComparer.OrdinalIgnoreCase.Compare(x.Value.String, y.Value.String); } } [TestMethod] public void TestSort() { var array = new OrderedDictionary(); const int count = 10; for (int i = count; i > 0; i--) { array[i] = i.ToString(); } // remove items and reverse array with holes: Assert.IsTrue(array.Remove(3)); Assert.IsTrue(array.Remove(4)); Assert.IsTrue(array.Remove(7)); array.Sort(new KeyComparer()); Assert.AreEqual(count - 3, array.Count); var last = new KeyValuePair<IntStringKey, PhpValue>(0, default); foreach (var pair in array) { Assert.IsTrue(last.Key.Integer < pair.Key.Integer); Assert.AreEqual(pair.Value.String, pair.Key.Integer.ToString()); last = pair; } } [TestMethod] public void TestDiff() { var array = new OrderedDictionary(); const int count = 100; for (int i = 0; i < count; i++) { array[i] = i.ToString(); } array.Shuffle(new Random()); var array2 = new OrderedDictionary(); array2.Add("3"); array2.Add("4"); array2.Add("7"); var diff = array.SetOperation(SetOperations.Difference, new[] { new PhpArray(array2) }, new ValueComparer()); Assert.AreEqual(array.Count - array2.Count, diff.Count); var diff_diff = array.SetOperation(SetOperations.Difference, new[] { new PhpArray(diff) }, new ValueComparer()); Assert.AreEqual(diff_diff.Count, array2.Count); } [TestMethod] public void TestPrepend() { var array = new OrderedDictionary(); array[0] = "0"; array[1] = "1"; array.AddFirst(-1, "-1"); array.AddFirst(-2, "-2"); Assert.AreEqual(4, array.Count); Assert.AreEqual("-2-101", ToString(array)); } } }
//------------------------------------------------------------------------------ // <copyright file="SingleStorage.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // <owner current="true" primary="true">[....]</owner> // <owner current="true" primary="false">[....]</owner> // <owner current="false" primary="false">[....]</owner> //------------------------------------------------------------------------------ namespace System.Data.Common { using System; using System.Xml; using System.Data.SqlTypes; using System.Collections; internal sealed class SingleStorage : DataStorage { private const Single defaultValue = 0.0f; private Single[] values; public SingleStorage(DataColumn column) : base(column, typeof(Single), defaultValue, StorageType.Single) { } override public Object Aggregate(int[] records, AggregateType kind) { bool hasData = false; try { switch (kind) { case AggregateType.Sum: Single sum = defaultValue; foreach (int record in records) { if (IsNull(record)) continue; checked { sum += values[record];} hasData = true; } if (hasData) { return sum; } return NullValue; case AggregateType.Mean: Double meanSum = (Double)defaultValue; int meanCount = 0; foreach (int record in records) { if (IsNull(record)) continue; checked { meanSum += (Double)values[record];} meanCount++; hasData = true; } if (hasData) { Single mean; checked {mean = (Single)(meanSum / meanCount);} return mean; } return NullValue; case AggregateType.Var: case AggregateType.StDev: int count = 0; double var = (double)defaultValue; double prec = (double)defaultValue; double dsum = (double)defaultValue; double sqrsum = (double)defaultValue; foreach (int record in records) { if (IsNull(record)) continue; dsum += (double)values[record]; sqrsum += (double)values[record]*(double)values[record]; count++; } if (count > 1) { var = ((double)count * sqrsum - (dsum * dsum)); prec = var / (dsum * dsum); // we are dealing with the risk of a cancellation error // double is guaranteed only for 15 digits so a difference // with a result less than 1e-15 should be considered as zero if ((prec < 1e-15) || (var <0)) var = 0; else var = var / (count * (count -1)); if (kind == AggregateType.StDev) { return Math.Sqrt(var); } return var; } return NullValue; case AggregateType.Min: Single min = Single.MaxValue; for (int i = 0; i < records.Length; i++) { int record = records[i]; if (IsNull(record)) continue; min=Math.Min(values[record], min); hasData = true; } if (hasData) { return min; } return NullValue; case AggregateType.Max: Single max = Single.MinValue; for (int i = 0; i < records.Length; i++) { int record = records[i]; if (IsNull(record)) continue; max=Math.Max(values[record], max); hasData = true; } if (hasData) { return max; } return NullValue; case AggregateType.First: if (records.Length > 0) { return values[records[0]]; } return null; case AggregateType.Count: return base.Aggregate(records, kind); } } catch (OverflowException) { throw ExprException.Overflow(typeof(Single)); } throw ExceptionBuilder.AggregateException(kind, DataType); } override public int Compare(int recordNo1, int recordNo2) { Single valueNo1 = values[recordNo1]; Single valueNo2 = values[recordNo2]; if (valueNo1 == defaultValue || valueNo2 == defaultValue) { int bitCheck = CompareBits(recordNo1, recordNo2); if (0 != bitCheck) return bitCheck; } return valueNo1.CompareTo(valueNo2); // not simple, checks Nan } public override int CompareValueTo(int recordNo, object value) { System.Diagnostics.Debug.Assert(0 <= recordNo, "Invalid record"); System.Diagnostics.Debug.Assert(null != value, "null value"); if (NullValue == value) { if (IsNull(recordNo)) { return 0; } return 1; } Single valueNo1 = values[recordNo]; if ((defaultValue == valueNo1) && IsNull(recordNo)) { return -1; } return valueNo1.CompareTo((Single)value); } public override object ConvertValue(object value) { if (NullValue != value) { if (null != value) { value = ((IConvertible)value).ToSingle(FormatProvider); } else { value = NullValue; } } return value; } override public void Copy(int recordNo1, int recordNo2) { CopyBits(recordNo1, recordNo2); values[recordNo2] = values[recordNo1]; } override public Object Get(int record) { Single value = values[record]; if (value != defaultValue) { return value; } return GetBits(record); } override public void Set(int record, Object value) { System.Diagnostics.Debug.Assert(null != value, "null value"); if (NullValue == value) { values[record] = defaultValue; SetNullBit(record, true); } else { values[record] = ((IConvertible)value).ToSingle(FormatProvider); SetNullBit(record, false); } } override public void SetCapacity(int capacity) { Single[] newValues = new Single[capacity]; if (null != values) { Array.Copy(values, 0, newValues, 0, Math.Min(capacity, values.Length)); } values = newValues; base.SetCapacity(capacity); } override public object ConvertXmlToObject(string s) { return XmlConvert.ToSingle(s); } override public string ConvertObjectToXml(object value) { return XmlConvert.ToString((Single)value); } override protected object GetEmptyStorage(int recordCount) { return new Single[recordCount]; } override protected void CopyValue(int record, object store, BitArray nullbits, int storeIndex) { Single[] typedStore = (Single[]) store; typedStore[storeIndex] = values[record]; nullbits.Set(storeIndex, IsNull(record)); } override protected void SetStorage(object store, BitArray nullbits) { values = (Single[]) store; SetNullStorage(nullbits); } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using System.Xml; using Hyak.Common; using Microsoft.Azure.Insights; using Microsoft.Azure.Insights.Models; using Newtonsoft.Json.Linq; namespace Microsoft.Azure.Insights { /// <summary> /// Operations for metric values. /// </summary> internal partial class MetricOperations : IServiceOperations<InsightsClient>, IMetricOperations { /// <summary> /// Initializes a new instance of the MetricOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal MetricOperations(InsightsClient client) { this._client = client; } private InsightsClient _client; /// <summary> /// Gets a reference to the Microsoft.Azure.Insights.InsightsClient. /// </summary> public InsightsClient Client { get { return this._client; } } /// <summary> /// The List Metric operation lists the metric value sets for the /// resource metrics. /// </summary> /// <param name='resourceUri'> /// Required. The resource identifier of the target resource to get /// metrics for. /// </param> /// <param name='filterString'> /// Optional. An OData $filter expression that supports querying by the /// name, startTime, endTime and timeGrain of the metric value sets. /// For example, "(name.value eq 'Percentage CPU') and startTime eq /// 2014-07-02T01:00Z and endTime eq 2014-08-21T01:00:00Z and /// timeGrain eq duration'PT1H'". In the expression, startTime, /// endTime and timeGrain are required. Name is optional. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The List Metric values operation response. /// </returns> public async Task<MetricListResponse> GetMetricsAsync(string resourceUri, string filterString, CancellationToken cancellationToken) { // Validate if (resourceUri == null) { throw new ArgumentNullException("resourceUri"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceUri", resourceUri); tracingParameters.Add("filterString", filterString); TracingAdapter.Enter(invocationId, this, "GetMetricsAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/"; url = url + Uri.EscapeDataString(resourceUri); url = url + "/metrics"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2014-04-01"); List<string> odataFilter = new List<string>(); if (filterString != null) { odataFilter.Add(Uri.EscapeDataString(filterString)); } if (odataFilter.Count > 0) { queryParameters.Add("$filter=" + string.Join(null, odataFilter)); } if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("Accept", "application/json"); httpRequest.Headers.Add("x-ms-version", "2014-04-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result MetricListResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new MetricListResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { MetricCollection metricCollectionInstance = new MetricCollection(); result.MetricCollection = metricCollectionInstance; JToken valueArray = responseDoc["value"]; if (valueArray != null && valueArray.Type != JTokenType.Null) { foreach (JToken valueValue in ((JArray)valueArray)) { Metric metricInstance = new Metric(); metricCollectionInstance.Value.Add(metricInstance); JToken nameValue = valueValue["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { LocalizableString nameInstance = new LocalizableString(); metricInstance.Name = nameInstance; JToken valueValue2 = nameValue["value"]; if (valueValue2 != null && valueValue2.Type != JTokenType.Null) { string valueInstance = ((string)valueValue2); nameInstance.Value = valueInstance; } JToken localizedValueValue = nameValue["localizedValue"]; if (localizedValueValue != null && localizedValueValue.Type != JTokenType.Null) { string localizedValueInstance = ((string)localizedValueValue); nameInstance.LocalizedValue = localizedValueInstance; } } JToken unitValue = valueValue["unit"]; if (unitValue != null && unitValue.Type != JTokenType.Null) { Unit unitInstance = ((Unit)Enum.Parse(typeof(Unit), ((string)unitValue), true)); metricInstance.Unit = unitInstance; } JToken timeGrainValue = valueValue["timeGrain"]; if (timeGrainValue != null && timeGrainValue.Type != JTokenType.Null) { TimeSpan timeGrainInstance = XmlConvert.ToTimeSpan(((string)timeGrainValue)); metricInstance.TimeGrain = timeGrainInstance; } JToken startTimeValue = valueValue["startTime"]; if (startTimeValue != null && startTimeValue.Type != JTokenType.Null) { DateTime startTimeInstance = ((DateTime)startTimeValue); metricInstance.StartTime = startTimeInstance; } JToken endTimeValue = valueValue["endTime"]; if (endTimeValue != null && endTimeValue.Type != JTokenType.Null) { DateTime endTimeInstance = ((DateTime)endTimeValue); metricInstance.EndTime = endTimeInstance; } JToken metricValuesArray = valueValue["metricValues"]; if (metricValuesArray != null && metricValuesArray.Type != JTokenType.Null) { foreach (JToken metricValuesValue in ((JArray)metricValuesArray)) { MetricValue metricValueInstance = new MetricValue(); metricInstance.MetricValues.Add(metricValueInstance); JToken timestampValue = metricValuesValue["timestamp"]; if (timestampValue != null && timestampValue.Type != JTokenType.Null) { DateTime timestampInstance = ((DateTime)timestampValue); metricValueInstance.Timestamp = timestampInstance; } JToken averageValue = metricValuesValue["average"]; if (averageValue != null && averageValue.Type != JTokenType.Null) { double averageInstance = ((double)averageValue); metricValueInstance.Average = averageInstance; } JToken minimumValue = metricValuesValue["minimum"]; if (minimumValue != null && minimumValue.Type != JTokenType.Null) { double minimumInstance = ((double)minimumValue); metricValueInstance.Minimum = minimumInstance; } JToken maximumValue = metricValuesValue["maximum"]; if (maximumValue != null && maximumValue.Type != JTokenType.Null) { double maximumInstance = ((double)maximumValue); metricValueInstance.Maximum = maximumInstance; } JToken totalValue = metricValuesValue["total"]; if (totalValue != null && totalValue.Type != JTokenType.Null) { double totalInstance = ((double)totalValue); metricValueInstance.Total = totalInstance; } JToken countValue = metricValuesValue["count"]; if (countValue != null && countValue.Type != JTokenType.Null) { long countInstance = ((long)countValue); metricValueInstance.Count = countInstance; } JToken lastValue = metricValuesValue["last"]; if (lastValue != null && lastValue.Type != JTokenType.Null) { double lastInstance = ((double)lastValue); metricValueInstance.Last = lastInstance; } JToken propertiesSequenceElement = ((JToken)metricValuesValue["properties"]); if (propertiesSequenceElement != null && propertiesSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in propertiesSequenceElement) { string propertiesKey = ((string)property.Name); string propertiesValue = ((string)property.Value); metricValueInstance.Properties.Add(propertiesKey, propertiesValue); } } } } JToken resourceIdValue = valueValue["resourceId"]; if (resourceIdValue != null && resourceIdValue.Type != JTokenType.Null) { string resourceIdInstance = ((string)resourceIdValue); metricInstance.ResourceId = resourceIdInstance; } JToken propertiesSequenceElement2 = ((JToken)valueValue["properties"]); if (propertiesSequenceElement2 != null && propertiesSequenceElement2.Type != JTokenType.Null) { foreach (JProperty property2 in propertiesSequenceElement2) { string propertiesKey2 = ((string)property2.Name); string propertiesValue2 = ((string)property2.Value); metricInstance.Properties.Add(propertiesKey2, propertiesValue2); } } JToken dimensionNameValue = valueValue["dimensionName"]; if (dimensionNameValue != null && dimensionNameValue.Type != JTokenType.Null) { LocalizableString dimensionNameInstance = new LocalizableString(); metricInstance.DimensionName = dimensionNameInstance; JToken valueValue3 = dimensionNameValue["value"]; if (valueValue3 != null && valueValue3.Type != JTokenType.Null) { string valueInstance2 = ((string)valueValue3); dimensionNameInstance.Value = valueInstance2; } JToken localizedValueValue2 = dimensionNameValue["localizedValue"]; if (localizedValueValue2 != null && localizedValueValue2.Type != JTokenType.Null) { string localizedValueInstance2 = ((string)localizedValueValue2); dimensionNameInstance.LocalizedValue = localizedValueInstance2; } } JToken dimensionValueValue = valueValue["dimensionValue"]; if (dimensionValueValue != null && dimensionValueValue.Type != JTokenType.Null) { LocalizableString dimensionValueInstance = new LocalizableString(); metricInstance.DimensionValue = dimensionValueInstance; JToken valueValue4 = dimensionValueValue["value"]; if (valueValue4 != null && valueValue4.Type != JTokenType.Null) { string valueInstance3 = ((string)valueValue4); dimensionValueInstance.Value = valueInstance3; } JToken localizedValueValue3 = dimensionValueValue["localizedValue"]; if (localizedValueValue3 != null && localizedValueValue3.Type != JTokenType.Null) { string localizedValueInstance3 = ((string)localizedValueValue3); dimensionValueInstance.LocalizedValue = localizedValueInstance3; } } } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } } }
/*++ File: FixedSOMContainer.cs Copyright (C) 2005 Microsoft Corporation. All rights reserved. Description: Abstract class that provides a common base class for all semantic containers History: 05/17/2005: agurcan - Created --*/ namespace System.Windows.Documents { using System.Collections.Generic; using System.Diagnostics; using System.Windows.Media; internal abstract class FixedSOMContainer :FixedSOMSemanticBox, IComparable { //-------------------------------------------------------------------- // // Constructors // //--------------------------------------------------------------------- #region Constructors protected FixedSOMContainer() { _semanticBoxes = new List<FixedSOMSemanticBox>(); } #endregion Constructors int IComparable.CompareTo(object comparedObj) { int result = Int32.MinValue; FixedSOMPageElement compared = comparedObj as FixedSOMPageElement; FixedSOMPageElement This = this as FixedSOMPageElement; Debug.Assert(compared != null); Debug.Assert(This != null); if (compared == null) { throw new ArgumentException(SR.Get(SRID.UnexpectedParameterType, comparedObj.GetType(), typeof(FixedSOMContainer)), "comparedObj"); } SpatialComparison compareHor = base._CompareHorizontal(compared, false); SpatialComparison compareVer = base._CompareVertical(compared); Debug.Assert(compareHor != SpatialComparison.None); Debug.Assert(compareVer != SpatialComparison.None); switch (compareHor) { case SpatialComparison.Before: if (compareVer != SpatialComparison.After) { result = -1; } break; case SpatialComparison.After: if (compareVer != SpatialComparison.Before) { result = 1; } break; case SpatialComparison.OverlapBefore: if (compareVer == SpatialComparison.Before) { result = -1; } else if (compareVer == SpatialComparison.After) { result = 1; } break; case SpatialComparison.OverlapAfter: if (compareVer == SpatialComparison.After) { result = 1; } else if (compareVer == SpatialComparison.Before) { result = -1; } break; case SpatialComparison.Equal: switch (compareVer) { case SpatialComparison.After: case SpatialComparison.OverlapAfter: result = 1; break; case SpatialComparison.Before: case SpatialComparison.OverlapBefore: result = -1; break; case SpatialComparison.Equal: result = 0; break; default: Debug.Assert(false); break; } break; default: //Shouldn't happen Debug.Assert(false); break; } if (result == Int32.MinValue) { //Indecisive. Does markup order help? if (This.FixedNodes.Count == 0 || compared.FixedNodes.Count == 0) { result = 0; } else { FixedNode thisObjFirstNode = This.FixedNodes[0]; FixedNode thisObjLastNode = This.FixedNodes[This.FixedNodes.Count - 1]; FixedNode otherObjFirstNode = compared.FixedNodes[0]; FixedNode otherObjLastNode = compared.FixedNodes[compared.FixedNodes.Count - 1]; if (This.FixedSOMPage.MarkupOrder.IndexOf(otherObjFirstNode) - This.FixedSOMPage.MarkupOrder.IndexOf(thisObjLastNode) == 1) { result = -1; } else if (This.FixedSOMPage.MarkupOrder.IndexOf(otherObjLastNode) - This.FixedSOMPage.MarkupOrder.IndexOf(thisObjFirstNode) == 1) { result = 1; } else { //Indecisive. Whichever is below comes after; if same whichever is on the right comes after int absVerComparison = _SpatialToAbsoluteComparison(compareVer); result = absVerComparison != 0 ? absVerComparison : _SpatialToAbsoluteComparison(compareHor); } } } return result; } #region Protected Methods protected void AddSorted(FixedSOMSemanticBox box) { int i=_semanticBoxes.Count-1; for (; i>=0; i--) { if (box.CompareTo(_semanticBoxes[i]) == 1) { break; } } _semanticBoxes.Insert(i+1, box); _UpdateBoundingRect(box.BoundingRect); } protected void Add(FixedSOMSemanticBox box) { _semanticBoxes.Add(box); _UpdateBoundingRect(box.BoundingRect); } #endregion #region public Properties internal virtual FixedElement.ElementType[] ElementTypes { get { return new FixedElement.ElementType[0]; } } public List<FixedSOMSemanticBox> SemanticBoxes { get { return _semanticBoxes; } set { _semanticBoxes = value; } } public List<FixedNode> FixedNodes { get { if (_fixedNodes == null) { _ConstructFixedNodes(); } return _fixedNodes; } } #endregion #region Private methods void _ConstructFixedNodes() { _fixedNodes = new List<FixedNode>(); foreach (FixedSOMSemanticBox box in _semanticBoxes) { FixedSOMElement element = box as FixedSOMElement; if (element != null) { _fixedNodes.Add(element.FixedNode); } else { FixedSOMContainer container = box as FixedSOMContainer; Debug.Assert(container != null); List<FixedNode> nodes = container.FixedNodes; foreach (FixedNode node in nodes) { _fixedNodes.Add(node); } } } } void _UpdateBoundingRect(Rect rect) { if (_boundingRect.IsEmpty) { _boundingRect = rect; } else { _boundingRect.Union(rect); } } #endregion Private methods //-------------------------------------------------------------------- // // Protected Fields // //--------------------------------------------------------------------- #region Protected Fields protected List<FixedSOMSemanticBox> _semanticBoxes; protected List<FixedNode> _fixedNodes; #endregion Protected Fields } }
using System.Linq; using System.Collections.Generic; using System.Diagnostics; using Content.Server.NodeContainer.EntitySystems; using Content.Server.Power.Components; using Content.Server.Power.NodeGroups; using Content.Server.Power.Pow3r; using JetBrains.Annotations; using Robust.Shared.GameObjects; using Robust.Shared.IoC; using Robust.Shared.Log; using Robust.Shared.Maths; namespace Content.Server.Power.EntitySystems { /// <summary> /// Manages power networks, power state, and all power components. /// </summary> [UsedImplicitly] public sealed class PowerNetSystem : EntitySystem { private readonly PowerState _powerState = new(); private readonly HashSet<PowerNet> _powerNetReconnectQueue = new(); private readonly HashSet<ApcNet> _apcNetReconnectQueue = new(); private readonly BatteryRampPegSolver _solver = new(); public override void Initialize() { base.Initialize(); UpdatesAfter.Add(typeof(NodeGroupSystem)); SubscribeLocalEvent<ApcPowerReceiverComponent, ComponentInit>(ApcPowerReceiverInit); SubscribeLocalEvent<ApcPowerReceiverComponent, ComponentShutdown>(ApcPowerReceiverShutdown); SubscribeLocalEvent<ApcPowerReceiverComponent, EntityPausedEvent>(ApcPowerReceiverPaused); SubscribeLocalEvent<PowerNetworkBatteryComponent, ComponentInit>(BatteryInit); SubscribeLocalEvent<PowerNetworkBatteryComponent, ComponentShutdown>(BatteryShutdown); SubscribeLocalEvent<PowerNetworkBatteryComponent, EntityPausedEvent>(BatteryPaused); SubscribeLocalEvent<PowerConsumerComponent, ComponentInit>(PowerConsumerInit); SubscribeLocalEvent<PowerConsumerComponent, ComponentShutdown>(PowerConsumerShutdown); SubscribeLocalEvent<PowerConsumerComponent, EntityPausedEvent>(PowerConsumerPaused); SubscribeLocalEvent<PowerSupplierComponent, ComponentInit>(PowerSupplierInit); SubscribeLocalEvent<PowerSupplierComponent, ComponentShutdown>(PowerSupplierShutdown); SubscribeLocalEvent<PowerSupplierComponent, EntityPausedEvent>(PowerSupplierPaused); } private void ApcPowerReceiverInit(EntityUid uid, ApcPowerReceiverComponent component, ComponentInit args) { AllocLoad(component.NetworkLoad); } private void ApcPowerReceiverShutdown(EntityUid uid, ApcPowerReceiverComponent component, ComponentShutdown args) { _powerState.Loads.Free(component.NetworkLoad.Id); } private static void ApcPowerReceiverPaused( EntityUid uid, ApcPowerReceiverComponent component, EntityPausedEvent args) { component.NetworkLoad.Paused = args.Paused; } private void BatteryInit(EntityUid uid, PowerNetworkBatteryComponent component, ComponentInit args) { AllocBattery(component.NetworkBattery); } private void BatteryShutdown(EntityUid uid, PowerNetworkBatteryComponent component, ComponentShutdown args) { _powerState.Batteries.Free(component.NetworkBattery.Id); } private static void BatteryPaused(EntityUid uid, PowerNetworkBatteryComponent component, EntityPausedEvent args) { component.NetworkBattery.Paused = args.Paused; } private void PowerConsumerInit(EntityUid uid, PowerConsumerComponent component, ComponentInit args) { AllocLoad(component.NetworkLoad); } private void PowerConsumerShutdown(EntityUid uid, PowerConsumerComponent component, ComponentShutdown args) { _powerState.Loads.Free(component.NetworkLoad.Id); } private static void PowerConsumerPaused(EntityUid uid, PowerConsumerComponent component, EntityPausedEvent args) { component.NetworkLoad.Paused = args.Paused; } private void PowerSupplierInit(EntityUid uid, PowerSupplierComponent component, ComponentInit args) { AllocSupply(component.NetworkSupply); } private void PowerSupplierShutdown(EntityUid uid, PowerSupplierComponent component, ComponentShutdown args) { _powerState.Supplies.Free(component.NetworkSupply.Id); } private static void PowerSupplierPaused(EntityUid uid, PowerSupplierComponent component, EntityPausedEvent args) { component.NetworkSupply.Paused = args.Paused; } public void InitPowerNet(PowerNet powerNet) { AllocNetwork(powerNet.NetworkNode); } public void DestroyPowerNet(PowerNet powerNet) { _powerState.Networks.Free(powerNet.NetworkNode.Id); } public void QueueReconnectPowerNet(PowerNet powerNet) { _powerNetReconnectQueue.Add(powerNet); } public void InitApcNet(ApcNet apcNet) { AllocNetwork(apcNet.NetworkNode); } public void DestroyApcNet(ApcNet apcNet) { _powerState.Networks.Free(apcNet.NetworkNode.Id); } public void QueueReconnectApcNet(ApcNet apcNet) { _apcNetReconnectQueue.Add(apcNet); } public PowerStatistics GetStatistics() { return new() { CountBatteries = _powerState.Batteries.Count, CountLoads = _powerState.Loads.Count, CountNetworks = _powerState.Networks.Count, CountSupplies = _powerState.Supplies.Count }; } public NetworkPowerStatistics GetNetworkStatistics(PowerState.Network network) { // Right, consumption. Now this is a big mess. // Start by summing up consumer draw rates. // Then deal with batteries. // While for consumers we want to use their max draw rates, // for batteries we ought to use their current draw rates, // because there's all sorts of weirdness with them. // A full battery will still have the same max draw rate, // but will likely have deliberately limited current draw rate. float consumptionW = network.Loads.Sum(s => _powerState.Loads[s].DesiredPower); consumptionW += network.BatteriesCharging.Sum(s => _powerState.Batteries[s].CurrentReceiving); // This is interesting because LastMaxSupplySum seems to match LastAvailableSupplySum for some reason. // I suspect it's accounting for current supply rather than theoretical supply. float maxSupplyW = network.Supplies.Sum(s => _powerState.Supplies[s].MaxSupply); // Battery stuff is more complex. // Without stealing PowerState, the most efficient way // to grab the necessary discharge data is from // PowerNetworkBatteryComponent (has Pow3r reference). float supplyBatteriesW = 0.0f; float storageCurrentJ = 0.0f; float storageMaxJ = 0.0f; foreach (var discharger in network.BatteriesDischarging) { var nb = _powerState.Batteries[discharger]; supplyBatteriesW += nb.CurrentSupply; storageCurrentJ += nb.CurrentStorage; storageMaxJ += nb.Capacity; maxSupplyW += nb.MaxSupply; } // And charging float outStorageCurrentJ = 0.0f; float outStorageMaxJ = 0.0f; foreach (var charger in network.BatteriesCharging) { var nb = _powerState.Batteries[charger]; outStorageCurrentJ += nb.CurrentStorage; outStorageMaxJ += nb.Capacity; } return new() { SupplyCurrent = network.LastMaxSupplySum, SupplyBatteries = supplyBatteriesW, SupplyTheoretical = maxSupplyW, Consumption = consumptionW, InStorageCurrent = storageCurrentJ, InStorageMax = storageMaxJ, OutStorageCurrent = outStorageCurrentJ, OutStorageMax = outStorageMaxJ }; } public override void Update(float frameTime) { base.Update(frameTime); // Reconnect networks. { foreach (var apcNet in _apcNetReconnectQueue) { if (apcNet.Removed) continue; DoReconnectApcNet(apcNet); } _apcNetReconnectQueue.Clear(); foreach (var powerNet in _powerNetReconnectQueue) { if (powerNet.Removed) continue; DoReconnectPowerNet(powerNet); } _powerNetReconnectQueue.Clear(); } // Synchronize batteries RaiseLocalEvent(new NetworkBatteryPreSync()); // Run power solver. _solver.Tick(frameTime, _powerState); // Synchronize batteries, the other way around. RaiseLocalEvent(new NetworkBatteryPostSync()); // Send events where necessary. { foreach (var apcReceiver in EntityManager.EntityQuery<ApcPowerReceiverComponent>()) { var recv = apcReceiver.NetworkLoad.ReceivingPower; ref var last = ref apcReceiver.LastPowerReceived; if (!MathHelper.CloseToPercent(recv, last)) { last = recv; apcReceiver.ApcPowerChanged(); } } foreach (var consumer in EntityManager.EntityQuery<PowerConsumerComponent>()) { var newRecv = consumer.NetworkLoad.ReceivingPower; ref var lastRecv = ref consumer.LastReceived; if (!MathHelper.CloseToPercent(lastRecv, newRecv)) { lastRecv = newRecv; var msg = new PowerConsumerReceivedChanged(newRecv, consumer.DrawRate); RaiseLocalEvent(consumer.Owner, msg); } } foreach (var powerNetBattery in EntityManager.EntityQuery<PowerNetworkBatteryComponent>()) { var lastSupply = powerNetBattery.LastSupply; var currentSupply = powerNetBattery.CurrentSupply; if (lastSupply == 0f && currentSupply != 0f) { RaiseLocalEvent(powerNetBattery.Owner, new PowerNetBatterySupplyEvent {Supply = true}); } else if (lastSupply > 0f && currentSupply == 0f) { RaiseLocalEvent(powerNetBattery.Owner, new PowerNetBatterySupplyEvent {Supply = false}); } powerNetBattery.LastSupply = currentSupply; } } } private void AllocLoad(PowerState.Load load) { _powerState.Loads.Allocate(out load.Id) = load; } private void AllocSupply(PowerState.Supply supply) { _powerState.Supplies.Allocate(out supply.Id) = supply; } private void AllocBattery(PowerState.Battery battery) { _powerState.Batteries.Allocate(out battery.Id) = battery; } private void AllocNetwork(PowerState.Network network) { _powerState.Networks.Allocate(out network.Id) = network; } private void DoReconnectApcNet(ApcNet net) { var netNode = net.NetworkNode; netNode.Loads.Clear(); netNode.BatteriesDischarging.Clear(); netNode.BatteriesCharging.Clear(); netNode.Supplies.Clear(); foreach (var provider in net.Providers) { foreach (var receiver in provider.LinkedReceivers) { netNode.Loads.Add(receiver.NetworkLoad.Id); receiver.NetworkLoad.LinkedNetwork = netNode.Id; } } foreach (var consumer in net.Consumers) { netNode.Loads.Add(consumer.NetworkLoad.Id); consumer.NetworkLoad.LinkedNetwork = netNode.Id; } foreach (var apc in net.Apcs) { var netBattery = EntityManager.GetComponent<PowerNetworkBatteryComponent>(apc.Owner); netNode.BatteriesDischarging.Add(netBattery.NetworkBattery.Id); netBattery.NetworkBattery.LinkedNetworkDischarging = netNode.Id; } } private void DoReconnectPowerNet(PowerNet net) { var netNode = net.NetworkNode; netNode.Loads.Clear(); netNode.Supplies.Clear(); netNode.BatteriesCharging.Clear(); netNode.BatteriesDischarging.Clear(); foreach (var consumer in net.Consumers) { netNode.Loads.Add(consumer.NetworkLoad.Id); consumer.NetworkLoad.LinkedNetwork = netNode.Id; } foreach (var supplier in net.Suppliers) { netNode.Supplies.Add(supplier.NetworkSupply.Id); supplier.NetworkSupply.LinkedNetwork = netNode.Id; } foreach (var charger in net.Chargers) { var battery = EntityManager.GetComponent<PowerNetworkBatteryComponent>(charger.Owner); netNode.BatteriesCharging.Add(battery.NetworkBattery.Id); battery.NetworkBattery.LinkedNetworkCharging = netNode.Id; } foreach (var discharger in net.Dischargers) { var battery = EntityManager.GetComponent<PowerNetworkBatteryComponent>(discharger.Owner); netNode.BatteriesDischarging.Add(battery.NetworkBattery.Id); battery.NetworkBattery.LinkedNetworkDischarging = netNode.Id; } } } /// <summary> /// Raised before power network simulation happens, to synchronize battery state from /// components like <see cref="BatteryComponent"/> into <see cref="PowerNetworkBatteryComponent"/>. /// </summary> public struct NetworkBatteryPreSync { } /// <summary> /// Raised after power network simulation happens, to synchronize battery charge changes from /// <see cref="PowerNetworkBatteryComponent"/> to components like <see cref="BatteryComponent"/>. /// </summary> public struct NetworkBatteryPostSync { } /// <summary> /// Raised when the amount of receiving power on a <see cref="PowerConsumerComponent"/> changes. /// </summary> public sealed class PowerConsumerReceivedChanged : EntityEventArgs { public float ReceivedPower { get; } public float DrawRate { get; } public PowerConsumerReceivedChanged(float receivedPower, float drawRate) { ReceivedPower = receivedPower; DrawRate = drawRate; } } /// <summary> /// Raised whenever a <see cref="PowerNetworkBatteryComponent"/> changes from / to 0 CurrentSupply. /// </summary> public sealed class PowerNetBatterySupplyEvent : EntityEventArgs { public bool Supply { get; init; } } public struct PowerStatistics { public int CountNetworks; public int CountLoads; public int CountSupplies; public int CountBatteries; } public struct NetworkPowerStatistics { public float SupplyCurrent; public float SupplyBatteries; public float SupplyTheoretical; public float Consumption; public float InStorageCurrent; public float InStorageMax; public float OutStorageCurrent; public float OutStorageMax; } }
namespace RelatedRecords { using System.ComponentModel; using System.Collections.ObjectModel; using System; using System.Runtime.CompilerServices; using Common; using System.Linq; using System.Windows; public enum eAutoFilter { Everything, TablesWithPrimaryKey, MatchingColumnNames } public enum eViewType { Datasets, Tables, Queries } [System.CodeDom.Compiler.GeneratedCodeAttribute("Xsd2Code", "3.4.0.32990")] [System.SerializableAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.XmlRootAttribute("Configuration", Namespace="", IsNullable=false)] public partial class CConfiguration: BaseModel { private ObservableCollection<CDatasource> datasourceField; private ObservableCollection<CDataset> datasetField; private string defaultDatasetField; private string defaultDatasourceField; public CConfiguration() { this.datasetField = new ObservableCollection<CDataset>(); this.datasourceField = new ObservableCollection<CDatasource>(); } [System.Xml.Serialization.XmlElementAttribute("Datasource")] public ObservableCollection<CDatasource> Datasource { get { return this.datasourceField; } set { this.datasourceField = value; } } [System.Xml.Serialization.XmlElementAttribute("Dataset")] public ObservableCollection<CDataset> Dataset { get { return this.datasetField; } set { this.datasetField = value; } } [System.Xml.Serialization.XmlAttributeAttribute()] public string defaultDataset { get { return this.defaultDatasetField; } set { this.defaultDatasetField = value; } } [System.Xml.Serialization.XmlAttributeAttribute()] public string defaultDatasource { get { return this.defaultDatasourceField; } set { this.defaultDatasourceField = value; } } public void Inflate() { foreach(var source in Datasource) { source.ConnectionString = source.ConnectionString.Inflated(); } } public void Deflate() { foreach (var source in Datasource) { source.ConnectionString = source.ConnectionString.Deflated(); } } } [System.CodeDom.Compiler.GeneratedCodeAttribute("Xsd2Code", "3.4.0.32990")] [System.SerializableAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.XmlRootAttribute(Namespace="", IsNullable=true)] public partial class CDatasource: BaseModel { private string connectionStringField; private string nameField; public string ConnectionString { get { return this.connectionStringField; } set { this.connectionStringField = value; } } [System.Xml.Serialization.XmlAttributeAttribute()] public string name { get { return this.nameField; } set { this.nameField = value; } } } [System.CodeDom.Compiler.GeneratedCodeAttribute("Xsd2Code", "3.4.0.32990")] [System.SerializableAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.XmlRootAttribute(Namespace="", IsNullable=true)] public partial class CRelationship: BaseModel { private string nameField; private string fromTableField; private string toTableField; private string fromColumnField; private string toColumnField; [System.Xml.Serialization.XmlAttributeAttribute()] public string name { get { return this.nameField; } set { this.nameField = value; } } [System.Xml.Serialization.XmlAttributeAttribute()] public string fromTable { get { return this.fromTableField; } set { this.fromTableField = value; } } [System.Xml.Serialization.XmlAttributeAttribute()] public string toTable { get { return this.toTableField; } set { this.toTableField = value; } } [System.Xml.Serialization.XmlAttributeAttribute()] public string fromColumn { get { return this.fromColumnField; } set { this.fromColumnField = value; } } [System.Xml.Serialization.XmlAttributeAttribute()] public string toColumn { get { return this.toColumnField; } set { this.toColumnField = value; } } public static string GetName(string sourceName, string targetName) { return string.Format("{0}->{1}", sourceName, targetName); } } [System.CodeDom.Compiler.GeneratedCodeAttribute("Xsd2Code", "3.4.0.32990")] [System.SerializableAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.XmlRootAttribute(Namespace="", IsNullable=true)] public partial class CColumn : BaseModel { private string nameField; private eDbType dbTypeField; private bool isPrimaryKeyField; private bool isForeignKeyField; private bool isNullableField; private string defaultValueField; private bool isIdentityField; [System.Xml.Serialization.XmlAttributeAttribute()] public string name { get { return this.nameField; } set { this.nameField = value; } } [System.Xml.Serialization.XmlAttributeAttribute()] public eDbType DbType { get { return this.dbTypeField; } set { this.dbTypeField = value; } } [System.Xml.Serialization.XmlAttributeAttribute()] public bool isPrimaryKey { get { return this.isPrimaryKeyField; } set { this.isPrimaryKeyField = value; } } [System.Xml.Serialization.XmlAttributeAttribute()] public bool isForeignKey { get { return this.isForeignKeyField; } set { this.isForeignKeyField = value; } } [System.Xml.Serialization.XmlAttributeAttribute()] public bool isNullable { get { return this.isNullableField; } set { this.isNullableField = value; } } [System.Xml.Serialization.XmlAttributeAttribute()] public string defaultValue { get { return this.defaultValueField; } set { this.defaultValueField = value; } } [System.Xml.Serialization.XmlAttributeAttribute()] public bool isIdentity { get { return this.isIdentityField; } set { this.isIdentityField = value; } } } [System.CodeDom.Compiler.GeneratedCodeAttribute("Xsd2Code", "3.4.0.32990")] [System.SerializableAttribute()] [System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)] public enum eDbType { /// <remarks/> bigint, binary, bit, @bool, @char, date, datetime, datetime2, datetimeoffset, @decimal, @float, geography, geometry, guid, hierarchyid, image, @int, @long, money, nchar, ntext, numeric, nvarchar, real, smalldatetime, smallint, smallmoney, sql_variant, @string, text, time, timestamp, tinyint, uniqueidentifier, varbinary, varchar, xml } [System.CodeDom.Compiler.GeneratedCodeAttribute("Xsd2Code", "3.4.0.32990")] [System.SerializableAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.XmlRootAttribute(Namespace="", IsNullable=true)] public partial class CTable: BaseModel { private ObservableCollection<CColumn> columnField; private ObservableCollection<CTable> childrenField; private string nameField; private bool isDefaultField; public CTable() { this.columnField = new ObservableCollection<CColumn>(); this.childrenField = new ObservableCollection<CTable>(); } [System.Xml.Serialization.XmlIgnore] public ObservableCollection<CTable> Children { get { return this.childrenField; } set { this.childrenField = value; } } [System.Xml.Serialization.XmlElementAttribute("Column")] public ObservableCollection<CColumn> Column { get { return this.columnField; } set { this.columnField = value; } } [System.Xml.Serialization.XmlAttributeAttribute()] public string name { get { return this.nameField; } set { this.nameField = value; } } [System.Xml.Serialization.XmlIgnore] public bool isDefault { get { return isDefaultField; } set { isDefaultField = value; OnPropertyChanged(); OnPropertyChanged("DefaultVisibility"); } } [System.Xml.Serialization.XmlIgnore] public Visibility DefaultVisibility { get { return isDefaultField ? Visibility.Visible : Visibility.Collapsed; } } } [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)] public partial class CQuery { private ObservableCollection<CParameter> parameterField; private string textField; private string nameField; private bool isStoreProcedureField; public CQuery() { this.parameterField = new ObservableCollection<CParameter>(); } [System.Xml.Serialization.XmlElementAttribute("Parameter")] public ObservableCollection<CParameter> Parameter { get { return this.parameterField; } set { this.parameterField = value; } } /// <remarks/> [System.Xml.Serialization.XmlTextAttribute()] public string Text { get { return this.textField; } set { this.textField = value; } } /// <remarks/> [System.Xml.Serialization.XmlAttributeAttribute()] public string name { get { return this.nameField; } set { this.nameField = value; } } /// <remarks/> [System.Xml.Serialization.XmlAttributeAttribute()] public bool isStoreProcedure { get { return this.isStoreProcedureField; } set { this.isStoreProcedureField = value; } } } /// <remarks/> [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)] public partial class CParameter { private string nameField; private eDbType typeField; private string defaultValueField; /// <remarks/> [System.Xml.Serialization.XmlAttributeAttribute()] public string name { get { return this.nameField; } set { this.nameField = value; } } /// <remarks/> [System.Xml.Serialization.XmlAttributeAttribute()] public eDbType type { get { return this.typeField; } set { this.typeField = value; } } /// <remarks/> [System.Xml.Serialization.XmlAttributeAttribute()] public string defaultValue { get { return this.defaultValueField; } set { this.defaultValueField = value; } } } [System.CodeDom.Compiler.GeneratedCodeAttribute("Xsd2Code", "3.4.0.32990")] [System.SerializableAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.XmlRootAttribute(Namespace="", IsNullable=true)] public partial class CDataset : BaseModel { private ObservableCollection<CTable> tableField; private ObservableCollection<CRelationship> relationshipField; private ObservableCollection<CQuery> queryField; private string nameField; private string dataSourceNameField; private string defaultTableField; private bool isDisabledField; private bool isSelectedField; private bool isDefaultField; public CDataset() { this.relationshipField = new ObservableCollection<CRelationship>(); this.tableField = new ObservableCollection<CTable>(); this.queryField = new ObservableCollection<CQuery>(); } [System.Xml.Serialization.XmlElementAttribute("Table")] public ObservableCollection<CTable> Table { get { return this.tableField; } set { this.tableField = value; } } [System.Xml.Serialization.XmlElementAttribute("Query")] public ObservableCollection<CQuery> Query { get { return this.queryField; } set { this.queryField = value; } } [System.Xml.Serialization.XmlElementAttribute("Relationship")] public ObservableCollection<CRelationship> Relationship { get { return this.relationshipField; } set { this.relationshipField = value; } } [System.Xml.Serialization.XmlAttributeAttribute()] public string name { get { return this.nameField; } set { this.nameField = value; OnPropertyChanged(); } } [System.Xml.Serialization.XmlAttributeAttribute()] public string dataSourceName { get { return this.dataSourceNameField; } set { this.dataSourceNameField = value; } } [System.Xml.Serialization.XmlAttributeAttribute()] public string defaultTable { get { return this.defaultTableField; } set { this.defaultTableField = value; } } [System.Xml.Serialization.XmlAttributeAttribute()] public bool isDisabled { get { return this.isDisabledField; } set { this.isDisabledField = value; } } [System.Xml.Serialization.XmlIgnore] public bool isSelected { get { return this.isSelectedField; } set { this.isSelectedField = value; OnPropertyChanged(); OnPropertyChanged("SelectedVisibility"); } } [System.Xml.Serialization.XmlIgnore] public Visibility SelectedVisibility { get { return isSelected ? Visibility.Visible : Visibility.Collapsed; } } [System.Xml.Serialization.XmlIgnore] public bool isDefault { get { return isDefaultField; } set { isDefaultField = value; OnPropertyChanged(); OnPropertyChanged("DefaultVisibility"); } } [System.Xml.Serialization.XmlIgnore] public Visibility DefaultVisibility { get { return isDefaultField ? Visibility.Visible : Visibility.Collapsed; } } } }
using System; using System.ComponentModel; using System.Drawing; using System.Threading; using System.Windows.Forms; using System.Windows.Forms.VisualStyles; using Palaso.Extensions; using Palaso.Progress; using Palaso.Reporting; namespace Palaso.UI.WindowsForms.Progress { /// <summary> /// A full-featured log ui control, which supports colored & styled text, user-controlled /// verbosity, error reporting, & copy to clipboard. Protects itself, thread-wise. /// Implements IProgress, so that processes can send /// text to it without knowing anything about UI. /// </summary> public partial class LogBox : UserControl, IProgress { public event EventHandler ReportErrorLinkClicked; private Action<IProgress> _getDiagnosticsMethod; private readonly ToolStripLabel _reportLink; private SynchronizationContext _synchronizationContext; public LogBox() { InitializeComponent(); _reportLink = new ToolStripLabel("Report this problem to the developers"); _reportLink.LinkColor = Color.Red; _reportLink.IsLink = true; _reportLink.Visible = false; menuStrip1.Items.Add(_reportLink); _reportLink.Click += delegate { if (!ReportError(_verboseBox.Text)) { try { if (!string.IsNullOrEmpty(_verboseBox.Text)) { Clipboard.SetText(_verboseBox.Text); MessageBox.Show( "Information on what happened has been copied to your clipboard. Please email it to the developers of the program you are using."); } } catch (Exception) { MessageBox.Show( "Unable to copy the message to the clipboard. You might need to restart the application or your computer"); } } if (ReportErrorLinkClicked != null) ReportErrorLinkClicked(this, EventArgs.Empty); }; _verboseBox.ForeColor = _box.ForeColor = SystemColors.WindowText; _verboseBox.BackColor = _box.BackColor = SystemColors.Window; menuStrip1.BackColor = Color.White; BackColor = VisualStyleInformation.TextControlBorder; _tableLayout.BackColor = SystemColors.Window; //On some machines (winXP?) we get in trouble if we don't make sure these boxes are visible before //they get invoked() to. It's not clear that the following actually works... in addition to this //effort, we also catch exceptions when in trying to invoke on them. _box.CreateControl(); _verboseBox.Visible = true; _verboseBox.CreateControl(); _verboseBox.Visible = false; SetFont(); _tableLayout.Size = new Size(ClientSize.Width - (_tableLayout.Left + 1), ClientSize.Height - (_tableLayout.Top + 1)); _box.Dock = DockStyle.Fill; _box.LinkClicked += _box_LinkClicked; _verboseBox.LinkClicked += _box_LinkClicked; _synchronizationContext = SynchronizationContext.Current; } void _box_LinkClicked(object sender, LinkClickedEventArgs e) { if (LinkClicked != null) LinkClicked(this, e); } public event EventHandler<LinkClickedEventArgs> LinkClicked; [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public SynchronizationContext SyncContext { get { return _synchronizationContext; } set //not private becuase the IProgress requires it be public { if (value == null || value == _synchronizationContext) return; throw new NotImplementedException( "There's no good reason for clients to be trying to set the SyncContext of a LogBox."); } } public void AddMenuItem(string label, Image image, EventHandler onClick) { _menu.DropDownItems.Add(label, image, onClick); } public bool ShowMenu { get { return _menu.Visible; } set { _menu.Visible = value; menuStrip1.Visible = (_menu.Visible || _reportLink.Visible); Invalidate(); } } public bool ShowDetailsMenuItem { get { return _showDetailsMenu.Visible; } set { _showDetailsMenu.Visible = value; } } public bool ShowDiagnosticsMenuItem { get { return _runDiagnostics.Visible; } set { _runDiagnostics.Visible = value; } } public bool ShowFontMenuItem { get { return _chooseFontMenuItem.Visible; } set { _chooseFontMenuItem.Visible = value; } } public bool ShowCopyToClipboardMenuItem { get { return _copyToClipboardMenuItem.Visible; } set { _copyToClipboardMenuItem.Visible = value; } } private void SetFont() { var fnt = SystemFonts.MessageBoxFont; var name = LogBoxSettings.Default.FontName; var size = LogBoxSettings.Default.FontSize; if (string.IsNullOrEmpty(name) && size > 0f) fnt = new Font(name, size); Font = fnt; } public override Font Font { get { return base.Font; } set { base.Font = _verboseBox.Font = _box.Font = value; } } public override string Text { get { return "Box:" + _box.Text + "Verbose:" + _verboseBox.Text; } } public string Rtf { get { return "Box:" + _box.Rtf + "Verbose:" + _verboseBox.Rtf; } } public void ScrollToTop() { foreach (var rtfBox in new[] { _box, _verboseBox }) { SafeInvoke(rtfBox, (() => { rtfBox.SelectionStart = rtfBox.SelectionLength = 0; rtfBox.ScrollToCaret(); })); } } public void WriteStatus(string message, params object[] args) { WriteMessage(message, args); } public void WriteMessageWithColor(Color color, string message, params object[] args) { Write(color, _box.Font.Style, message, args); } public void WriteMessageWithColor(string colorName, string message, params object[] args) { Write(Color.FromName(colorName), _box.Font.Style, message, args); } public void WriteMessageWithFontStyle(FontStyle style, string message, params object[] args) { Write(_box.ForeColor, style, message, args); } public void WriteMessageWithColorAndFontStyle(Color color, FontStyle style, string message, params object[] args) { Write(color, style, message, args); } public void WriteMessage(string message, params object[] args) { Write(_box.ForeColor, _box.Font.Style, message, args); } /// <summary> /// This is an attempt to avoid a mysterious crash (B. Waters) where the invoke was /// happening before the window's handle had been created /// </summary> public void SafeInvoke(Control box, Action action) { try { if (!box.IsHandleCreated) { //Debug.Fail("In release build, would have given up writing this message, because the destination control isn't built yet."); return; } if(!IsDisposed) //note, we'll check it again on the UI thread, since it could be disposed while waiting to run { if (SynchronizationContext.Current == SyncContext) //we're on the UI thread { action(); } else { //NB: if you're getting eratic behavior here, make sure there isn't one of those "access to modified closure" situations in your calling method SyncContext.Post(state => { //assumption is that since this is run on the UI thread, we can't be disposed in between the check of IsDiposed and the action itself if (!IsDisposed) action(); }, null); } } } catch (Exception) { #if DEBUG throw; #else //WS-34006 // better to swallow the message than raise a stink #endif } } private void Write(Color color, FontStyle style, string msg, params object[] args) { #if !DEBUG try { #endif foreach (var rtfBox in new[] {_box, _verboseBox}) { var rtfBoxForDelegate = rtfBox; //no really, this assignment is needed. Took hours to track down this bug. var styleForDelegate = style; SafeInvoke(rtfBox, (() => { #if !MONO // changing the text colour throws exceptions with mono 2011-12-09 // so just append plain text if (!rtfBoxForDelegate.Font.FontFamily.IsStyleAvailable(styleForDelegate)) style = rtfBoxForDelegate.Font.Style; using (var fnt = new Font(rtfBoxForDelegate.Font, styleForDelegate)) { rtfBoxForDelegate.SelectionStart = rtfBoxForDelegate.Text.Length; rtfBoxForDelegate.SelectionColor = color; rtfBoxForDelegate.SelectionFont = fnt; #endif rtfBoxForDelegate.AppendText(string.Format(msg + Environment.NewLine, args)); rtfBoxForDelegate.SelectionStart = rtfBoxForDelegate.Text.Length; rtfBoxForDelegate.ScrollToCaret(); #if !MONO } #endif })); } #if !DEBUG } catch (Exception) { //swallow. If the dreaded XP "Invoke or BeginInvoke cannot be called on a control until the window handle has been created" happens, it's really not worth crashing over //we shouldn't be getting that, given the SafeInvoke thing, but I did get a crash report here (but it was confusing, as if the //stack trace didn't actually go into this method, but the build date was after I wrote this. So this exception may never actually happen. } #endif } public void WriteWarning(string message, params object[] args) { Write(Color.Blue, _box.Font.Style, "Warning: " + message, args); } /// <summary> /// This is a callback the client can set to soemthing which will then generate /// Write() calls. If it is set, the user sees a "Run diagnostics" menu item. /// </summary> public Action<IProgress> GetDiagnosticsMethod { get { return _getDiagnosticsMethod; } set { _getDiagnosticsMethod = value; _runDiagnostics.Visible = (_getDiagnosticsMethod != null); } } public void WriteException(Exception error) { Write(Color.Red, _box.Font.Style, "Exception: " + error.Message); WriteVerbose(error.StackTrace); if (error.InnerException != null) { WriteError("Inner--> "); WriteException(error.InnerException); } } public void WriteError(string message, params object[] args) { Write(Color.Red, _box.Font.Style, Environment.NewLine + "Error: " + message, args); // There is no Invoke method on ToolStripItems (which the _reportLink is) // and setting it to visible from another thread seems to work okay. _reportLink.Visible = true; menuStrip1.Invoke(new Action(() => { menuStrip1.Visible = true; })); ErrorEncountered = true; } public bool ErrorEncountered { get; set; } public IProgressIndicator ProgressIndicator { get; set; } // this isn't implemented for a LogBox public void WriteVerbose(string message, params object[] args) { #if MONO _verboseBox.AppendText(SafeFormat(message + Environment.NewLine, args)); #else SafeInvoke(_verboseBox, (() => { _verboseBox.SelectionStart = _verboseBox.Text.Length; _verboseBox.SelectionColor = Color.DarkGray; _verboseBox.AppendText(SafeFormat(message + Environment.NewLine, args)); })); #endif } public static string SafeFormat(string format, params object[] args) { if (args == null && args.Length == 0) return format; //in many cases, we can avoid the format entirely. This gets us past the "hg log -template {node}" error. return format.FormatWithErrorStringInsteadOfException(args); } public bool ShowVerbose { set { _showDetailsMenu.Checked = value; } } public bool CancelRequested { get; set; } private void _showDetails_CheckedChanged(object sender, EventArgs e) { _verboseBox.Visible = _showDetailsMenu.Checked; _box.Visible = !_showDetailsMenu.Checked; if (_showDetailsMenu.Checked) { _box.Dock = DockStyle.None; _verboseBox.Dock = DockStyle.Fill; } else { _verboseBox.Dock = DockStyle.None; _box.Dock = DockStyle.Fill; } } private void _copyToClipboardLink_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { #if MONO //at least on Xubuntu, getting some rtf on the clipboard would mean that when you pasted, you'd see rtf if (!string.IsNullOrEmpty(_verboseBox.Text)) { Clipboard.SetText(_verboseBox.Text); } #else var data = new DataObject(); data.SetText(_verboseBox.Rtf, TextDataFormat.Rtf); data.SetText(_verboseBox.Text, TextDataFormat.UnicodeText); Clipboard.SetDataObject(data); #endif } public void Clear() { _box.Text = ""; _verboseBox.Text = ""; } private void copyToClipboardToolStripMenuItem_Click(object sender, EventArgs e) { _copyToClipboardLink_LinkClicked(sender, null); } private void LogBox_BackColorChanged(object sender, EventArgs e) { //_menu.BackColor = BackColor; } private void menuStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e) { } //private void _reportProblemLink_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) //{ // if (!ReportError(_verboseBox.Text)) // { // Clipboard.SetText(_verboseBox.Text); // MessageBox.Show( // "Information on what happened has been copied to your clipboard. Please email it to the developers of the program you are using."); // } //} private static bool ReportError(string msg) { try { ErrorReport.ReportNonFatalMessageWithStackTrace(msg); return true; } catch (Exception) { return false; } } private void OnRunDiagnosticsClick(object sender, EventArgs e) { if (GetDiagnosticsMethod != null) { ShowVerbose = true; GetDiagnosticsMethod(this); } } //this is important because we may be showing characters which aren't in the standard font private void OnChooseFontClick(object sender, EventArgs e) { using(var dlg = new FontDialog()) { dlg.ShowColor = false; dlg.ShowEffects = false; dlg.ShowApply = false; dlg.ShowHelp = false; dlg.Font = _box.Font; if (DialogResult.OK == dlg.ShowDialog()) { LogBoxSettings.Default.FontName = dlg.Font.Name; LogBoxSettings.Default.FontSize = dlg.Font.Size; LogBoxSettings.Default.Save(); SetFont(); } } } private void HandleTableLayoutPaint(object sender, PaintEventArgs e) { if (ShowMenu || _reportLink.Visible) { var pt = menuStrip1.Location; using (var pen = new Pen(VisualStyleInformation.TextControlBorder)) e.Graphics.DrawLine(pen, pt.X, pt.Y - 1, pt.X + menuStrip1.Width, pt.Y - 1); } } private void LogBox_Load(object sender, EventArgs e) { } } }
#pragma warning disable 0168 using nHydrate.Generator.Common; using nHydrate.Generator.Common.Models; using nHydrate.Generator.Common.Util; using System.Linq; using System.Text; namespace nHydrate.Generator.EFCodeFirstNetCore.Generators.ContextExtensions { public class ContextExtensionsGeneratedTemplate : EFCodeFirstNetCoreBaseTemplate { public ContextExtensionsGeneratedTemplate(ModelRoot model) : base(model) { } #region BaseClassTemplate overrides public override string FileName => _model.ProjectName + "EntitiesExtensions.Generated.cs"; public string ParentItemName => _model.ProjectName + "EntitiesExtensions.cs"; public override string FileContent { get => Generate(); } #endregion #region GenerateContent public override string Generate() { var sb = new StringBuilder(); GenerationHelper.AppendFileGeneatedMessageInCode(sb); this.AppendUsingStatements(sb); sb.AppendLine($"namespace {this.GetLocalNamespace()}"); sb.AppendLine("{"); this.AppendExtensions(sb); sb.AppendLine("}"); return sb.ToString(); } private void AppendUsingStatements(StringBuilder sb) { sb.AppendLine("using System;"); sb.AppendLine("using System.Linq;"); sb.AppendLine("using System.Collections.Generic;"); sb.AppendLine("using System.Reflection;"); sb.AppendLine(); } private void AppendExtensions(StringBuilder sb) { sb.AppendLine($" #region {_model.ProjectName}EntitiesExtensions"); sb.AppendLine(); sb.AppendLine(" /// <summary>"); sb.AppendLine(" /// Extension methods for this library"); sb.AppendLine(" /// </summary>"); sb.AppendLine($" [System.CodeDom.Compiler.GeneratedCode(\"nHydrate\", \"{_model.ModelToolVersion}\")]"); sb.AppendLine($" public static partial class {_model.ProjectName}EntitiesExtensions"); sb.AppendLine(" {"); #region GetEntityType sb.AppendLine(" #region GetEntityType"); sb.AppendLine(); sb.AppendLine(" /// <summary>"); sb.AppendLine(" /// Determines the entity from one of its fields"); sb.AppendLine(" /// </summary>"); sb.AppendLine(" public static System.Type GetEntityType(EntityMappingConstants entityType)"); sb.AppendLine(" {"); sb.AppendLine(" switch (entityType)"); sb.AppendLine(" {"); foreach (var table in _model.Database.Tables.Where(x => !x.AssociativeTable && !x.IsEnumOnly()).OrderBy(x => x.PascalName)) sb.AppendLine($" case EntityMappingConstants.{table.PascalName}: return typeof({this.GetLocalNamespace()}.Entity.{table.PascalName});"); sb.AppendLine(" }"); sb.AppendLine(" throw new Exception(\"Unknown entity type!\");"); sb.AppendLine(" }"); sb.AppendLine(); sb.AppendLine(" #endregion"); sb.AppendLine(); #endregion #region GetValue Methods sb.AppendLine(" #region GetValue Methods"); sb.AppendLine(); //GetValue by lambda sb.AppendLine(" /// <summary>"); sb.AppendLine(" /// Gets the value of one of this object's properties."); sb.AppendLine(" /// </summary>"); sb.AppendLine(" /// <typeparam name=\"T\">The type of value to retrieve</typeparam>"); sb.AppendLine(" /// <typeparam name=\"R\">The type of object from which retrieve the field value</typeparam>"); sb.AppendLine(" /// <param name=\"item\">The item from which to pull the value.</param>"); sb.AppendLine(" /// <param name=\"selector\">The field to retrieve</param>"); sb.AppendLine(" /// <returns></returns>"); sb.AppendLine(" public static T GetValue<T, R>(this R item, System.Linq.Expressions.Expression<System.Func<R, T>> selector)"); sb.AppendLine(" where R : IBusinessObject"); sb.AppendLine(" {"); sb.AppendLine(" var b = selector.Body.ToString();"); sb.AppendLine(" var arr = b.Split('.');"); sb.AppendLine(" if (arr.Length != 2) throw new System.Exception(\"Invalid selector\");"); sb.AppendLine(" var tn = arr.Last();"); sb.AppendLine(" var ft = ((IReadOnlyBusinessObject)item).GetFieldNameConstants();"); sb.AppendLine(" var te = (System.Enum)Enum.Parse(ft, tn, true);"); sb.AppendLine(" return item.GetValueInternal<T, R>(field: te, defaultValue: default(T));"); sb.AppendLine(" }"); sb.AppendLine(); //GetValue by lambda with default sb.AppendLine(" /// <summary>"); sb.AppendLine(" /// Gets the value of one of this object's properties."); sb.AppendLine(" /// </summary>"); sb.AppendLine(" /// <typeparam name=\"T\">The type of value to retrieve</typeparam>"); sb.AppendLine(" /// <typeparam name=\"R\">The type of object from which retrieve the field value</typeparam>"); sb.AppendLine(" /// <param name=\"item\">The item from which to pull the value.</param>"); sb.AppendLine(" /// <param name=\"selector\">The field to retrieve</param>"); sb.AppendLine(" /// <param name=\"defaultValue\">The default value to return if the specified value is NULL</param>"); sb.AppendLine(" /// <returns></returns>"); sb.AppendLine(" public static T GetValue<T, R>(this R item, System.Linq.Expressions.Expression<System.Func<R, T>> selector, T defaultValue)"); sb.AppendLine(" where R : IBusinessObject"); sb.AppendLine(" {"); sb.AppendLine(" var b = selector.Body.ToString();"); sb.AppendLine(" var arr = b.Split('.');"); sb.AppendLine(" if (arr.Length != 2) throw new System.Exception(\"Invalid selector\");"); sb.AppendLine(" var tn = arr.Last();"); sb.AppendLine(" var ft = ((IReadOnlyBusinessObject)item).GetFieldNameConstants();"); sb.AppendLine(" var te = (System.Enum)Enum.Parse(ft, tn, true);"); sb.AppendLine(" return item.GetValueInternal<T, R>(field: te, defaultValue: defaultValue);"); sb.AppendLine(" }"); sb.AppendLine(); //GetValue by by Enum with default sb.AppendLine(" /// <summary>"); sb.AppendLine(" /// Gets the value of one of this object's properties."); sb.AppendLine(" /// </summary>"); sb.AppendLine(" /// <typeparam name=\"T\">The type of value to retrieve</typeparam>"); sb.AppendLine(" /// <typeparam name=\"R\">The type of object from which retrieve the field value</typeparam>"); sb.AppendLine(" /// <param name=\"item\">The item from which to pull the value.</param>"); sb.AppendLine(" /// <param name=\"field\">The field value to retrieve</param>"); sb.AppendLine(" /// <param name=\"defaultValue\">The default value to return if the specified value is NULL</param>"); sb.AppendLine(" /// <returns></returns>"); sb.AppendLine(" private static T GetValueInternal<T, R>(this R item, System.Enum field, T defaultValue)"); sb.AppendLine(" where R : IBusinessObject"); sb.AppendLine(" {"); sb.AppendLine(" var valid = false;"); sb.AppendLine(" if (typeof(T) == typeof(bool)) valid = true;"); sb.AppendLine(" else if (typeof(T) == typeof(byte)) valid = true;"); sb.AppendLine(" else if (typeof(T) == typeof(char)) valid = true;"); sb.AppendLine(" else if (typeof(T) == typeof(DateTime)) valid = true;"); sb.AppendLine(" else if (typeof(T) == typeof(decimal)) valid = true;"); sb.AppendLine(" else if (typeof(T) == typeof(double)) valid = true;"); sb.AppendLine(" else if (typeof(T) == typeof(int)) valid = true;"); sb.AppendLine(" else if (typeof(T) == typeof(long)) valid = true;"); sb.AppendLine(" else if (typeof(T) == typeof(Single)) valid = true;"); sb.AppendLine(" else if (typeof(T) == typeof(string)) valid = true;"); sb.AppendLine(" if (!valid)"); sb.AppendLine(" throw new Exception(\"Cannot convert object to type '\" + typeof(T).ToString() + \"'!\");"); sb.AppendLine(); sb.AppendLine(" object o = ((IReadOnlyBusinessObject)item).GetValue(field, defaultValue);"); sb.AppendLine(" if (o == null) return defaultValue;"); sb.AppendLine(); sb.AppendLine(" if (o is T)"); sb.AppendLine(" {"); sb.AppendLine(" return (T)o;"); sb.AppendLine(" }"); sb.AppendLine(" else if (typeof(T) == typeof(bool))"); sb.AppendLine(" {"); sb.AppendLine(" return (T)(object)Convert.ToBoolean(o);"); sb.AppendLine(" }"); sb.AppendLine(" else if (typeof(T) == typeof(byte))"); sb.AppendLine(" {"); sb.AppendLine(" return (T)(object)Convert.ToByte(o);"); sb.AppendLine(" }"); sb.AppendLine(" else if (typeof(T) == typeof(char))"); sb.AppendLine(" {"); sb.AppendLine(" return (T)(object)Convert.ToChar(o);"); sb.AppendLine(" }"); sb.AppendLine(" else if (typeof(T) == typeof(DateTime))"); sb.AppendLine(" {"); sb.AppendLine(" return (T)(object)Convert.ToDateTime(o);"); sb.AppendLine(" }"); sb.AppendLine(" else if (typeof(T) == typeof(decimal))"); sb.AppendLine(" {"); sb.AppendLine(" return (T)(object)Convert.ToDecimal(o);"); sb.AppendLine(" }"); sb.AppendLine(" else if (typeof(T) == typeof(double))"); sb.AppendLine(" {"); sb.AppendLine(" return (T)(object)Convert.ToDouble(o);"); sb.AppendLine(" }"); sb.AppendLine(" else if (typeof(T) == typeof(int))"); sb.AppendLine(" {"); sb.AppendLine(" return (T)(object)Convert.ToInt32(o);"); sb.AppendLine(" }"); sb.AppendLine(" else if (typeof(T) == typeof(long))"); sb.AppendLine(" {"); sb.AppendLine(" return (T)(object)Convert.ToInt64(o);"); sb.AppendLine(" }"); sb.AppendLine(" else if (typeof(T) == typeof(Single))"); sb.AppendLine(" {"); sb.AppendLine(" return (T)(object)Convert.ToSingle(o);"); sb.AppendLine(" }"); sb.AppendLine(" else if (typeof(T) == typeof(string))"); sb.AppendLine(" {"); sb.AppendLine(" return (T)(object)Convert.ToString(o);"); sb.AppendLine(" }"); sb.AppendLine(" throw new Exception(\"Cannot convert object!\");"); sb.AppendLine(" }"); sb.AppendLine(); sb.AppendLine(" #endregion"); sb.AppendLine(); #endregion #region SetValue sb.AppendLine(" #region SetValue"); sb.AppendLine(" /// <summary>"); sb.AppendLine(" /// Assigns a value to a field on this object."); sb.AppendLine(" /// </summary>"); sb.AppendLine(" /// <param name=\"item\">The entity to set</param>"); sb.AppendLine(" /// <param name=\"selector\">The field on the entity to set</param>"); sb.AppendLine(" /// <param name=\"newValue\">The new value to assign to the field</param>"); sb.AppendLine(" public static void SetValue<TResult, R>(this R item, System.Linq.Expressions.Expression<System.Func<R, TResult>> selector, TResult newValue)"); sb.AppendLine(" where R : IBusinessObject"); sb.AppendLine(" {"); sb.AppendLine(" SetValue(item: item, selector: selector, newValue: newValue, fixLength: false);"); sb.AppendLine(" }"); sb.AppendLine(); sb.AppendLine(" /// <summary>"); sb.AppendLine(" /// Assigns a value to a field on this object."); sb.AppendLine(" /// </summary>"); sb.AppendLine(" /// <param name=\"item\">The entity to set</param>"); sb.AppendLine(" /// <param name=\"selector\">The field on the entity to set</param>"); sb.AppendLine(" /// <param name=\"newValue\">The new value to assign to the field</param>"); sb.AppendLine(" /// <param name=\"fixLength\">Determines if the length should be truncated if too long. When false, an error will be raised if data is too large to be assigned to the field.</param>"); sb.AppendLine(" public static void SetValue<TResult, R>(this R item, System.Linq.Expressions.Expression<System.Func<R, TResult>> selector, TResult newValue, bool fixLength)"); sb.AppendLine(" where R : IBusinessObject"); sb.AppendLine(" {"); sb.AppendLine(" var b = selector.Body.ToString();"); sb.AppendLine(" var arr = b.Split('.');"); sb.AppendLine(" if (arr.Length != 2) throw new System.Exception(\"Invalid selector\");"); sb.AppendLine(" var tn = arr.Last();"); sb.AppendLine(" var ft = ((IReadOnlyBusinessObject)item).GetFieldNameConstants();"); sb.AppendLine(" var te = (System.Enum)Enum.Parse(ft, tn, true);"); sb.AppendLine(" ((IBusinessObject)item).SetValue(field: te, newValue: newValue, fixLength: fixLength);"); sb.AppendLine(" }"); sb.AppendLine(); sb.AppendLine(" #endregion"); sb.AppendLine(); #endregion #region Many-to-Many Convenience extensions sb.AppendLine(" #region Many-to-Many Convenience Extensions"); foreach (var table in _model.Database.Tables.Where(x => x.AssociativeTable).OrderBy(x => x.Name)) { var relations = table.GetRelationsWhereChild().ToList(); if (relations.Count == 2) { var relation1 = relations.First(); var relation2 = relations.Last(); sb.AppendLine(" /// <summary>"); sb.AppendLine($" /// Adds a {relation1.ParentTable.PascalName} child entity to a many-to-many relationship"); sb.AppendLine(" /// </summary>"); sb.AppendLine($" public static void Associate{relation1.ParentTable.PascalName}(this EFDAL.Entity.{relation2.ParentTable.PascalName} item, EFDAL.Entity.{relation1.ParentTable.PascalName} child)"); sb.AppendLine(" {"); sb.AppendLine($" if (item.{table.PascalName}List == null)"); sb.AppendLine($" item.{table.PascalName}List = new List<Entity.{table.PascalName}>();"); sb.AppendLine(" item." + table.PascalName + "List.Add(new EFDAL.Entity." + table.PascalName + " { " + relation2.ParentTable.PascalName + " = item, " + relation1.ParentTable.PascalName + " = child });"); sb.AppendLine(" }"); sb.AppendLine(); sb.AppendLine(" /// <summary>"); sb.AppendLine($" /// Removes a {relation1.ParentTable.PascalName} child entity from a many-to-many relationship"); sb.AppendLine(" /// </summary>"); sb.AppendLine($" public static void Unassociate{relation1.ParentTable.PascalName}(this EFDAL.Entity.{relation2.ParentTable.PascalName} item, EFDAL.Entity.{relation1.ParentTable.PascalName} child)"); sb.AppendLine(" {"); sb.AppendLine($" if (item.{table.PascalName}List == null)"); sb.AppendLine($" item.{table.PascalName}List = new List<Entity.{table.PascalName}>();"); sb.AppendLine(); sb.AppendLine($" var list = item.{table.PascalName}List.Where(x => x.{relation1.ParentTable.PascalName} == child).ToList();"); sb.AppendLine(" foreach (var cItem in list)"); sb.AppendLine($" item.{table.PascalName}List.Remove(cItem);"); sb.AppendLine(" }"); sb.AppendLine(); sb.AppendLine(" /// <summary>"); sb.AppendLine($" /// Adds a {relation2.ParentTable.PascalName} child entity to a many-to-many relationship"); sb.AppendLine(" /// </summary>"); sb.AppendLine($" public static void Associate{relation2.ParentTable.PascalName}(this EFDAL.Entity.{relation1.ParentTable.PascalName} item, EFDAL.Entity.{relation2.ParentTable.PascalName} child)"); sb.AppendLine(" {"); sb.AppendLine($" if (item.{table.PascalName}List == null)"); sb.AppendLine($" item.{table.PascalName}List = new List<Entity.{table.PascalName}>();"); sb.AppendLine(" item." + table.PascalName + "List.Add(new EFDAL.Entity." + table.PascalName + " { " + relation1.ParentTable.PascalName + " = item, " + relation2.ParentTable.PascalName + " = child });"); sb.AppendLine(" }"); sb.AppendLine(); sb.AppendLine(" /// <summary>"); sb.AppendLine($" /// Removes a {relation2.ParentTable.PascalName} child entity from a many-to-many relationship"); sb.AppendLine(" /// </summary>"); sb.AppendLine($" public static void Unassociate{relation2.ParentTable.PascalName}(this EFDAL.Entity.{relation1.ParentTable.PascalName} item, EFDAL.Entity.{relation2.ParentTable.PascalName} child)"); sb.AppendLine(" {"); sb.AppendLine($" if (item.{table.PascalName}List == null)"); sb.AppendLine($" item.{table.PascalName}List = new List<Entity.{table.PascalName}>();"); sb.AppendLine(); sb.AppendLine($" var list = item.{table.PascalName}List.Where(x => x.{relation2.ParentTable.PascalName} == child).ToList();"); sb.AppendLine(" foreach (var cItem in list)"); sb.AppendLine($" item.{table.PascalName}List.Remove(cItem);"); sb.AppendLine(" }"); sb.AppendLine(); } } sb.AppendLine(" #endregion"); #endregion sb.AppendLine(" }"); sb.AppendLine(); #region SequentialId sb.AppendLine(" #region SequentialIdGenerator"); sb.AppendLine(); sb.AppendLine(" /// <summary>"); sb.AppendLine(" /// Generates Sequential Guid values that can be used for Sql Server UniqueIdentifiers to improve performance."); sb.AppendLine(" /// </summary>"); sb.AppendLine(" internal class SequentialIdGenerator"); sb.AppendLine(" {"); sb.AppendLine(" private readonly object _lock;"); sb.AppendLine(" private Guid _lastGuid;"); sb.AppendLine(" // 3 - the least significant byte in Guid ByteArray [for SQL Server ORDER BY clause]"); sb.AppendLine(" // 10 - the most significant byte in Guid ByteArray [for SQL Server ORDERY BY clause]"); sb.AppendLine(" private static readonly int[] SqlOrderMap = new int[] { 3, 2, 1, 0, 5, 4, 7, 6, 9, 8, 15, 14, 13, 12, 11, 10 };"); sb.AppendLine(); sb.AppendLine(" /// <summary>"); sb.AppendLine(" /// Creates a new SequentialId class to generate sequential GUID values."); sb.AppendLine(" /// </summary>"); sb.AppendLine(" public SequentialIdGenerator() : this(Guid.NewGuid()) { }"); sb.AppendLine(); sb.AppendLine(" /// <summary>"); sb.AppendLine(" /// Creates a new SequentialId class to generate sequential GUID values."); sb.AppendLine(" /// </summary>"); sb.AppendLine(" /// <param name=\"seed\">Starting seed value.</param>"); sb.AppendLine(" /// <remarks>You can save the last generated value <see cref=\"LastValue\"/> and then "); sb.AppendLine(" /// use this as the new seed value to pick up where you left off.</remarks>"); sb.AppendLine(" public SequentialIdGenerator(Guid seed)"); sb.AppendLine(" {"); sb.AppendLine(" _lock = new object();"); sb.AppendLine(" _lastGuid = seed;"); sb.AppendLine(" }"); sb.AppendLine(); sb.AppendLine(" /// <summary>"); sb.AppendLine(" /// Last generated guid value. If no values have been generated, this will be the seed value."); sb.AppendLine(" /// </summary>"); sb.AppendLine(" public Guid LastValue"); sb.AppendLine(" {"); sb.AppendLine(" get {"); sb.AppendLine(" lock (_lock)"); sb.AppendLine(" {"); sb.AppendLine(" return _lastGuid;"); sb.AppendLine(" }"); sb.AppendLine(" }"); sb.AppendLine(" set"); sb.AppendLine(" {"); sb.AppendLine(" lock (_lock)"); sb.AppendLine(" {"); sb.AppendLine(" _lastGuid = value;"); sb.AppendLine(" }"); sb.AppendLine(" }"); sb.AppendLine(" }"); sb.AppendLine(); sb.AppendLine(" /// <summary>"); sb.AppendLine(" /// Generate a new sequential id."); sb.AppendLine(" /// </summary>"); sb.AppendLine(" /// <returns>New sequential id value.</returns>"); sb.AppendLine(" public Guid NewId()"); sb.AppendLine(" {"); sb.AppendLine(" Guid newId;"); sb.AppendLine(" lock (_lock)"); sb.AppendLine(" {"); sb.AppendLine(" var guidBytes = _lastGuid.ToByteArray();"); sb.AppendLine(" ReorderToSqlOrder(ref guidBytes);"); sb.AppendLine(" newId = new Guid(guidBytes);"); sb.AppendLine(" _lastGuid = newId;"); sb.AppendLine(" }"); sb.AppendLine(); sb.AppendLine(" return newId;"); sb.AppendLine(" }"); sb.AppendLine(); sb.AppendLine(" private static void ReorderToSqlOrder(ref byte[] bytes)"); sb.AppendLine(" {"); sb.AppendLine(" foreach (var bytesIndex in SqlOrderMap)"); sb.AppendLine(" {"); sb.AppendLine(" bytes[bytesIndex]++;"); sb.AppendLine(" if (bytes[bytesIndex] != 0)"); sb.AppendLine(" {"); sb.AppendLine(" break;"); sb.AppendLine(" }"); sb.AppendLine(" }"); sb.AppendLine(" }"); sb.AppendLine(); sb.AppendLine(" /// <summary>"); sb.AppendLine(" /// IComparer.Compare compatible method to order Guid values the same way as MS Sql Server."); sb.AppendLine(" /// </summary>"); sb.AppendLine(" /// <param name=\"x\">The first guid to compare</param>"); sb.AppendLine(" /// <param name=\"y\">The second guid to compare</param>"); sb.AppendLine(" /// <returns><see cref=\"System.Collections.IComparer.Compare\"/></returns>"); sb.AppendLine(" public static int SqlCompare(Guid x, Guid y)"); sb.AppendLine(" {"); sb.AppendLine(" var result = 0;"); sb.AppendLine(" var index = SqlOrderMap.Length - 1;"); sb.AppendLine(" var xBytes = x.ToByteArray();"); sb.AppendLine(" var yBytes = y.ToByteArray();"); sb.AppendLine(); sb.AppendLine(" while (result == 0 && index >= 0)"); sb.AppendLine(" {"); sb.AppendLine(" result = xBytes[SqlOrderMap[index]].CompareTo(yBytes[SqlOrderMap[index]]);"); sb.AppendLine(" index--;"); sb.AppendLine(" }"); sb.AppendLine(" return result;"); sb.AppendLine(" }"); sb.AppendLine(" }"); sb.AppendLine(); sb.AppendLine(" #endregion"); sb.AppendLine(); #endregion sb.AppendLine(" #endregion"); sb.AppendLine(); } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Web; namespace Umbraco.Core.ObjectResolution { /// <summary> /// The base class for all many-objects resolvers. /// </summary> /// <typeparam name="TResolver">The type of the concrete resolver class.</typeparam> /// <typeparam name="TResolved">The type of the resolved objects.</typeparam> public abstract class ManyObjectsResolverBase<TResolver, TResolved> : ResolverBase<TResolver> where TResolved : class where TResolver : ResolverBase { private IEnumerable<TResolved> _applicationInstances = null; private readonly ReaderWriterLockSlim _lock = new ReaderWriterLockSlim(); private readonly string _httpContextKey; private readonly List<Type> _instanceTypes = new List<Type>(); private IEnumerable<TResolved> _sortedValues = null; private int _defaultPluginWeight = 10; #region Constructors /// <summary> /// Initializes a new instance of the <see cref="ManyObjectsResolverBase{TResolver, TResolved}"/> class with an empty list of objects, /// and an optional lifetime scope. /// </summary> /// <param name="scope">The lifetime scope of instantiated objects, default is per Application.</param> /// <remarks>If <paramref name="scope"/> is per HttpRequest then there must be a current HttpContext.</remarks> /// <exception cref="InvalidOperationException"><paramref name="scope"/> is per HttpRequest but the current HttpContext is null.</exception> protected ManyObjectsResolverBase(ObjectLifetimeScope scope = ObjectLifetimeScope.Application) { CanResolveBeforeFrozen = false; if (scope == ObjectLifetimeScope.HttpRequest) { if (HttpContext.Current == null) throw new InvalidOperationException("Use alternative constructor accepting a HttpContextBase object in order to set the lifetime scope to HttpRequest when HttpContext.Current is null"); CurrentHttpContext = new HttpContextWrapper(HttpContext.Current); } LifetimeScope = scope; if (scope == ObjectLifetimeScope.HttpRequest) _httpContextKey = this.GetType().FullName; _instanceTypes = new List<Type>(); } /// <summary> /// Initializes a new instance of the <see cref="ManyObjectsResolverBase{TResolver, TResolved}"/> class with an empty list of objects, /// with creation of objects based on an HttpRequest lifetime scope. /// </summary> /// <param name="httpContext">The HttpContextBase corresponding to the HttpRequest.</param> /// <exception cref="ArgumentNullException"><paramref name="httpContext"/> is <c>null</c>.</exception> protected ManyObjectsResolverBase(HttpContextBase httpContext) { CanResolveBeforeFrozen = false; if (httpContext == null) throw new ArgumentNullException("httpContext"); LifetimeScope = ObjectLifetimeScope.HttpRequest; _httpContextKey = this.GetType().FullName; CurrentHttpContext = httpContext; _instanceTypes = new List<Type>(); } /// <summary> /// Initializes a new instance of the <see cref="ManyObjectsResolverBase{TResolver, TResolved}"/> class with an initial list of object types, /// and an optional lifetime scope. /// </summary> /// <param name="value">The list of object types.</param> /// <param name="scope">The lifetime scope of instantiated objects, default is per Application.</param> /// <remarks>If <paramref name="scope"/> is per HttpRequest then there must be a current HttpContext.</remarks> /// <exception cref="InvalidOperationException"><paramref name="scope"/> is per HttpRequest but the current HttpContext is null.</exception> protected ManyObjectsResolverBase(IEnumerable<Type> value, ObjectLifetimeScope scope = ObjectLifetimeScope.Application) : this(scope) { _instanceTypes = value.ToList(); } /// <summary> /// Initializes a new instance of the <see cref="ManyObjectsResolverBase{TResolver, TResolved}"/> class with an initial list of objects, /// with creation of objects based on an HttpRequest lifetime scope. /// </summary> /// <param name="httpContext">The HttpContextBase corresponding to the HttpRequest.</param> /// <param name="value">The list of object types.</param> /// <exception cref="ArgumentNullException"><paramref name="httpContext"/> is <c>null</c>.</exception> protected ManyObjectsResolverBase(HttpContextBase httpContext, IEnumerable<Type> value) : this(httpContext) { _instanceTypes = value.ToList(); } #endregion /// <summary> /// Gets or sets a value indicating whether the resolver can resolve objects before resolution is frozen. /// </summary> /// <remarks>This is false by default and is used for some special internal resolvers.</remarks> internal bool CanResolveBeforeFrozen { get; set; } /// <summary> /// Gets the list of types to create instances from. /// </summary> protected virtual IEnumerable<Type> InstanceTypes { get { return _instanceTypes; } } /// <summary> /// Gets or sets the <see cref="HttpContextBase"/> used to initialize this object, if any. /// </summary> /// <remarks>If not null, then <c>LifetimeScope</c> will be <c>ObjectLifetimeScope.HttpRequest</c>.</remarks> protected HttpContextBase CurrentHttpContext { get; private set; } /// <summary> /// Gets or sets the lifetime scope of resolved objects. /// </summary> protected ObjectLifetimeScope LifetimeScope { get; private set; } /// <summary> /// Gets the resolved object instances, sorted by weight. /// </summary> /// <returns>The sorted resolved object instances.</returns> /// <remarks> /// <para>The order is based upon the <c>WeightedPluginAttribute</c> and <c>DefaultPluginWeight</c>.</para> /// <para>Weights are sorted ascendingly (lowest weights come first).</para> /// </remarks> protected IEnumerable<TResolved> GetSortedValues() { if (_sortedValues == null) { var values = Values.ToList(); values.Sort((f1, f2) => GetObjectWeight(f1).CompareTo(GetObjectWeight(f2))); _sortedValues = values; } return _sortedValues; } /// <summary> /// Gets or sets the default type weight. /// </summary> /// <remarks>Determines the weight of types that do not have a <c>WeightedPluginAttribute</c> set on /// them, when calling <c>GetSortedValues</c>.</remarks> protected virtual int DefaultPluginWeight { get { return _defaultPluginWeight; } set { _defaultPluginWeight = value; } } /// <summary> /// Returns the weight of an object for user with GetSortedValues /// </summary> /// <param name="o"></param> /// <returns></returns> protected virtual int GetObjectWeight(object o) { var type = o.GetType(); var attr = type.GetCustomAttribute<WeightedPluginAttribute>(true); return attr == null ? DefaultPluginWeight : attr.Weight; } /// <summary> /// Gets the resolved object instances. /// </summary> /// <exception cref="InvalidOperationException"><c>CanResolveBeforeFrozen</c> is false, and resolution is not frozen.</exception> protected IEnumerable<TResolved> Values { get { using (Resolution.Reader(CanResolveBeforeFrozen)) { // note: we apply .ToArray() to the output of CreateInstance() because that is an IEnumerable that // comes from the PluginManager we want to be _sure_ that it's not a Linq of some sort, but the // instances have actually been instanciated when we return. switch (LifetimeScope) { case ObjectLifetimeScope.HttpRequest: // create new instances per HttpContext using (var l = new UpgradeableReadLock(_lock)) { // create if not already there if (CurrentHttpContext.Items[_httpContextKey] == null) { l.UpgradeToWriteLock(); CurrentHttpContext.Items[_httpContextKey] = CreateInstances().ToArray(); } return (TResolved[])CurrentHttpContext.Items[_httpContextKey]; } case ObjectLifetimeScope.Application: // create new instances per application using (var l = new UpgradeableReadLock(_lock)) { // create if not already there if (_applicationInstances == null) { l.UpgradeToWriteLock(); _applicationInstances = CreateInstances().ToArray(); } return _applicationInstances; } case ObjectLifetimeScope.Transient: default: // create new instances each time return CreateInstances().ToArray(); } } } } /// <summary> /// Creates the object instances for the types contained in the types collection. /// </summary> /// <returns>A list of objects of type <typeparamref name="TResolved"/>.</returns> protected virtual IEnumerable<TResolved> CreateInstances() { return PluginManager.Current.CreateInstances<TResolved>(InstanceTypes); } #region Types collection manipulation /// <summary> /// Removes a type. /// </summary> /// <param name="value">The type to remove.</param> /// <exception cref="InvalidOperationException">the resolver does not support removing types, or /// the type is not a valid type for the resolver.</exception> public virtual void RemoveType(Type value) { EnsureSupportsRemove(); using (Resolution.Configuration) using (var l = new UpgradeableReadLock(_lock)) { EnsureCorrectType(value); l.UpgradeToWriteLock(); _instanceTypes.Remove(value); } } /// <summary> /// Removes a type. /// </summary> /// <typeparam name="T">The type to remove.</typeparam> /// <exception cref="InvalidOperationException">the resolver does not support removing types, or /// the type is not a valid type for the resolver.</exception> public void RemoveType<T>() where T : TResolved { RemoveType(typeof(T)); } /// <summary> /// Adds types. /// </summary> /// <param name="types">The types to add.</param> /// <remarks>The types are appended at the end of the list.</remarks> /// <exception cref="InvalidOperationException">the resolver does not support adding types, or /// a type is not a valid type for the resolver, or a type is already in the collection of types.</exception> protected void AddTypes(IEnumerable<Type> types) { EnsureSupportsAdd(); using (Resolution.Configuration) using (new WriteLock(_lock)) { foreach(var t in types) { EnsureCorrectType(t); if (_instanceTypes.Contains(t)) { throw new InvalidOperationException(string.Format( "Type {0} is already in the collection of types.", t.FullName)); } _instanceTypes.Add(t); } } } /// <summary> /// Adds a type. /// </summary> /// <param name="value">The type to add.</param> /// <remarks>The type is appended at the end of the list.</remarks> /// <exception cref="InvalidOperationException">the resolver does not support adding types, or /// the type is not a valid type for the resolver, or the type is already in the collection of types.</exception> public virtual void AddType(Type value) { EnsureSupportsAdd(); using (Resolution.Configuration) using (var l = new UpgradeableReadLock(_lock)) { EnsureCorrectType(value); if (_instanceTypes.Contains(value)) { throw new InvalidOperationException(string.Format( "Type {0} is already in the collection of types.", value.FullName)); } l.UpgradeToWriteLock(); _instanceTypes.Add(value); } } /// <summary> /// Adds a type. /// </summary> /// <typeparam name="T">The type to add.</typeparam> /// <remarks>The type is appended at the end of the list.</remarks> /// <exception cref="InvalidOperationException">the resolver does not support adding types, or /// the type is not a valid type for the resolver, or the type is already in the collection of types.</exception> public void AddType<T>() where T : TResolved { AddType(typeof(T)); } /// <summary> /// Clears the list of types. /// </summary> /// <exception cref="InvalidOperationException">the resolver does not support clearing types.</exception> public virtual void Clear() { EnsureSupportsClear(); using (Resolution.Configuration) using (new WriteLock(_lock)) { _instanceTypes.Clear(); } } /// <summary> /// Inserts a type at the specified index. /// </summary> /// <param name="index">The zero-based index at which the type should be inserted.</param> /// <param name="value">The type to insert.</param> /// <exception cref="InvalidOperationException">the resolver does not support inserting types, or /// the type is not a valid type for the resolver, or the type is already in the collection of types.</exception> /// <exception cref="ArgumentOutOfRangeException"><paramref name="index"/> is out of range.</exception> public virtual void InsertType(int index, Type value) { EnsureSupportsInsert(); using (Resolution.Configuration) using (var l = new UpgradeableReadLock(_lock)) { EnsureCorrectType(value); if (_instanceTypes.Contains(value)) { throw new InvalidOperationException(string.Format( "Type {0} is already in the collection of types.", value.FullName)); } l.UpgradeToWriteLock(); _instanceTypes.Insert(index, value); } } /// <summary> /// Inserts a type at the beginning of the list. /// </summary> /// <param name="value">The type to insert.</param> /// <exception cref="InvalidOperationException">the resolver does not support inserting types, or /// the type is not a valid type for the resolver, or the type is already in the collection of types.</exception> public virtual void InsertType(Type value) { InsertType(0, value); } /// <summary> /// Inserts a type at the specified index. /// </summary> /// <typeparam name="T">The type to insert.</typeparam> /// <param name="index">The zero-based index at which the type should be inserted.</param> /// <exception cref="ArgumentOutOfRangeException"><paramref name="index"/> is out of range.</exception> public void InsertType<T>(int index) where T : TResolved { InsertType(index, typeof(T)); } /// <summary> /// Inserts a type at the beginning of the list. /// </summary> /// <typeparam name="T">The type to insert.</typeparam> public void InsertType<T>() where T : TResolved { InsertType(0, typeof(T)); } /// <summary> /// Inserts a type before a specified, already existing type. /// </summary> /// <param name="existingType">The existing type before which to insert.</param> /// <param name="value">The type to insert.</param> /// <exception cref="InvalidOperationException">the resolver does not support inserting types, or /// one of the types is not a valid type for the resolver, or the existing type is not in the collection, /// or the new type is already in the collection of types.</exception> public virtual void InsertTypeBefore(Type existingType, Type value) { EnsureSupportsInsert(); using (Resolution.Configuration) using (var l = new UpgradeableReadLock(_lock)) { EnsureCorrectType(existingType); EnsureCorrectType(value); if (!_instanceTypes.Contains(existingType)) { throw new InvalidOperationException(string.Format( "Type {0} is not in the collection of types.", existingType.FullName)); } if (_instanceTypes.Contains(value)) { throw new InvalidOperationException(string.Format( "Type {0} is already in the collection of types.", value.FullName)); } int index = _instanceTypes.IndexOf(existingType); l.UpgradeToWriteLock(); _instanceTypes.Insert(index, value); } } /// <summary> /// Inserts a type before a specified, already existing type. /// </summary> /// <typeparam name="TExisting">The existing type before which to insert.</typeparam> /// <typeparam name="T">The type to insert.</typeparam> /// <exception cref="InvalidOperationException">the resolver does not support inserting types, or /// one of the types is not a valid type for the resolver, or the existing type is not in the collection, /// or the new type is already in the collection of types.</exception> public void InsertTypeBefore<TExisting, T>() where TExisting : TResolved where T : TResolved { InsertTypeBefore(typeof(TExisting), typeof(T)); } /// <summary> /// Returns a value indicating whether the specified type is already in the collection of types. /// </summary> /// <param name="value">The type to look for.</param> /// <returns>A value indicating whether the type is already in the collection of types.</returns> public virtual bool ContainsType(Type value) { using (new ReadLock(_lock)) { return _instanceTypes.Contains(value); } } /// <summary> /// Gets the types in the collection of types. /// </summary> /// <returns>The types in the collection of types.</returns> /// <remarks>Returns an enumeration, the list cannot be modified.</remarks> public virtual IEnumerable<Type> GetTypes() { Type[] types; using (new ReadLock(_lock)) { types = _instanceTypes.ToArray(); } return types; } /// <summary> /// Returns a value indicating whether the specified type is already in the collection of types. /// </summary> /// <typeparam name="T">The type to look for.</typeparam> /// <returns>A value indicating whether the type is already in the collection of types.</returns> public bool ContainsType<T>() where T : TResolved { return ContainsType(typeof(T)); } #endregion /// <summary> /// Returns a WriteLock to use when modifying collections /// </summary> /// <returns></returns> protected WriteLock GetWriteLock() { return new WriteLock(_lock); } #region Type utilities /// <summary> /// Ensures that a type is a valid type for the resolver. /// </summary> /// <param name="value">The type to test.</param> /// <exception cref="InvalidOperationException">the type is not a valid type for the resolver.</exception> protected void EnsureCorrectType(Type value) { if (!TypeHelper.IsTypeAssignableFrom<TResolved>(value)) throw new InvalidOperationException(string.Format( "Type {0} is not an acceptable type for resolver {1}.", value.FullName, this.GetType().FullName)); } #endregion #region Types collection manipulation support /// <summary> /// Ensures that the resolver supports removing types. /// </summary> /// <exception cref="InvalidOperationException">The resolver does not support removing types.</exception> protected void EnsureSupportsRemove() { if (!SupportsRemove) throw new InvalidOperationException("This resolver does not support removing types"); } /// <summary> /// Ensures that the resolver supports clearing types. /// </summary> /// <exception cref="InvalidOperationException">The resolver does not support clearing types.</exception> protected void EnsureSupportsClear() { if (!SupportsClear) throw new InvalidOperationException("This resolver does not support clearing types"); } /// <summary> /// Ensures that the resolver supports adding types. /// </summary> /// <exception cref="InvalidOperationException">The resolver does not support adding types.</exception> protected void EnsureSupportsAdd() { if (!SupportsAdd) throw new InvalidOperationException("This resolver does not support adding new types"); } /// <summary> /// Ensures that the resolver supports inserting types. /// </summary> /// <exception cref="InvalidOperationException">The resolver does not support inserting types.</exception> protected void EnsureSupportsInsert() { if (!SupportsInsert) throw new InvalidOperationException("This resolver does not support inserting new types"); } /// <summary> /// Gets a value indicating whether the resolver supports adding types. /// </summary> protected virtual bool SupportsAdd { get { return true; } } /// <summary> /// Gets a value indicating whether the resolver supports inserting types. /// </summary> protected virtual bool SupportsInsert { get { return true; } } /// <summary> /// Gets a value indicating whether the resolver supports clearing types. /// </summary> protected virtual bool SupportsClear { get { return true; } } /// <summary> /// Gets a value indicating whether the resolver supports removing types. /// </summary> protected virtual bool SupportsRemove { get { return true; } } #endregion } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Diagnostics; using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; using System.Collections.Generic; using CURLAUTH = Interop.Http.CURLAUTH; using CURLcode = Interop.Http.CURLcode; using CURLMcode = Interop.Http.CURLMcode; using CURLoption = Interop.Http.CURLoption; namespace System.Net.Http { internal partial class CurlHandler : HttpMessageHandler { #region Constants private const string VerboseDebuggingConditional = "CURLHANDLER_VERBOSE"; private const char SpaceChar = ' '; private const int StatusCodeLength = 3; private const string UriSchemeHttp = "http"; private const string UriSchemeHttps = "https"; private const string EncodingNameGzip = "gzip"; private const string EncodingNameDeflate = "deflate"; private const int RequestBufferSize = 16384; // Default used by libcurl private const string NoTransferEncoding = HttpKnownHeaderNames.TransferEncoding + ":"; private const string NoContentType = HttpKnownHeaderNames.ContentType + ":"; private const int CurlAge = 5; private const int MinCurlAge = 3; #endregion #region Fields private readonly static char[] s_newLineCharArray = new char[] { HttpRuleParser.CR, HttpRuleParser.LF }; private readonly static string[] s_authenticationSchemes = { "Negotiate", "Digest", "Basic" }; // the order in which libcurl goes over authentication schemes private readonly static CURLAUTH[] s_authSchemePriorityOrder = { CURLAUTH.Negotiate, CURLAUTH.Digest, CURLAUTH.Basic }; private readonly static bool s_supportsAutomaticDecompression; private readonly static bool s_supportsSSL; private readonly static bool s_supportsHttp2Multiplexing; private readonly MultiAgent _agent = new MultiAgent(); private volatile bool _anyOperationStarted; private volatile bool _disposed; private IWebProxy _proxy = null; private ICredentials _serverCredentials = null; private ProxyUsePolicy _proxyPolicy = ProxyUsePolicy.UseDefaultProxy; private DecompressionMethods _automaticDecompression = HttpHandlerDefaults.DefaultAutomaticDecompression; private bool _preAuthenticate = HttpHandlerDefaults.DefaultPreAuthenticate; private CredentialCache _credentialCache = null; // protected by LockObject private CookieContainer _cookieContainer = new CookieContainer(); private bool _useCookie = HttpHandlerDefaults.DefaultUseCookies; private bool _automaticRedirection = HttpHandlerDefaults.DefaultAutomaticRedirection; private int _maxAutomaticRedirections = HttpHandlerDefaults.DefaultMaxAutomaticRedirections; private ClientCertificateOption _clientCertificateOption = HttpHandlerDefaults.DefaultClientCertificateOption; private object LockObject { get { return _agent; } } #endregion static CurlHandler() { // curl_global_init call handled by Interop.LibCurl's cctor int age; if (!Interop.Http.GetCurlVersionInfo( out age, out s_supportsSSL, out s_supportsAutomaticDecompression, out s_supportsHttp2Multiplexing)) { throw new InvalidOperationException(SR.net_http_unix_https_libcurl_no_versioninfo); } // Verify the version of curl we're using is new enough if (age < MinCurlAge) { throw new InvalidOperationException(SR.net_http_unix_https_libcurl_too_old); } } #region Properties internal bool AutomaticRedirection { get { return _automaticRedirection; } set { CheckDisposedOrStarted(); _automaticRedirection = value; } } internal bool SupportsProxy { get { return true; } } internal bool SupportsRedirectConfiguration { get { return true; } } internal bool UseProxy { get { return _proxyPolicy != ProxyUsePolicy.DoNotUseProxy; } set { CheckDisposedOrStarted(); _proxyPolicy = value ? ProxyUsePolicy.UseCustomProxy : ProxyUsePolicy.DoNotUseProxy; } } internal IWebProxy Proxy { get { return _proxy; } set { CheckDisposedOrStarted(); _proxy = value; } } internal ICredentials Credentials { get { return _serverCredentials; } set { _serverCredentials = value; } } internal ClientCertificateOption ClientCertificateOptions { get { return _clientCertificateOption; } set { CheckDisposedOrStarted(); _clientCertificateOption = value; } } internal bool SupportsAutomaticDecompression { get { return s_supportsAutomaticDecompression; } } internal DecompressionMethods AutomaticDecompression { get { return _automaticDecompression; } set { CheckDisposedOrStarted(); _automaticDecompression = value; } } internal bool PreAuthenticate { get { return _preAuthenticate; } set { CheckDisposedOrStarted(); _preAuthenticate = value; if (value && _credentialCache == null) { _credentialCache = new CredentialCache(); } } } internal bool UseCookie { get { return _useCookie; } set { CheckDisposedOrStarted(); _useCookie = value; } } internal CookieContainer CookieContainer { get { return _cookieContainer; } set { CheckDisposedOrStarted(); _cookieContainer = value; } } internal int MaxAutomaticRedirections { get { return _maxAutomaticRedirections; } set { if (value <= 0) { throw new ArgumentOutOfRangeException( "value", value, SR.Format(SR.net_http_value_must_be_greater_than, 0)); } CheckDisposedOrStarted(); _maxAutomaticRedirections = value; } } /// <summary> /// <b> UseDefaultCredentials is a no op on Unix </b> /// </summary> internal bool UseDefaultCredentials { get { return false; } set { } } #endregion protected override void Dispose(bool disposing) { _disposed = true; base.Dispose(disposing); } protected internal override Task<HttpResponseMessage> SendAsync( HttpRequestMessage request, CancellationToken cancellationToken) { if (request == null) { throw new ArgumentNullException("request", SR.net_http_handler_norequest); } if (request.RequestUri.Scheme == UriSchemeHttps) { if (!s_supportsSSL) { throw new PlatformNotSupportedException(SR.net_http_unix_https_support_unavailable_libcurl); } } else { Debug.Assert(request.RequestUri.Scheme == UriSchemeHttp, "HttpClient expected to validate scheme as http or https."); } if (request.Headers.TransferEncodingChunked.GetValueOrDefault() && (request.Content == null)) { throw new InvalidOperationException(SR.net_http_chunked_not_allowed_with_empty_content); } if (_useCookie && _cookieContainer == null) { throw new InvalidOperationException(SR.net_http_invalid_cookiecontainer); } CheckDisposed(); SetOperationStarted(); // Do an initial cancellation check to avoid initiating the async operation if // cancellation has already been requested. After this, we'll rely on CancellationToken.Register // to notify us of cancellation requests and shut down the operation if possible. if (cancellationToken.IsCancellationRequested) { return Task.FromCanceled<HttpResponseMessage>(cancellationToken); } // Create the easy request. This associates the easy request with this handler and configures // it based on the settings configured for the handler. var easy = new EasyRequest(this, request, cancellationToken); try { easy.InitializeCurl(); if (easy._requestContentStream != null) { easy._requestContentStream.Run(); } _agent.Queue(new MultiAgent.IncomingRequest { Easy = easy, Type = MultiAgent.IncomingRequestType.New }); } catch (Exception exc) { easy.FailRequest(exc); easy.Cleanup(); // no active processing remains, so we can cleanup } return easy.Task; } #region Private methods private void SetOperationStarted() { if (!_anyOperationStarted) { _anyOperationStarted = true; } } private KeyValuePair<NetworkCredential, CURLAUTH> GetNetworkCredentials(ICredentials credentials, Uri requestUri) { if (_preAuthenticate) { KeyValuePair<NetworkCredential, CURLAUTH> ncAndScheme; lock (LockObject) { Debug.Assert(_credentialCache != null, "Expected non-null credential cache"); ncAndScheme = GetCredentials(_credentialCache, requestUri); } if (ncAndScheme.Key != null) { return ncAndScheme; } } return GetCredentials(credentials, requestUri); } private void AddCredentialToCache(Uri serverUri, CURLAUTH authAvail, NetworkCredential nc) { lock (LockObject) { for (int i=0; i < s_authSchemePriorityOrder.Length; i++) { if ((authAvail & s_authSchemePriorityOrder[i]) != 0) { Debug.Assert(_credentialCache != null, "Expected non-null credential cache"); try { _credentialCache.Add(serverUri, s_authenticationSchemes[i], nc); } catch(ArgumentException) { //Ignore the case of key already present } } } } } private void AddResponseCookies(EasyRequest state, string cookieHeader) { if (!_useCookie) { return; } try { _cookieContainer.SetCookies(state._targetUri, cookieHeader); state.SetCookieOption(state._requestMessage.RequestUri); } catch (CookieException e) { string msg = string.Format("Malformed cookie: SetCookies Failed with {0}, server: {1}, cookie:{2}", e.Message, state._requestMessage.RequestUri, cookieHeader); VerboseTrace(msg); } } private static KeyValuePair<NetworkCredential, CURLAUTH> GetCredentials(ICredentials credentials, Uri requestUri) { NetworkCredential nc = null; CURLAUTH curlAuthScheme = CURLAUTH.None; if (credentials != null) { // we collect all the schemes that are accepted by libcurl for which there is a non-null network credential. // But CurlHandler works under following assumption: // for a given server, the credentials do not vary across authentication schemes. for (int i=0; i < s_authSchemePriorityOrder.Length; i++) { NetworkCredential networkCredential = credentials.GetCredential(requestUri, s_authenticationSchemes[i]); if (networkCredential != null) { curlAuthScheme |= s_authSchemePriorityOrder[i]; if (nc == null) { nc = networkCredential; } else if(!AreEqualNetworkCredentials(nc, networkCredential)) { throw new PlatformNotSupportedException(SR.net_http_unix_invalid_credential); } } } } VerboseTrace("curlAuthScheme = " + curlAuthScheme); return new KeyValuePair<NetworkCredential, CURLAUTH>(nc, curlAuthScheme); ; } private void CheckDisposed() { if (_disposed) { throw new ObjectDisposedException(GetType().FullName); } } private void CheckDisposedOrStarted() { CheckDisposed(); if (_anyOperationStarted) { throw new InvalidOperationException(SR.net_http_operation_started); } } private static void ThrowIfCURLEError(CURLcode error) { if (error != CURLcode.CURLE_OK) { var inner = new CurlException((int)error, isMulti: false); VerboseTrace(inner.Message); throw inner; } } private static void ThrowIfCURLMError(CURLMcode error) { if (error != CURLMcode.CURLM_OK) { string msg = CurlException.GetCurlErrorString((int)error, true); VerboseTrace(msg); switch (error) { case CURLMcode.CURLM_ADDED_ALREADY: case CURLMcode.CURLM_BAD_EASY_HANDLE: case CURLMcode.CURLM_BAD_HANDLE: case CURLMcode.CURLM_BAD_SOCKET: throw new ArgumentException(msg); case CURLMcode.CURLM_UNKNOWN_OPTION: throw new ArgumentOutOfRangeException(msg); case CURLMcode.CURLM_OUT_OF_MEMORY: throw new OutOfMemoryException(msg); case CURLMcode.CURLM_INTERNAL_ERROR: default: throw new CurlException((int)error, msg); } } } private static bool AreEqualNetworkCredentials(NetworkCredential credential1, NetworkCredential credential2) { Debug.Assert(credential1 != null && credential2 != null, "arguments are non-null in network equality check"); return credential1.UserName == credential2.UserName && credential1.Domain == credential2.Domain && string.Equals(credential1.Password, credential2.Password, StringComparison.Ordinal); } [Conditional(VerboseDebuggingConditional)] private static void VerboseTrace(string text = null, [CallerMemberName] string memberName = null, EasyRequest easy = null, MultiAgent agent = null) { // If we weren't handed a multi agent, see if we can get one from the EasyRequest if (agent == null && easy != null && easy._associatedMultiAgent != null) { agent = easy._associatedMultiAgent; } int? agentId = agent != null ? agent.RunningWorkerId : null; // Get an ID string that provides info about which MultiAgent worker and which EasyRequest this trace is about string ids = ""; if (agentId != null || easy != null) { ids = "(" + (agentId != null ? "M#" + agentId : "") + (agentId != null && easy != null ? ", " : "") + (easy != null ? "E#" + easy.Task.Id : "") + ")"; } // Create the message and trace it out string msg = string.Format("[{0, -30}]{1, -16}: {2}", memberName, ids, text); Interop.Sys.PrintF("%s\n", msg); } [Conditional(VerboseDebuggingConditional)] private static void VerboseTraceIf(bool condition, string text = null, [CallerMemberName] string memberName = null, EasyRequest easy = null) { if (condition) { VerboseTrace(text, memberName, easy, agent: null); } } private static Exception CreateHttpRequestException(Exception inner = null) { return new HttpRequestException(SR.net_http_client_execution_error, inner); } private static bool TryParseStatusLine(HttpResponseMessage response, string responseHeader, EasyRequest state) { if (!responseHeader.StartsWith(CurlResponseParseUtils.HttpPrefix, StringComparison.OrdinalIgnoreCase)) { return false; } // Clear the header if status line is recieved again. This signifies that there are multiple response headers (like in redirection). response.Headers.Clear(); response.Content.Headers.Clear(); CurlResponseParseUtils.ReadStatusLine(response, responseHeader); state._isRedirect = state._handler.AutomaticRedirection && (response.StatusCode == HttpStatusCode.Redirect || response.StatusCode == HttpStatusCode.RedirectKeepVerb || response.StatusCode == HttpStatusCode.RedirectMethod) ; return true; } private static void HandleRedirectLocationHeader(EasyRequest state, string locationValue) { Debug.Assert(state._isRedirect); Debug.Assert(state._handler.AutomaticRedirection); string location = locationValue.Trim(); //only for absolute redirects Uri forwardUri; if (Uri.TryCreate(location, UriKind.RelativeOrAbsolute, out forwardUri) && forwardUri.IsAbsoluteUri) { KeyValuePair<NetworkCredential, CURLAUTH> ncAndScheme = GetCredentials(state._handler.Credentials as CredentialCache, forwardUri); if (ncAndScheme.Key != null) { state.SetCredentialsOptions(ncAndScheme); } else { state.SetCurlOption(CURLoption.CURLOPT_USERNAME, IntPtr.Zero); state.SetCurlOption(CURLoption.CURLOPT_PASSWORD, IntPtr.Zero); } // reset proxy - it is possible that the proxy has different credentials for the new URI state.SetProxyOptions(forwardUri); if (state._handler._useCookie) { // reset cookies. state.SetCurlOption(CURLoption.CURLOPT_COOKIE, IntPtr.Zero); // set cookies again state.SetCookieOption(forwardUri); } state.SetRedirectUri(forwardUri); } // set the headers again. This is a workaround for libcurl's limitation in handling headers with empty values state.SetRequestHeaders(); } private static void SetChunkedModeForSend(HttpRequestMessage request) { bool chunkedMode = request.Headers.TransferEncodingChunked.GetValueOrDefault(); HttpContent requestContent = request.Content; Debug.Assert(requestContent != null, "request is null"); // Deal with conflict between 'Content-Length' vs. 'Transfer-Encoding: chunked' semantics. // libcurl adds a Tranfer-Encoding header by default and the request fails if both are set. if (requestContent.Headers.ContentLength.HasValue) { if (chunkedMode) { // Same behaviour as WinHttpHandler requestContent.Headers.ContentLength = null; } else { // Prevent libcurl from adding Transfer-Encoding header request.Headers.TransferEncodingChunked = false; } } else if (!chunkedMode) { // Make sure Transfer-Encoding: chunked header is set, // as we have content to send but no known length for it. request.Headers.TransferEncodingChunked = true; } } #endregion private enum ProxyUsePolicy { DoNotUseProxy = 0, // Do not use proxy. Ignores the value set in the environment. UseDefaultProxy = 1, // Do not set the proxy parameter. Use the value of environment variable, if any. UseCustomProxy = 2 // Use The proxy specified by the user. } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Runtime.InteropServices; using Microsoft.Win32.SafeHandles; internal static partial class Interop { internal static partial class Crypto { [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_EvpCipherCreate2")] internal static extern SafeEvpCipherCtxHandle EvpCipherCreate( IntPtr cipher, ref byte key, int keyLength, int effectivekeyLength, ref byte iv, int enc); [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_EvpCipherCreatePartial")] internal static extern SafeEvpCipherCtxHandle EvpCipherCreatePartial( IntPtr cipher); [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_EvpCipherSetKeyAndIV")] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool EvpCipherSetKeyAndIV( SafeEvpCipherCtxHandle ctx, ref byte key, ref byte iv, EvpCipherDirection direction); internal static void EvpCipherSetKeyAndIV( SafeEvpCipherCtxHandle ctx, ReadOnlySpan<byte> key, ReadOnlySpan<byte> iv, EvpCipherDirection direction) { if (!EvpCipherSetKeyAndIV( ctx, ref MemoryMarshal.GetReference(key), ref MemoryMarshal.GetReference(iv), direction)) { throw CreateOpenSslCryptographicException(); } } [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_EvpCipherSetGcmNonceLength")] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool CryptoNative_EvpCipherSetGcmNonceLength( SafeEvpCipherCtxHandle ctx, int nonceLength); internal static void EvpCipherSetGcmNonceLength(SafeEvpCipherCtxHandle ctx, int nonceLength) { if (!CryptoNative_EvpCipherSetGcmNonceLength(ctx, nonceLength)) { throw CreateOpenSslCryptographicException(); } } [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_EvpCipherSetCcmNonceLength")] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool CryptoNative_EvpCipherSetCcmNonceLength( SafeEvpCipherCtxHandle ctx, int nonceLength); internal static void EvpCipherSetCcmNonceLength(SafeEvpCipherCtxHandle ctx, int nonceLength) { if (!CryptoNative_EvpCipherSetCcmNonceLength(ctx, nonceLength)) { throw CreateOpenSslCryptographicException(); } } [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_EvpCipherDestroy")] internal static extern void EvpCipherDestroy(IntPtr ctx); [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_EvpCipherReset")] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool EvpCipherReset(SafeEvpCipherCtxHandle ctx); [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_EvpCipherCtxSetPadding")] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool EvpCipherCtxSetPadding(SafeEvpCipherCtxHandle x, int padding); [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_EvpCipherUpdate")] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool EvpCipherUpdate( SafeEvpCipherCtxHandle ctx, ref byte @out, out int outl, ref byte @in, int inl); internal static bool EvpCipherUpdate( SafeEvpCipherCtxHandle ctx, Span<byte> output, out int bytesWritten, ReadOnlySpan<byte> input) { return EvpCipherUpdate( ctx, ref MemoryMarshal.GetReference(output), out bytesWritten, ref MemoryMarshal.GetReference(input), input.Length); } internal static void EvpCipherSetInputLength(SafeEvpCipherCtxHandle ctx, int inputLength) { ref byte nullRef = ref MemoryMarshal.GetReference(Span<byte>.Empty); if (!EvpCipherUpdate(ctx, ref nullRef, out _, ref nullRef, inputLength)) { throw CreateOpenSslCryptographicException(); } } [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_EvpCipherFinalEx")] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool EvpCipherFinalEx( SafeEvpCipherCtxHandle ctx, ref byte outm, out int outl); internal static bool EvpCipherFinalEx( SafeEvpCipherCtxHandle ctx, Span<byte> output, out int bytesWritten) { return EvpCipherFinalEx(ctx, ref MemoryMarshal.GetReference(output), out bytesWritten); } [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_EvpCipherGetGcmTag")] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool EvpCipherGetGcmTag( SafeEvpCipherCtxHandle ctx, ref byte tag, int tagLength); internal static void EvpCipherGetGcmTag(SafeEvpCipherCtxHandle ctx, Span<byte> tag) { if (!EvpCipherGetGcmTag(ctx, ref MemoryMarshal.GetReference(tag), tag.Length)) { throw CreateOpenSslCryptographicException(); } } [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_EvpCipherSetGcmTag")] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool EvpCipherSetGcmTag( SafeEvpCipherCtxHandle ctx, ref byte tag, int tagLength); internal static void EvpCipherSetGcmTag(SafeEvpCipherCtxHandle ctx, ReadOnlySpan<byte> tag) { if (!EvpCipherSetGcmTag(ctx, ref MemoryMarshal.GetReference(tag), tag.Length)) { throw CreateOpenSslCryptographicException(); } } [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_EvpCipherGetCcmTag")] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool EvpCipherGetCcmTag( SafeEvpCipherCtxHandle ctx, ref byte tag, int tagLength); internal static void EvpCipherGetCcmTag(SafeEvpCipherCtxHandle ctx, Span<byte> tag) { if (!EvpCipherGetCcmTag(ctx, ref MemoryMarshal.GetReference(tag), tag.Length)) { throw CreateOpenSslCryptographicException(); } } [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_EvpCipherSetCcmTag")] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool EvpCipherSetCcmTag( SafeEvpCipherCtxHandle ctx, ref byte tag, int tagLength); internal static void EvpCipherSetCcmTag(SafeEvpCipherCtxHandle ctx, ReadOnlySpan<byte> tag) { if (!EvpCipherSetCcmTag(ctx, ref MemoryMarshal.GetReference(tag), tag.Length)) { throw CreateOpenSslCryptographicException(); } } internal static void EvpCipherSetCcmTagLength(SafeEvpCipherCtxHandle ctx, int tagLength) { ref byte nullRef = ref MemoryMarshal.GetReference(Span<byte>.Empty); if (!EvpCipherSetCcmTag(ctx, ref nullRef, tagLength)) { throw CreateOpenSslCryptographicException(); } } [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_EvpAes128Ecb")] internal static extern IntPtr EvpAes128Ecb(); [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_EvpAes128Cbc")] internal static extern IntPtr EvpAes128Cbc(); [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_EvpAes128Gcm")] internal static extern IntPtr EvpAes128Gcm(); [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_EvpAes128Ccm")] internal static extern IntPtr EvpAes128Ccm(); [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_EvpAes192Ecb")] internal static extern IntPtr EvpAes192Ecb(); [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_EvpAes192Cbc")] internal static extern IntPtr EvpAes192Cbc(); [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_EvpAes192Gcm")] internal static extern IntPtr EvpAes192Gcm(); [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_EvpAes192Ccm")] internal static extern IntPtr EvpAes192Ccm(); [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_EvpAes256Ecb")] internal static extern IntPtr EvpAes256Ecb(); [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_EvpAes256Cbc")] internal static extern IntPtr EvpAes256Cbc(); [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_EvpAes256Gcm")] internal static extern IntPtr EvpAes256Gcm(); [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_EvpAes256Ccm")] internal static extern IntPtr EvpAes256Ccm(); [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_EvpDesCbc")] internal static extern IntPtr EvpDesCbc(); [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_EvpDesEcb")] internal static extern IntPtr EvpDesEcb(); [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_EvpDes3Cbc")] internal static extern IntPtr EvpDes3Cbc(); [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_EvpDes3Ecb")] internal static extern IntPtr EvpDes3Ecb(); [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_EvpRC2Cbc")] internal static extern IntPtr EvpRC2Cbc(); [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_EvpRC2Ecb")] internal static extern IntPtr EvpRC2Ecb(); internal enum EvpCipherDirection : int { NoChange = -1, Decrypt = 0, Encrypt = 1, } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Threading.Tasks; using Newtonsoft.Json.Linq; using NuGet.Common; using NuGet.Packaging.Core; using NuGet.Versioning; namespace Sleet { public class FlatContainer : ISleetService, IPackageIdLookup { private readonly SleetContext _context; public string Name { get; } = nameof(FlatContainer); public FlatContainer(SleetContext context) { _context = context; } public Task ApplyOperationsAsync(SleetOperations changeContext) { // Remove existing files, this will typically result in marking the files // as deleted in the virtual file system since they have not been // downloaded. It is a fast/safe operation that must be done first. foreach (var toRemove in changeContext.ToRemove) { if (!toRemove.IsSymbolsPackage) { DeleteNupkg(toRemove.Identity); } } var tasks = new List<Func<Task>>(); // Copy in nupkgs/nuspec files // Ignore symbols packages tasks.AddRange(changeContext.ToAdd.Where(e => !e.IsSymbolsPackage).Select(e => new Func<Task>(() => AddPackageAsync(e)))); // Rebuild index files as needed var rebuildIds = changeContext.GetChangedIds(); tasks.AddRange(rebuildIds.Select(e => new Func<Task>(() => CreateIndexAsync(e, changeContext.UpdatedIndex.Packages)))); // Run all tasks return TaskUtils.RunAsync(tasks); } private void DeleteNupkg(PackageIdentity package) { // Delete nupkg var nupkgFile = _context.Source.Get(GetNupkgPath(package)); nupkgFile.Delete(_context.Log, _context.Token); // Nuspec var nuspecPath = $"{package.Id}.nuspec".ToLowerInvariant(); var nuspecFile = _context.Source.Get(GetZipFileUri(package, nuspecPath)); nuspecFile.Delete(_context.Log, _context.Token); // Icon var iconFile = _context.Source.Get(GetIconPath(package)); iconFile.Delete(_context.Log, _context.Token); } public Uri GetNupkgPath(PackageIdentity package) { return GetNupkgPath(_context, package); } public static Uri GetNupkgPath(SleetContext context, PackageIdentity package) { var id = package.Id; var version = package.Version.ToIdentityString(); return context.Source.GetPath($"/flatcontainer/{id}/{version}/{id}.{version}.nupkg".ToLowerInvariant()); } public Uri GetIconPath(PackageIdentity package) { return GetIconPath(_context, package); } public static Uri GetIconPath(SleetContext context, PackageIdentity package) { var id = package.Id; var version = package.Version.ToIdentityString(); return context.Source.GetPath($"/flatcontainer/{id}/{version}/icon".ToLowerInvariant()); } public Uri GetIndexUri(string id) { return _context.Source.GetPath($"/flatcontainer/{id}/index.json".ToLowerInvariant()); } public Uri GetZipFileUri(PackageIdentity package, string filePath) { var id = package.Id; var version = package.Version.ToIdentityString(); return _context.Source.GetPath($"/flatcontainer/{id}/{version}/{filePath}".ToLowerInvariant()); } public async Task<SortedSet<NuGetVersion>> GetVersions(string id) { var results = new SortedSet<NuGetVersion>(); var file = _context.Source.Get(GetIndexUri(id)); var json = await file.GetJsonOrNull(_context.Log, _context.Token); if (json?.Property("versions")?.Value is JArray versionArray) { results.UnionWith(versionArray.Select(s => NuGetVersion.Parse(s.ToString()))); } return results; } public JObject CreateIndexJson(SortedSet<NuGetVersion> versions) { var json = new JObject(); var versionArray = new JArray(); foreach (var version in versions) { versionArray.Add(new JValue(version.ToIdentityString())); } json.Add("versions", versionArray); return json; } public async Task<ISet<PackageIdentity>> GetPackagesByIdAsync(string packageId) { var results = new HashSet<PackageIdentity>(); var versions = await GetVersions(packageId); foreach (var version in versions) { results.Add(new PackageIdentity(packageId, version)); } return results; } public Task PreLoadAsync(SleetOperations operations) { return Task.FromResult(true); } private async Task CreateIndexAsync(string id, PackageSet packageSet) { // Get all versions var packages = await packageSet.GetPackagesByIdAsync(id); var versions = new SortedSet<NuGetVersion>(packages.Select(e => e.Version)); await CreateIndexAsync(id, versions); } private async Task CreateIndexAsync(string id, SortedSet<NuGetVersion> versions) { // Update index var indexFile = _context.Source.Get(GetIndexUri(id)); using (var timer = PerfEntryWrapper.CreateModifyTimer(indexFile, _context.PerfTracker)) { var indexJson = CreateIndexJson(versions); await indexFile.Write(indexJson, _context.Log, _context.Token); } } private Task AddPackageAsync(PackageInput packageInput) { return Task.WhenAll(new[] { AddNuspecAsync(packageInput), AddNupkgAsync(packageInput), AddIconAsync(packageInput) }); } private Task AddNupkgAsync(PackageInput packageInput) { // Add the nupkg by linking it instead of copying it to the local cache. var nupkgFile = _context.Source.Get(GetNupkgPath(packageInput.Identity)); nupkgFile.Link(packageInput.PackagePath, _context.Log, _context.Token); return Task.FromResult(true); } private async Task AddNuspecAsync(PackageInput packageInput) { // Add nuspec var nuspecPath = $"{packageInput.Identity.Id}.nuspec".ToLowerInvariant(); var entryFile = _context.Source.Get(GetZipFileUri(packageInput.Identity, nuspecPath)); using (var nuspecStream = packageInput.Nuspec.Xml.AsMemoryStream()) { await entryFile.Write(nuspecStream, _context.Log, _context.Token); } } private async Task AddIconAsync(PackageInput packageInput) { // Find icon path in package from nuspec var iconPath = packageInput.Nuspec.GetIcon(); if (!string.IsNullOrWhiteSpace(iconPath)) { iconPath = PathUtility.StripLeadingDirectorySeparators(iconPath).Trim(); using (var zip = packageInput.CreateZip()) { var entry = zip.GetEntry(iconPath); if (entry != null) { var entryFile = _context.Source.Get(GetIconPath(packageInput.Identity)); await entryFile.Write(entry.Open(), _context.Log, _context.Token); } } } } } }
using System; using NUnit.Framework; using Org.BouncyCastle.Crypto; using Org.BouncyCastle.Crypto.Digests; using Org.BouncyCastle.Crypto.Engines; using Org.BouncyCastle.Crypto.Encodings; using Org.BouncyCastle.Crypto.Parameters; using Org.BouncyCastle.Utilities.Encoders; using Org.BouncyCastle.Utilities.Test; namespace Org.BouncyCastle.Crypto.Tests { /** * standard vector test for SHA-256 from FIPS Draft 180-2. * * Note, the first two vectors are _not_ from the draft, the last three are. */ [TestFixture] public class Sha256DigestTest : ITest { // static private string testVec1 = ""; static private string resVec1 = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"; static private string testVec2 = "61"; static private string resVec2 = "ca978112ca1bbdcafac231b39a23dc4da786eff8147c4e72b9807785afee48bb"; static private string testVec3 = "616263"; static private string resVec3 = "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"; static private string testVec4 = "6162636462636465636465666465666765666768666768696768696a68696a6b696a6b6c6a6b6c6d6b6c6d6e6c6d6e6f6d6e6f706e6f7071"; static private string resVec4 = "248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1"; // 1 million 'a' static private string testVec5 = "61616161616161616161"; static private string resVec5 = "cdc76e5c9914fb9281a1c7e284d73e67f1809a48a497200e046d39ccc7112cd0"; public string Name { get { return "SHA256"; } } public ITestResult Perform() { IDigest digest = new Sha256Digest(); byte[] resBuf = new byte[digest.GetDigestSize()]; string resStr; // // test 1 // digest.DoFinal(resBuf, 0); resStr = Hex.ToHexString(resBuf); if (!resVec1.Equals(resStr)) { return new SimpleTestResult(false, "SHA-256 failing standard vector test 1" + SimpleTest.NewLine + " expected: " + resVec1 + SimpleTest.NewLine + " got : " + resStr); } // // test 2 // byte[] bytes = Hex.Decode(testVec2); digest.BlockUpdate(bytes, 0, bytes.Length); digest.DoFinal(resBuf, 0); resStr = Hex.ToHexString(resBuf); if (!resVec2.Equals(resStr)) { return new SimpleTestResult(false, "SHA-256 failing standard vector test 2" + SimpleTest.NewLine + " expected: " + resVec2 + SimpleTest.NewLine + " got : " + resStr); } // // test 3 // bytes = Hex.Decode(testVec3); digest.BlockUpdate(bytes, 0, bytes.Length); digest.DoFinal(resBuf, 0); resStr = Hex.ToHexString(resBuf); if (!resVec3.Equals(resStr)) { return new SimpleTestResult(false, "SHA-256 failing standard vector test 3" + SimpleTest.NewLine + " expected: " + resVec3 + SimpleTest.NewLine + " got : " + resStr); } // // test 4 // bytes = Hex.Decode(testVec4); digest.BlockUpdate(bytes, 0, bytes.Length); digest.DoFinal(resBuf, 0); resStr = Hex.ToHexString(resBuf); if (!resVec4.Equals(resStr)) { return new SimpleTestResult(false, "SHA-256 failing standard vector test 4" + SimpleTest.NewLine + " expected: " + resVec4 + SimpleTest.NewLine + " got : " + resStr); } // // test 5 // bytes = Hex.Decode(testVec4); digest.BlockUpdate(bytes, 0, bytes.Length/2); // clone the IDigest IDigest d = new Sha256Digest((Sha256Digest)digest); digest.BlockUpdate(bytes, bytes.Length/2, bytes.Length - bytes.Length/2); digest.DoFinal(resBuf, 0); resStr = Hex.ToHexString(resBuf); if (!resVec4.Equals(resStr)) { return new SimpleTestResult(false, "SHA-256 failing standard vector test 5" + SimpleTest.NewLine + " expected: " + resVec4 + SimpleTest.NewLine + " got : " + resStr); } d.BlockUpdate(bytes, bytes.Length/2, bytes.Length - bytes.Length/2); d.DoFinal(resBuf, 0); resStr = Hex.ToHexString(resBuf); if (!resVec4.Equals(resStr)) { return new SimpleTestResult(false, "SHA-256 failing standard vector test 5" + SimpleTest.NewLine + " expected: " + resVec4 + SimpleTest.NewLine + " got : " + resStr); } // test 6 bytes = Hex.Decode(testVec5); for ( int i = 0; i < 100000; i++ ) { digest.BlockUpdate(bytes, 0, bytes.Length); } digest.DoFinal(resBuf, 0); resStr = Hex.ToHexString(resBuf); if (!resVec5.Equals(resStr)) { return new SimpleTestResult(false, "SHA-256 failing standard vector test 6" + SimpleTest.NewLine + " expected: " + resVec5 + SimpleTest.NewLine + " got : " + resStr); } return new SimpleTestResult(true, Name + ": Okay"); } public static void Main( string[] args) { ITest test = new Sha256DigestTest(); ITestResult result = test.Perform(); Console.WriteLine(result); } [Test] public void TestFunction() { string resultText = Perform().ToString(); Assert.AreEqual(Name + ": Okay", resultText); } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace xStudio.Web.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
using RevitLookup.Views.Utils; namespace RevitLookup.Views { partial class ParamEnumView { /// <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 is not 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(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(ParamEnumView)); this.listView = new System.Windows.Forms.ListView(); this.m_colEnum = new System.Windows.Forms.ColumnHeader(); this.m_colVal = new System.Windows.Forms.ColumnHeader(); this.listViewContextMenuStrip = new System.Windows.Forms.ContextMenuStrip(this.components); this.copyToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.m_bnOk = new System.Windows.Forms.Button(); this.m_printDialog = new System.Windows.Forms.PrintDialog(); this.m_printDocument = new System.Drawing.Printing.PrintDocument(); this.m_printPreviewDialog = new System.Windows.Forms.PrintPreviewDialog(); this.toolStrip1 = new System.Windows.Forms.ToolStrip(); this.toolStripButton1 = new System.Windows.Forms.ToolStripButton(); this.toolStripButton2 = new System.Windows.Forms.ToolStripButton(); this.panel1 = new System.Windows.Forms.Panel(); this.listViewContextMenuStrip.SuspendLayout(); this.toolStrip1.SuspendLayout(); this.panel1.SuspendLayout(); this.SuspendLayout(); // // listView // this.listView.Anchor = ((System.Windows.Forms.AnchorStyles) ((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.listView.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {this.m_colEnum, this.m_colVal}); this.listView.ContextMenuStrip = this.listViewContextMenuStrip; this.listView.FullRowSelect = true; this.listView.GridLines = true; this.listView.HideSelection = false; this.listView.Location = new System.Drawing.Point(3, 3); this.listView.Name = "listView"; this.listView.ShowItemToolTips = true; this.listView.Size = new System.Drawing.Size(503, 422); this.listView.Sorting = System.Windows.Forms.SortOrder.Ascending; this.listView.TabIndex = 0; this.listView.UseCompatibleStateImageBehavior = false; this.listView.View = System.Windows.Forms.View.Details; this.listView.ColumnClick += new System.Windows.Forms.ColumnClickEventHandler(this.OnColumnClick); // // m_colEnum // this.m_colEnum.Text = "Enum"; this.m_colEnum.Width = 280; // // m_colVal // this.m_colVal.Text = "Value"; this.m_colVal.Width = 802; // // listViewContextMenuStrip // this.listViewContextMenuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {this.copyToolStripMenuItem}); this.listViewContextMenuStrip.Name = "listViewContextMenuStrip"; this.listViewContextMenuStrip.Size = new System.Drawing.Size(103, 26); // // copyToolStripMenuItem // this.copyToolStripMenuItem.Image = global::RevitLookup.Properties.Resources.Copy; this.copyToolStripMenuItem.Name = "copyToolStripMenuItem"; this.copyToolStripMenuItem.Size = new System.Drawing.Size(102, 22); this.copyToolStripMenuItem.Text = "Copy"; this.copyToolStripMenuItem.Click += new System.EventHandler(this.CopyToolStripMenuItem_Click); // // m_bnOk // this.m_bnOk.Anchor = ((System.Windows.Forms.AnchorStyles) (((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.m_bnOk.DialogResult = System.Windows.Forms.DialogResult.OK; this.m_bnOk.FlatStyle = System.Windows.Forms.FlatStyle.System; this.m_bnOk.Location = new System.Drawing.Point(3, 431); this.m_bnOk.Name = "m_bnOk"; this.m_bnOk.Size = new System.Drawing.Size(503, 23); this.m_bnOk.TabIndex = 1; this.m_bnOk.Text = "OK"; this.m_bnOk.UseVisualStyleBackColor = true; this.m_bnOk.Click += new System.EventHandler(this.ButtonOk_Click); // // m_printDialog // this.m_printDialog.Document = this.m_printDocument; this.m_printDialog.UseEXDialog = true; // // m_printDocument // this.m_printDocument.PrintPage += new System.Drawing.Printing.PrintPageEventHandler(this.PrintDocument_PrintPage); // // m_printPreviewDialog // this.m_printPreviewDialog.AutoScrollMargin = new System.Drawing.Size(0, 0); this.m_printPreviewDialog.AutoScrollMinSize = new System.Drawing.Size(0, 0); this.m_printPreviewDialog.ClientSize = new System.Drawing.Size(400, 300); this.m_printPreviewDialog.Document = this.m_printDocument; this.m_printPreviewDialog.Enabled = true; this.m_printPreviewDialog.Icon = ((System.Drawing.Icon) (resources.GetObject("m_printPreviewDialog.Icon"))); this.m_printPreviewDialog.Name = "m_printPreviewDialog"; this.m_printPreviewDialog.Visible = false; // // toolStrip1 // this.toolStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {this.toolStripButton1, this.toolStripButton2}); this.toolStrip1.Location = new System.Drawing.Point(0, 0); this.toolStrip1.Name = "toolStrip1"; this.toolStrip1.Size = new System.Drawing.Size(509, 25); this.toolStrip1.TabIndex = 2; this.toolStrip1.Text = "toolStrip1"; // // toolStripButton1 // this.toolStripButton1.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolStripButton1.Image = global::RevitLookup.Properties.Resources.Print; this.toolStripButton1.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolStripButton1.Name = "toolStripButton1"; this.toolStripButton1.Size = new System.Drawing.Size(23, 22); this.toolStripButton1.Text = "Print"; this.toolStripButton1.Click += new System.EventHandler(this.PrintMenuItem_Click); // // toolStripButton2 // this.toolStripButton2.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolStripButton2.Image = global::RevitLookup.Properties.Resources.Preview; this.toolStripButton2.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolStripButton2.Name = "toolStripButton2"; this.toolStripButton2.Size = new System.Drawing.Size(23, 22); this.toolStripButton2.Text = "Print Preview"; this.toolStripButton2.Click += new System.EventHandler(this.PrintPreviewMenuItem_Click); // // panel1 // this.panel1.Anchor = ((System.Windows.Forms.AnchorStyles) ((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.panel1.Controls.Add(this.m_bnOk); this.panel1.Controls.Add(this.listView); this.panel1.Location = new System.Drawing.Point(0, 28); this.panel1.Name = "panel1"; this.panel1.Size = new System.Drawing.Size(509, 458); this.panel1.TabIndex = 3; // // ParamEnumView // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.CancelButton = this.m_bnOk; this.ClientSize = new System.Drawing.Size(509, 486); this.Controls.Add(this.panel1); this.Controls.Add(this.toolStrip1); this.Icon = ((System.Drawing.Icon) (resources.GetObject("$this.Icon"))); this.MinimumSize = new System.Drawing.Size(525, 200); this.Name = "ParamEnumView"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; this.Text = "Enum Mappings"; this.listViewContextMenuStrip.ResumeLayout(false); this.toolStrip1.ResumeLayout(false); this.toolStrip1.PerformLayout(); this.panel1.ResumeLayout(false); this.ResumeLayout(false); this.PerformLayout(); } private System.Windows.Forms.Panel panel1; #endregion private System.Windows.Forms.ListView listView; private System.Windows.Forms.ColumnHeader m_colEnum; private System.Windows.Forms.ColumnHeader m_colVal; private System.Windows.Forms.Button m_bnOk; private ListViewColumnSorter colSorter; private System.Windows.Forms.ContextMenuStrip listViewContextMenuStrip; private System.Windows.Forms.ToolStripMenuItem copyToolStripMenuItem; private System.Windows.Forms.PrintDialog m_printDialog; private System.Drawing.Printing.PrintDocument m_printDocument; private System.Windows.Forms.PrintPreviewDialog m_printPreviewDialog; private System.Windows.Forms.ToolStrip toolStrip1; private System.Windows.Forms.ToolStripButton toolStripButton1; private System.Windows.Forms.ToolStripButton toolStripButton2; } }
using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.Serialization; using System.Timers; using System.Xml; using System.Xml.Serialization; using UnityEngine; using ws.winx.devices; using ws.winx.drivers; using ws.winx.input; using ws.winx.input.states; using ws.winx.platform; using ws.winx.unity; using ws.winx.utils; using UnityEngine.Events; using UnityEngine.Serialization; namespace ws.winx.input.components{ [RequireComponent(typeof(UserInterfaceWindow))] public class InputComponent : MonoBehaviour { // // Fields // //TODO Maybe // public TextAsset profileList; // // public TextAsset[] profiles; public string settingsFileName="InputSettings.xml"; public DeviceProfiles profiles; [FormerlySerializedAs ("onLoad"), UnityEngine.SerializeField] private UnityEvent m_onLoad = new UnityEvent (); // // Nested Types // [Serializable] public class InputComponentEvent : UnityEvent { } // // Properties // public UnityEvent onLoad { get { return this.m_onLoad; } set { this.m_onLoad = value; } } UserInterfaceWindow ui; // Use this for initialization void Start () { if (String.IsNullOrEmpty (settingsFileName)) { Debug.LogError("Please add settings(.xml or .bin) fileName from StreamingAssets"); return; } ui= this.GetComponent<UserInterfaceWindow>(); //supporting devices with custom drivers //When you add them add specialized first then XInputDriver then wide range supporting drivers like WinMM or OSXDriver //supporting devices with custom drivers //When you add them add specialized first then XInputDriver then wide range supporting drivers WinMM or OSXDriver #if (UNITY_STANDALONE_WIN) InputManager.AddDriver(new ThrustMasterDriver()); //InputManager.AddDriver(new WiiDriver()); InputManager.AddDriver(new XInputDriver()); //change default driver //InputManager.hidInterface.defaultDriver=new UnityDriver(); #endif #if (UNITY_STANDALONE_OSX) InputManager.AddDriver(new ThrustMasterDriver()); InputManager.AddDriver(new XInputDriver()); //change default driver //InputManager.hidInterface.defaultDriver=new UnityDriver(); #endif #if (UNITY_STANDALONE_ANDROID) InputManager.AddDriver(new ThrustMasterDriver()); InputManager.AddDriver(new XInputDriver()); #endif if (profiles == null) InputManager.hidInterface.LoadProfiles ("DeviceProfiles"); else InputManager.hidInterface.SetProfiles (profiles); InputManager.hidInterface.Enumerate(); //if you want to load some states from .xml and add custom manually first load settings xml //!!!Application.streamingAssetPath gives "Raw" folder in web player #if (UNITY_STANDALONE || UNITY_EDITOR ) && !UNITY_WEBPLAYER && !UNITY_ANDROID //UnityEngine.Debug.Log("Standalone"); if (ui != null && !String.IsNullOrEmpty (settingsFileName)) {//settingsXML would trigger internal loading mechanism (only for testing) //load settings from external file ui.settings=InputManager.loadSettings(Path.Combine(Application.streamingAssetsPath, settingsFileName)); // ui.settings=InputManager.loadSettingsFromXMLText(Path.Combine(Application.streamingAssetsPath,settingsFileName)); //dispatch Event this.m_onLoad.Invoke(); } #endif #region Load InputSettings.xml Android #if UNITY_ANDROID Loader request = new Loader(); if (Application.platform == RuntimePlatform.Android) { if (File.Exists(Application.persistentDataPath + "/" + settingsFileName)) { if (ui != null) { Debug.Log("Game>> Try to load from " + Application.persistentDataPath); ui.settings=InputManager.loadSettings(Application.persistentDataPath + "/" + settingsFileName); //dispatch load complete this.m_onLoad.Invoke(); return; } } else {// content of StreamingAssets get packed inside .APK and need to be load with WWW request.Add(Path.Combine(Application.streamingAssetsPath, "InputSettings.xml")); request.Add(Path.Combine(Application.streamingAssetsPath, "profiles.txt")); request.Add(Path.Combine(Application.streamingAssetsPath, "xbox360_drd.txt")); //.... //unpack everything in presistentDataPath } request.LoadComplete += new EventHandler<LoaderEvtArgs<List<WWW>>>(onLoadComplete); request.Error += new EventHandler<LoaderEvtArgs<String>>(onLoadError); request.LoadItemComplete += new EventHandler<LoaderEvtArgs<WWW>>(onLoadItemComplete); request.load(); } else //TARGET=ANDROID but playing in EDITOR => use Standalone setup { if (ui != null) {//settingsXML would trigger internal loading mechanism (only for testing) InputManager.loadSettings(Path.Combine(Application.streamingAssetsPath, settingsFileName)); ui.settings = InputManager.Settings; } } #endif #endregion #if(UNITY_WEBPLAYER || UNITY_EDITOR) && !UNITY_STANDALONE && !UNITY_ANDROID Loader request = new Loader(); //UNITY_WEBPLAYER: Application.dataPath "http://localhost/appfolder/" request.Add(Application.dataPath+"/StreamingAssets/"+settingsFileName); request.LoadComplete += new EventHandler<LoaderEvtArgs<List<WWW>>>(onLoadComplete); request.Error += new EventHandler<LoaderEvtArgs<String>>(onLoadError); request.LoadItemComplete += new EventHandler<LoaderEvtArgs<WWW>>(onLoadItemComplete); request.load(); #endif } #if (UNITY_WEBPLAYER || UNITY_EDITOR || UNITY_ANDROID) && !UNITY_STANDALONE void onLoadComplete(object sender, LoaderEvtArgs<List<WWW>> args) { // Debug.Log(((List<WWW>)args.data).ElementAt(0).text); if (System.Threading.Thread.CurrentThread.ManagedThreadId != 1) return; //UnityEngine.Debug.Log("WebPlayer " + Path.Combine(Path.Combine(Application.dataPath, "StreamingAssets"), "InputSettings.xml")); if (ui != null) { InputManager.loadSettingsFromText(args.data.ElementAt(0).text); ui.settings = InputManager.Settings; } //dispatch load complete this.m_onLoad.Invoke(); } void onLoadItemComplete(object sender, LoaderEvtArgs<WWW> args) { // Debug.Log(args.data.text); } void onLoadError(object sender, LoaderEvtArgs<String> args) { Debug.Log(args.data); } #endif // Update is called once per frame void Update () { InputManager.dispatchEvent(); } void OnGUI(){ if (ui != null && ui.settings != null && GUI.Button (new Rect (0, 0, 100, 30), "Settings")) ui.enabled = !ui.enabled; } /// <summary> /// DONT FORGET TO CLEAN AFTER YOURSELF /// </summary> void OnDestroy() { InputManager.Dispose(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Buffers; using System.IO.Pipelines; using System.Text; using Microsoft.Extensions.Primitives; namespace Microsoft.AspNetCore.WebUtilities { public class FormPipeReaderTests { [Fact] public async Task ReadFormAsync_EmptyKeyAtEndAllowed() { var bodyPipe = await MakePipeReader("=bar"); var formCollection = await ReadFormAsync(new FormPipeReader(bodyPipe)); Assert.Equal("bar", formCollection[""].ToString()); } [Fact] public async Task ReadFormAsync_EmptyKeyWithAdditionalEntryAllowed() { var bodyPipe = await MakePipeReader("=bar&baz=2"); var formCollection = await ReadFormAsync(new FormPipeReader(bodyPipe)); Assert.Equal("bar", formCollection[""].ToString()); Assert.Equal("2", formCollection["baz"].ToString()); } [Fact] public async Task ReadFormAsync_EmptyValueAtEndAllowed() { var bodyPipe = await MakePipeReader("foo="); var formCollection = await ReadFormAsync(new FormPipeReader(bodyPipe)); Assert.Equal("", formCollection["foo"].ToString()); } [Fact] public async Task ReadFormAsync_EmptyValueWithoutEqualsAtEndAllowed() { var bodyPipe = await MakePipeReader("foo"); var formCollection = await ReadFormAsync(new FormPipeReader(bodyPipe)); Assert.Equal("", formCollection["foo"].ToString()); } [Fact] public async Task ReadFormAsync_EmptyValueWithAdditionalEntryAllowed() { var bodyPipe = await MakePipeReader("foo=&baz=2"); var formCollection = await ReadFormAsync(new FormPipeReader(bodyPipe)); Assert.Equal("", formCollection["foo"].ToString()); Assert.Equal("2", formCollection["baz"].ToString()); } [Fact] public async Task ReadFormAsync_EmptyValueWithoutEqualsWithAdditionalEntryAllowed() { var bodyPipe = await MakePipeReader("foo&baz=2"); var formCollection = await ReadFormAsync(new FormPipeReader(bodyPipe)); Assert.Equal("", formCollection["foo"].ToString()); Assert.Equal("2", formCollection["baz"].ToString()); } [Fact] public async Task ReadFormAsync_ValueContainsInvalidCharacters_Throw() { var bodyPipe = await MakePipeReader("%00"); var exception = await Assert.ThrowsAsync<InvalidDataException>( () => ReadFormAsync(new FormPipeReader(bodyPipe))); Assert.Equal("The form value contains invalid characters.", exception.Message); Assert.IsType<InvalidOperationException>(exception.InnerException); } [Fact] public async Task ReadFormAsync_ValueCountLimitMet_Success() { var bodyPipe = await MakePipeReader("foo=1&bar=2&baz=3"); var formCollection = await ReadFormAsync(new FormPipeReader(bodyPipe) { ValueCountLimit = 3 }); Assert.Equal("1", formCollection["foo"].ToString()); Assert.Equal("2", formCollection["bar"].ToString()); Assert.Equal("3", formCollection["baz"].ToString()); Assert.Equal(3, formCollection.Count); } [Fact] public async Task ReadFormAsync_ValueCountLimitExceeded_Throw() { var content = "foo=1&baz=2&bar=3&baz=4&baf=5"; var bodyPipe = await MakePipeReader(content); var exception = await Assert.ThrowsAsync<InvalidDataException>( () => ReadFormAsync(new FormPipeReader(bodyPipe) { ValueCountLimit = 3 })); Assert.Equal("Form value count limit 3 exceeded.", exception.Message); // The body pipe is still readable and has not advanced. var readResult = await bodyPipe.ReadAsync(); Assert.Equal(Encoding.UTF8.GetBytes(content), readResult.Buffer.ToArray()); } [Fact] public async Task ReadFormAsync_ValueCountLimitExceededSameKey_Throw() { var content = "baz=1&baz=2&baz=3&baz=4"; var bodyPipe = await MakePipeReader(content); var exception = await Assert.ThrowsAsync<InvalidDataException>( () => ReadFormAsync(new FormPipeReader(bodyPipe) { ValueCountLimit = 3 })); Assert.Equal("Form value count limit 3 exceeded.", exception.Message); // The body pipe is still readable and has not advanced. var readResult = await bodyPipe.ReadAsync(); Assert.Equal(Encoding.UTF8.GetBytes(content), readResult.Buffer.ToArray()); } [Fact] public async Task ReadFormAsync_KeyLengthLimitMet_Success() { var bodyPipe = await MakePipeReader("fooooooooo=1&bar=2&baz=3&baz=4"); var formCollection = await ReadFormAsync(new FormPipeReader(bodyPipe) { KeyLengthLimit = 10 }); Assert.Equal("1", formCollection["fooooooooo"].ToString()); Assert.Equal("2", formCollection["bar"].ToString()); Assert.Equal("3,4", formCollection["baz"].ToString()); Assert.Equal(3, formCollection.Count); } [Fact] public async Task ReadFormAsync_KeyLengthLimitExceeded_Throw() { var content = "foo=1&baz12345678=2"; var bodyPipe = await MakePipeReader(content); var exception = await Assert.ThrowsAsync<InvalidDataException>( () => ReadFormAsync(new FormPipeReader(bodyPipe) { KeyLengthLimit = 10 })); Assert.Equal("Form key length limit 10 exceeded.", exception.Message); // The body pipe is still readable and has not advanced. var readResult = await bodyPipe.ReadAsync(); Assert.Equal(Encoding.UTF8.GetBytes(content), readResult.Buffer.ToArray()); } [Fact] public async Task ReadFormAsync_ValueLengthLimitMet_Success() { var bodyPipe = await MakePipeReader("foo=1&bar=1234567890&baz=3&baz=4"); var formCollection = await ReadFormAsync(new FormPipeReader(bodyPipe) { ValueLengthLimit = 10 }); Assert.Equal("1", formCollection["foo"].ToString()); Assert.Equal("1234567890", formCollection["bar"].ToString()); Assert.Equal("3,4", formCollection["baz"].ToString()); Assert.Equal(3, formCollection.Count); } [Fact] public async Task ReadFormAsync_ValueLengthLimitExceeded_Throw() { var content = "foo=1&baz=12345678901"; var bodyPipe = await MakePipeReader(content); var exception = await Assert.ThrowsAsync<InvalidDataException>( () => ReadFormAsync(new FormPipeReader(bodyPipe) { ValueLengthLimit = 10 })); Assert.Equal("Form value length limit 10 exceeded.", exception.Message); // The body pipe is still readable and has not advanced. var readResult = await bodyPipe.ReadAsync(); Assert.Equal(Encoding.UTF8.GetBytes(content), readResult.Buffer.ToArray()); } [Fact] public async Task ReadFormAsync_ValueLengthLimitExceededAcrossBufferBoundary_Throw() { Pipe bodyPipe = new Pipe(); var content1 = "foo=1&baz=1234567890"; var content2 = "1"; await bodyPipe.Writer.WriteAsync(Encoding.UTF8.GetBytes(content1)); await bodyPipe.Writer.FlushAsync(); var readTask = Assert.ThrowsAsync<InvalidDataException>( () => ReadFormAsync(new FormPipeReader(bodyPipe.Reader) { ValueLengthLimit = 10 })); await bodyPipe.Writer.WriteAsync(Encoding.UTF8.GetBytes(content2)); bodyPipe.Writer.Complete(); var exception = await readTask; Assert.Equal("Form value length limit 10 exceeded.", exception.Message); // The body pipe is still readable and has not advanced. var readResult = await bodyPipe.Reader.ReadAsync(); Assert.Equal(Encoding.UTF8.GetBytes("baz=12345678901"), readResult.Buffer.ToArray()); } // https://en.wikipedia.org/wiki/Percent-encoding [Theory] [InlineData("++=hello", " ", "hello")] [InlineData("a=1+1", "a", "1 1")] [InlineData("%22%25%2D%2E%3C%3E%5C%5E%5F%60%7B%7C%7D%7E=%22%25%2D%2E%3C%3E%5C%5E%5F%60%7B%7C%7D%7E", "\"%-.<>\\^_`{|}~", "\"%-.<>\\^_`{|}~")] [InlineData("a=%41", "a", "A")] // ascii encoded hex [InlineData("a=%C3%A1", "a", "\u00e1")] // utf8 code points [InlineData("a=%u20AC", "a", "%u20AC")] // utf16 not supported public async Task ReadForm_Decoding(string formData, string key, string expectedValue) { var bodyPipe = await MakePipeReader(text: formData); var form = await ReadFormAsync(new FormPipeReader(bodyPipe)); Assert.Equal(expectedValue, form[key]); } [Theory] [MemberData(nameof(Encodings))] public void TryParseFormValues_SingleSegmentWorks(Encoding encoding) { var readOnlySequence = new ReadOnlySequence<byte>(encoding.GetBytes("foo=bar&baz=boo")); KeyValueAccumulator accumulator = default; var formReader = new FormPipeReader(null!, encoding); formReader.ParseFormValues(ref readOnlySequence, ref accumulator, isFinalBlock: true); Assert.True(readOnlySequence.IsEmpty); Assert.Equal(2, accumulator.KeyCount); var dict = accumulator.GetResults(); Assert.Equal("bar", dict["foo"]); Assert.Equal("boo", dict["baz"]); } [Theory] [MemberData(nameof(Encodings))] public void TryParseFormValues_Works(Encoding encoding) { var readOnlySequence = ReadOnlySequenceFactory.SingleSegmentFactory.CreateWithContent(encoding.GetBytes("foo=bar&baz=boo&t=")); KeyValueAccumulator accumulator = default; var formReader = new FormPipeReader(null!, encoding); formReader.ParseFormValues(ref readOnlySequence, ref accumulator, isFinalBlock: true); Assert.True(readOnlySequence.IsEmpty); Assert.Equal(3, accumulator.KeyCount); var dict = accumulator.GetResults(); Assert.Equal("bar", dict["foo"]); Assert.Equal("boo", dict["baz"]); Assert.Equal("", dict["t"]); } [Theory] [MemberData(nameof(Encodings))] public void TryParseFormValues_LimitsCanBeLarge(Encoding encoding) { var readOnlySequence = ReadOnlySequenceFactory.SingleSegmentFactory.CreateWithContent(encoding.GetBytes("foo=bar&baz=boo&t=")); KeyValueAccumulator accumulator = default; var formReader = new FormPipeReader(null!, encoding); formReader.KeyLengthLimit = int.MaxValue; formReader.ValueLengthLimit = int.MaxValue; formReader.ParseFormValues(ref readOnlySequence, ref accumulator, isFinalBlock: false); formReader.ParseFormValues(ref readOnlySequence, ref accumulator, isFinalBlock: true); Assert.True(readOnlySequence.IsEmpty); Assert.Equal(3, accumulator.KeyCount); var dict = accumulator.GetResults(); Assert.Equal("bar", dict["foo"]); Assert.Equal("boo", dict["baz"]); Assert.Equal("", dict["t"]); } [Theory] [MemberData(nameof(Encodings))] public void TryParseFormValues_SplitAcrossSegmentsWorks(Encoding encoding) { var readOnlySequence = ReadOnlySequenceFactory.SegmentPerByteFactory.CreateWithContent(encoding.GetBytes("foo=bar&baz=boo&t=")); KeyValueAccumulator accumulator = default; var formReader = new FormPipeReader(null!, encoding); formReader.ParseFormValues(ref readOnlySequence, ref accumulator, isFinalBlock: true); Assert.True(readOnlySequence.IsEmpty); Assert.Equal(3, accumulator.KeyCount); var dict = accumulator.GetResults(); Assert.Equal("bar", dict["foo"]); Assert.Equal("boo", dict["baz"]); Assert.Equal("", dict["t"]); } [Theory] [MemberData(nameof(Encodings))] public void TryParseFormValues_SplitAcrossSegmentsWorks_LimitsCanBeLarge(Encoding encoding) { var readOnlySequence = ReadOnlySequenceFactory.SegmentPerByteFactory.CreateWithContent(encoding.GetBytes("foo=bar&baz=boo&t=")); KeyValueAccumulator accumulator = default; var formReader = new FormPipeReader(null!, encoding); formReader.KeyLengthLimit = int.MaxValue; formReader.ValueLengthLimit = int.MaxValue; formReader.ParseFormValues(ref readOnlySequence, ref accumulator, isFinalBlock: false); formReader.ParseFormValues(ref readOnlySequence, ref accumulator, isFinalBlock: true); Assert.True(readOnlySequence.IsEmpty); Assert.Equal(3, accumulator.KeyCount); var dict = accumulator.GetResults(); Assert.Equal("bar", dict["foo"]); Assert.Equal("boo", dict["baz"]); Assert.Equal("", dict["t"]); } [Theory] [MemberData(nameof(Encodings))] public void TryParseFormValues_MultiSegmentWithArrayPoolAcrossSegmentsWorks(Encoding encoding) { var readOnlySequence = ReadOnlySequenceFactory.SegmentPerByteFactory.CreateWithContent(encoding.GetBytes("foo=bar&baz=bo" + new string('a', 128))); KeyValueAccumulator accumulator = default; var formReader = new FormPipeReader(null!, encoding); formReader.ParseFormValues(ref readOnlySequence, ref accumulator, isFinalBlock: true); Assert.True(readOnlySequence.IsEmpty); Assert.Equal(2, accumulator.KeyCount); var dict = accumulator.GetResults(); Assert.Equal("bar", dict["foo"]); Assert.Equal("bo" + new string('a', 128), dict["baz"]); } [Theory] [MemberData(nameof(Encodings))] public void TryParseFormValues_MultiSegmentSplitAcrossSegmentsWithPlusesWorks(Encoding encoding) { var readOnlySequence = ReadOnlySequenceFactory.SegmentPerByteFactory.CreateWithContent(encoding.GetBytes("+++=+++&++++=++++&+=")); KeyValueAccumulator accumulator = default; var formReader = new FormPipeReader(null!, encoding); formReader.ParseFormValues(ref readOnlySequence, ref accumulator, isFinalBlock: true); Assert.True(readOnlySequence.IsEmpty); Assert.Equal(3, accumulator.KeyCount); var dict = accumulator.GetResults(); Assert.Equal(" ", dict[" "]); Assert.Equal(" ", dict[" "]); Assert.Equal("", dict[" "]); } [Theory] [MemberData(nameof(Encodings))] public void TryParseFormValues_DecodedPlusesWorks(Encoding encoding) { var readOnlySequence = ReadOnlySequenceFactory.SingleSegmentFactory.CreateWithContent(encoding.GetBytes("++%2B=+++%2B&++++=++++&+=")); KeyValueAccumulator accumulator = default; var formReader = new FormPipeReader(null!, encoding); formReader.ParseFormValues(ref readOnlySequence, ref accumulator, isFinalBlock: true); Assert.True(readOnlySequence.IsEmpty); Assert.Equal(3, accumulator.KeyCount); var dict = accumulator.GetResults(); Assert.Equal(" ", dict[" "]); Assert.Equal(" +", dict[" +"]); Assert.Equal("", dict[" "]); } [Theory] [MemberData(nameof(Encodings))] public void TryParseFormValues_SplitAcrossSegmentsThatNeedDecodingWorks(Encoding encoding) { var readOnlySequence = ReadOnlySequenceFactory.SegmentPerByteFactory.CreateWithContent(encoding.GetBytes("\"%-.<>\\^_`{|}~=\"%-.<>\\^_`{|}~&\"%-.<>\\^_`{|}=wow")); KeyValueAccumulator accumulator = default; var formReader = new FormPipeReader(null!, encoding); formReader.ParseFormValues(ref readOnlySequence, ref accumulator, isFinalBlock: true); Assert.True(readOnlySequence.IsEmpty); Assert.Equal(2, accumulator.KeyCount); var dict = accumulator.GetResults(); Assert.Equal("\"%-.<>\\^_`{|}~", dict["\"%-.<>\\^_`{|}~"]); Assert.Equal("wow", dict["\"%-.<>\\^_`{|}"]); } [Fact] public void TryParseFormValues_MultiSegmentFastPathWorks() { var readOnlySequence = ReadOnlySequenceFactory.CreateSegments(Encoding.UTF8.GetBytes("foo=bar&"), Encoding.UTF8.GetBytes("baz=boo")); KeyValueAccumulator accumulator = default; var formReader = new FormPipeReader(null!); formReader.ParseFormValues(ref readOnlySequence, ref accumulator, isFinalBlock: true); Assert.True(readOnlySequence.IsEmpty); Assert.Equal(2, accumulator.KeyCount); var dict = accumulator.GetResults(); Assert.Equal("bar", dict["foo"]); Assert.Equal("boo", dict["baz"]); } [Fact] public void TryParseFormValues_ExceedKeyLengthThrows() { var readOnlySequence = ReadOnlySequenceFactory.SingleSegmentFactory.CreateWithContent(Encoding.UTF8.GetBytes("foo=bar&baz=boo&t=")); KeyValueAccumulator accumulator = default; var formReader = new FormPipeReader(null!); formReader.KeyLengthLimit = 2; var exception = Assert.Throws<InvalidDataException>(() => formReader.ParseFormValues(ref readOnlySequence, ref accumulator, isFinalBlock: true)); Assert.Equal("Form key length limit 2 exceeded.", exception.Message); } [Fact] public void TryParseFormValues_ExceedKeyLengthThrowsInSplitSegment() { var readOnlySequence = ReadOnlySequenceFactory.CreateSegments(Encoding.UTF8.GetBytes("fo=bar&ba"), Encoding.UTF8.GetBytes("z=boo&t=")); KeyValueAccumulator accumulator = default; var formReader = new FormPipeReader(null!); formReader.KeyLengthLimit = 2; var exception = Assert.Throws<InvalidDataException>(() => formReader.ParseFormValues(ref readOnlySequence, ref accumulator, isFinalBlock: true)); Assert.Equal("Form key length limit 2 exceeded.", exception.Message); } [Fact] public void TryParseFormValues_ExceedValueLengthThrows() { var readOnlySequence = ReadOnlySequenceFactory.CreateSegments(Encoding.UTF8.GetBytes("foo=bar&baz=boo&t=")); KeyValueAccumulator accumulator = default; var formReader = new FormPipeReader(null!); formReader.ValueLengthLimit = 2; var exception = Assert.Throws<InvalidDataException>(() => formReader.ParseFormValues(ref readOnlySequence, ref accumulator, isFinalBlock: true)); Assert.Equal("Form value length limit 2 exceeded.", exception.Message); } [Fact] public void TryParseFormValues_ExceedValueLengthThrowsInSplitSegment() { var readOnlySequence = ReadOnlySequenceFactory.CreateSegments(Encoding.UTF8.GetBytes("foo=ba&baz=bo"), Encoding.UTF8.GetBytes("o&t=")); KeyValueAccumulator accumulator = default; var formReader = new FormPipeReader(null!); formReader.ValueLengthLimit = 2; var exception = Assert.Throws<InvalidDataException>(() => formReader.ParseFormValues(ref readOnlySequence, ref accumulator, isFinalBlock: true)); Assert.Equal("Form value length limit 2 exceeded.", exception.Message); } [Fact] public void TryParseFormValues_ExceedKeyLengthThrowsInSplitSegmentEnd() { var readOnlySequence = ReadOnlySequenceFactory.CreateSegments(Encoding.UTF8.GetBytes("foo=ba&baz=bo"), Encoding.UTF8.GetBytes("o&asdfasdfasd=")); KeyValueAccumulator accumulator = default; var formReader = new FormPipeReader(null!); formReader.KeyLengthLimit = 10; var exception = Assert.Throws<InvalidDataException>(() => formReader.ParseFormValues(ref readOnlySequence, ref accumulator, isFinalBlock: true)); Assert.Equal("Form key length limit 10 exceeded.", exception.Message); } [Fact] public void TryParseFormValues_ExceedValueLengthThrowsInSplitSegmentEnd() { var readOnlySequence = ReadOnlySequenceFactory.CreateSegments(Encoding.UTF8.GetBytes("foo=ba&baz=bo"), Encoding.UTF8.GetBytes("o&t=asdfasdfasd")); KeyValueAccumulator accumulator = default; var formReader = new FormPipeReader(null!); formReader.ValueLengthLimit = 10; var exception = Assert.Throws<InvalidDataException>(() => formReader.ParseFormValues(ref readOnlySequence, ref accumulator, isFinalBlock: true)); Assert.Equal("Form value length limit 10 exceeded.", exception.Message); } [Fact] public async Task ResetPipeWorks() { // Same test that is in the benchmark var pipe = new Pipe(); var bytes = Encoding.UTF8.GetBytes("foo=bar&baz=boo"); for (var i = 0; i < 1000; i++) { pipe.Writer.Write(bytes); pipe.Writer.Complete(); var formReader = new FormPipeReader(pipe.Reader); await formReader.ReadFormAsync(); pipe.Reader.Complete(); pipe.Reset(); } } [Theory] [MemberData(nameof(IncompleteFormKeys))] public void ParseFormWithIncompleteKeyWhenIsFinalBlockSucceeds(ReadOnlySequence<byte> readOnlySequence) { KeyValueAccumulator accumulator = default; var formReader = new FormPipeReader(null!) { KeyLengthLimit = 3 }; formReader.ParseFormValues(ref readOnlySequence, ref accumulator, isFinalBlock: true); Assert.True(readOnlySequence.IsEmpty); IDictionary<string, StringValues> values = accumulator.GetResults(); Assert.Contains("fo", values); Assert.Equal("bar", values["fo"]); Assert.Contains("ba", values); Assert.Equal("", values["ba"]); } [Theory] [MemberData(nameof(IncompleteFormValues))] public void ParseFormWithIncompleteValueWhenIsFinalBlockSucceeds(ReadOnlySequence<byte> readOnlySequence) { KeyValueAccumulator accumulator = default; var formReader = new FormPipeReader(null!) { ValueLengthLimit = 3 }; formReader.ParseFormValues(ref readOnlySequence, ref accumulator, isFinalBlock: true); Assert.True(readOnlySequence.IsEmpty); IDictionary<string, StringValues> values = accumulator.GetResults(); Assert.Contains("fo", values); Assert.Equal("bar", values["fo"]); Assert.Contains("b", values); Assert.Equal("", values["b"]); } [Fact] public async Task ReadFormAsync_AccumulatesEmptyKeys() { var bodyPipe = await MakePipeReader("&&&"); var formCollection = await ReadFormAsync(new FormPipeReader(bodyPipe)); Assert.Single(formCollection); } public static TheoryData<ReadOnlySequence<byte>> IncompleteFormKeys => new TheoryData<ReadOnlySequence<byte>> { { ReadOnlySequenceFactory.CreateSegments(Encoding.UTF8.GetBytes("fo=bar&b"), Encoding.UTF8.GetBytes("a")) }, { new ReadOnlySequence<byte>(Encoding.UTF8.GetBytes("fo=bar&ba")) } }; public static TheoryData<ReadOnlySequence<byte>> IncompleteFormValues => new TheoryData<ReadOnlySequence<byte>> { { ReadOnlySequenceFactory.CreateSegments(Encoding.UTF8.GetBytes("fo=bar&b"), Encoding.UTF8.GetBytes("=")) }, { new ReadOnlySequence<byte>(Encoding.UTF8.GetBytes("fo=bar&b=")) } }; public static TheoryData<Encoding> Encodings => new TheoryData<Encoding> { { Encoding.UTF8 }, { Encoding.UTF32 }, { Encoding.ASCII }, { Encoding.Unicode } }; internal virtual Task<Dictionary<string, StringValues>> ReadFormAsync(FormPipeReader reader) { return reader.ReadFormAsync(); } private static async Task<PipeReader> MakePipeReader(string text) { var formContent = Encoding.UTF8.GetBytes(text); Pipe bodyPipe = new Pipe(); await bodyPipe.Writer.WriteAsync(formContent); // Complete the writer so the reader will complete after processing all data. bodyPipe.Writer.Complete(); return bodyPipe.Reader; } } }
// 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; namespace System.IO.Compression { // All blocks.TryReadBlock do a check to see if signature is correct. Generic extra field is slightly different // all of the TryReadBlocks will throw if there are not enough bytes in the stream internal struct ZipGenericExtraField { private const int SizeOfHeader = 4; private ushort _tag; private ushort _size; private byte[] _data; public ushort Tag => _tag; // returns size of data, not of the entire block public ushort Size => _size; public byte[] Data => _data; public void WriteBlock(Stream stream) { BinaryWriter writer = new BinaryWriter(stream); writer.Write(Tag); writer.Write(Size); writer.Write(Data); } // shouldn't ever read the byte at position endExtraField // assumes we are positioned at the beginning of an extra field subfield public static bool TryReadBlock(BinaryReader reader, long endExtraField, out ZipGenericExtraField field) { field = new ZipGenericExtraField(); // not enough bytes to read tag + size if (endExtraField - reader.BaseStream.Position < 4) return false; field._tag = reader.ReadUInt16(); field._size = reader.ReadUInt16(); // not enough bytes to read the data if (endExtraField - reader.BaseStream.Position < field._size) return false; field._data = reader.ReadBytes(field._size); return true; } // shouldn't ever read the byte at position endExtraField public static List<ZipGenericExtraField> ParseExtraField(Stream extraFieldData) { List<ZipGenericExtraField> extraFields = new List<ZipGenericExtraField>(); using (BinaryReader reader = new BinaryReader(extraFieldData)) { ZipGenericExtraField field; while (TryReadBlock(reader, extraFieldData.Length, out field)) { extraFields.Add(field); } } return extraFields; } public static int TotalSize(List<ZipGenericExtraField> fields) { int size = 0; foreach (ZipGenericExtraField field in fields) size += field.Size + SizeOfHeader; //size is only size of data return size; } public static void WriteAllBlocks(List<ZipGenericExtraField> fields, Stream stream) { foreach (ZipGenericExtraField field in fields) field.WriteBlock(stream); } } internal struct Zip64ExtraField { // Size is size of the record not including the tag or size fields // If the extra field is going in the local header, it cannot include only // one of uncompressed/compressed size public const int OffsetToFirstField = 4; private const ushort TagConstant = 1; private ushort _size; private long? _uncompressedSize; private long? _compressedSize; private long? _localHeaderOffset; private int? _startDiskNumber; public ushort TotalSize => (ushort)(_size + 4); public long? UncompressedSize { get { return _uncompressedSize; } set { _uncompressedSize = value; UpdateSize(); } } public long? CompressedSize { get { return _compressedSize; } set { _compressedSize = value; UpdateSize(); } } public long? LocalHeaderOffset { get { return _localHeaderOffset; } set { _localHeaderOffset = value; UpdateSize(); } } public int? StartDiskNumber => _startDiskNumber; private void UpdateSize() { _size = 0; if (_uncompressedSize != null) _size += 8; if (_compressedSize != null) _size += 8; if (_localHeaderOffset != null) _size += 8; if (_startDiskNumber != null) _size += 4; } // There is a small chance that something very weird could happen here. The code calling into this function // will ask for a value from the extra field if the field was masked with FF's. It's theoretically possible // that a field was FF's legitimately, and the writer didn't decide to write the corresponding extra field. // Also, at the same time, other fields were masked with FF's to indicate looking in the zip64 record. // Then, the search for the zip64 record will fail because the expected size is wrong, // and a nulled out Zip64ExtraField will be returned. Thus, even though there was Zip64 data, // it will not be used. It is questionable whether this situation is possible to detect // unlike the other functions that have try-pattern semantics, these functions always return a // Zip64ExtraField. If a Zip64 extra field actually doesn't exist, all of the fields in the // returned struct will be null // // If there are more than one Zip64 extra fields, we take the first one that has the expected size // public static Zip64ExtraField GetJustZip64Block(Stream extraFieldStream, bool readUncompressedSize, bool readCompressedSize, bool readLocalHeaderOffset, bool readStartDiskNumber) { Zip64ExtraField zip64Field; using (BinaryReader reader = new BinaryReader(extraFieldStream)) { ZipGenericExtraField currentExtraField; while (ZipGenericExtraField.TryReadBlock(reader, extraFieldStream.Length, out currentExtraField)) { if (TryGetZip64BlockFromGenericExtraField(currentExtraField, readUncompressedSize, readCompressedSize, readLocalHeaderOffset, readStartDiskNumber, out zip64Field)) { return zip64Field; } } } zip64Field = new Zip64ExtraField(); zip64Field._compressedSize = null; zip64Field._uncompressedSize = null; zip64Field._localHeaderOffset = null; zip64Field._startDiskNumber = null; return zip64Field; } private static bool TryGetZip64BlockFromGenericExtraField(ZipGenericExtraField extraField, bool readUncompressedSize, bool readCompressedSize, bool readLocalHeaderOffset, bool readStartDiskNumber, out Zip64ExtraField zip64Block) { zip64Block = new Zip64ExtraField(); zip64Block._compressedSize = null; zip64Block._uncompressedSize = null; zip64Block._localHeaderOffset = null; zip64Block._startDiskNumber = null; if (extraField.Tag != TagConstant) return false; // this pattern needed because nested using blocks trigger CA2202 MemoryStream? ms = null; try { ms = new MemoryStream(extraField.Data); using (BinaryReader reader = new BinaryReader(ms)) { ms = null; zip64Block._size = extraField.Size; ushort expectedSize = 0; if (readUncompressedSize) expectedSize += 8; if (readCompressedSize) expectedSize += 8; if (readLocalHeaderOffset) expectedSize += 8; if (readStartDiskNumber) expectedSize += 4; // if it is not the expected size, perhaps there is another extra field that matches if (expectedSize != zip64Block._size) return false; if (readUncompressedSize) zip64Block._uncompressedSize = reader.ReadInt64(); if (readCompressedSize) zip64Block._compressedSize = reader.ReadInt64(); if (readLocalHeaderOffset) zip64Block._localHeaderOffset = reader.ReadInt64(); if (readStartDiskNumber) zip64Block._startDiskNumber = reader.ReadInt32(); // original values are unsigned, so implies value is too big to fit in signed integer if (zip64Block._uncompressedSize < 0) throw new InvalidDataException(SR.FieldTooBigUncompressedSize); if (zip64Block._compressedSize < 0) throw new InvalidDataException(SR.FieldTooBigCompressedSize); if (zip64Block._localHeaderOffset < 0) throw new InvalidDataException(SR.FieldTooBigLocalHeaderOffset); if (zip64Block._startDiskNumber < 0) throw new InvalidDataException(SR.FieldTooBigStartDiskNumber); return true; } } finally { if (ms != null) ms.Dispose(); } } public static Zip64ExtraField GetAndRemoveZip64Block(List<ZipGenericExtraField> extraFields, bool readUncompressedSize, bool readCompressedSize, bool readLocalHeaderOffset, bool readStartDiskNumber) { Zip64ExtraField zip64Field = new Zip64ExtraField(); zip64Field._compressedSize = null; zip64Field._uncompressedSize = null; zip64Field._localHeaderOffset = null; zip64Field._startDiskNumber = null; List<ZipGenericExtraField> markedForDelete = new List<ZipGenericExtraField>(); bool zip64FieldFound = false; foreach (ZipGenericExtraField ef in extraFields) { if (ef.Tag == TagConstant) { markedForDelete.Add(ef); if (!zip64FieldFound) { if (TryGetZip64BlockFromGenericExtraField(ef, readUncompressedSize, readCompressedSize, readLocalHeaderOffset, readStartDiskNumber, out zip64Field)) { zip64FieldFound = true; } } } } foreach (ZipGenericExtraField ef in markedForDelete) extraFields.Remove(ef); return zip64Field; } public static void RemoveZip64Blocks(List<ZipGenericExtraField> extraFields) { List<ZipGenericExtraField> markedForDelete = new List<ZipGenericExtraField>(); foreach (ZipGenericExtraField field in extraFields) if (field.Tag == TagConstant) markedForDelete.Add(field); foreach (ZipGenericExtraField field in markedForDelete) extraFields.Remove(field); } public void WriteBlock(Stream stream) { BinaryWriter writer = new BinaryWriter(stream); writer.Write(TagConstant); writer.Write(_size); if (_uncompressedSize != null) writer.Write(_uncompressedSize.Value); if (_compressedSize != null) writer.Write(_compressedSize.Value); if (_localHeaderOffset != null) writer.Write(_localHeaderOffset.Value); if (_startDiskNumber != null) writer.Write(_startDiskNumber.Value); } } internal struct Zip64EndOfCentralDirectoryLocator { public const uint SignatureConstant = 0x07064B50; public const int SignatureSize = sizeof(uint); public const int SizeOfBlockWithoutSignature = 16; public uint NumberOfDiskWithZip64EOCD; public ulong OffsetOfZip64EOCD; public uint TotalNumberOfDisks; public static bool TryReadBlock(BinaryReader reader, out Zip64EndOfCentralDirectoryLocator zip64EOCDLocator) { zip64EOCDLocator = new Zip64EndOfCentralDirectoryLocator(); if (reader.ReadUInt32() != SignatureConstant) return false; zip64EOCDLocator.NumberOfDiskWithZip64EOCD = reader.ReadUInt32(); zip64EOCDLocator.OffsetOfZip64EOCD = reader.ReadUInt64(); zip64EOCDLocator.TotalNumberOfDisks = reader.ReadUInt32(); return true; } public static void WriteBlock(Stream stream, long zip64EOCDRecordStart) { BinaryWriter writer = new BinaryWriter(stream); writer.Write(SignatureConstant); writer.Write((uint)0); // number of disk with start of zip64 eocd writer.Write(zip64EOCDRecordStart); writer.Write((uint)1); // total number of disks } } internal struct Zip64EndOfCentralDirectoryRecord { private const uint SignatureConstant = 0x06064B50; private const ulong NormalSize = 0x2C; // the size of the data excluding the size/signature fields if no extra data included public ulong SizeOfThisRecord; public ushort VersionMadeBy; public ushort VersionNeededToExtract; public uint NumberOfThisDisk; public uint NumberOfDiskWithStartOfCD; public ulong NumberOfEntriesOnThisDisk; public ulong NumberOfEntriesTotal; public ulong SizeOfCentralDirectory; public ulong OffsetOfCentralDirectory; public static bool TryReadBlock(BinaryReader reader, out Zip64EndOfCentralDirectoryRecord zip64EOCDRecord) { zip64EOCDRecord = new Zip64EndOfCentralDirectoryRecord(); if (reader.ReadUInt32() != SignatureConstant) return false; zip64EOCDRecord.SizeOfThisRecord = reader.ReadUInt64(); zip64EOCDRecord.VersionMadeBy = reader.ReadUInt16(); zip64EOCDRecord.VersionNeededToExtract = reader.ReadUInt16(); zip64EOCDRecord.NumberOfThisDisk = reader.ReadUInt32(); zip64EOCDRecord.NumberOfDiskWithStartOfCD = reader.ReadUInt32(); zip64EOCDRecord.NumberOfEntriesOnThisDisk = reader.ReadUInt64(); zip64EOCDRecord.NumberOfEntriesTotal = reader.ReadUInt64(); zip64EOCDRecord.SizeOfCentralDirectory = reader.ReadUInt64(); zip64EOCDRecord.OffsetOfCentralDirectory = reader.ReadUInt64(); return true; } public static void WriteBlock(Stream stream, long numberOfEntries, long startOfCentralDirectory, long sizeOfCentralDirectory) { BinaryWriter writer = new BinaryWriter(stream); // write Zip 64 EOCD record writer.Write(SignatureConstant); writer.Write(NormalSize); writer.Write((ushort)ZipVersionNeededValues.Zip64); // version needed is 45 for zip 64 support writer.Write((ushort)ZipVersionNeededValues.Zip64); // version made by: high byte is 0 for MS DOS, low byte is version needed writer.Write((uint)0); // number of this disk is 0 writer.Write((uint)0); // number of disk with start of central directory is 0 writer.Write(numberOfEntries); // number of entries on this disk writer.Write(numberOfEntries); // number of entries total writer.Write(sizeOfCentralDirectory); writer.Write(startOfCentralDirectory); } } internal readonly struct ZipLocalFileHeader { public const uint DataDescriptorSignature = 0x08074B50; public const uint SignatureConstant = 0x04034B50; public const int OffsetToCrcFromHeaderStart = 14; public const int OffsetToVersionFromHeaderStart = 4; public const int OffsetToBitFlagFromHeaderStart = 6; public const int SizeOfLocalHeader = 30; public static List<ZipGenericExtraField> GetExtraFields(BinaryReader reader) { // assumes that TrySkipBlock has already been called, so we don't have to validate twice List<ZipGenericExtraField> result; const int OffsetToFilenameLength = 26; // from the point before the signature reader.BaseStream.Seek(OffsetToFilenameLength, SeekOrigin.Current); ushort filenameLength = reader.ReadUInt16(); ushort extraFieldLength = reader.ReadUInt16(); reader.BaseStream.Seek(filenameLength, SeekOrigin.Current); using (Stream str = new SubReadStream(reader.BaseStream, reader.BaseStream.Position, extraFieldLength)) { result = ZipGenericExtraField.ParseExtraField(str); } Zip64ExtraField.RemoveZip64Blocks(result); return result; } // will not throw end of stream exception public static bool TrySkipBlock(BinaryReader reader) { const int OffsetToFilenameLength = 22; // from the point after the signature if (reader.ReadUInt32() != SignatureConstant) return false; if (reader.BaseStream.Length < reader.BaseStream.Position + OffsetToFilenameLength) return false; reader.BaseStream.Seek(OffsetToFilenameLength, SeekOrigin.Current); ushort filenameLength = reader.ReadUInt16(); ushort extraFieldLength = reader.ReadUInt16(); if (reader.BaseStream.Length < reader.BaseStream.Position + filenameLength + extraFieldLength) return false; reader.BaseStream.Seek(filenameLength + extraFieldLength, SeekOrigin.Current); return true; } public static bool TryValidateBlock(BinaryReader reader, ZipArchiveEntry entry) { const int OffsetToFilename = 26; // from the point after the signature if (reader.ReadUInt32() != SignatureConstant) return false; if (reader.BaseStream.Length < reader.BaseStream.Position + OffsetToFilename) return false; reader.BaseStream.Seek(2, SeekOrigin.Current); // skipping minimum version (using min version from central directory header) uint dataDescriptorBit = reader.ReadUInt16() & (uint)ZipArchiveEntry.BitFlagValues.DataDescriptor; reader.BaseStream.Seek(10, SeekOrigin.Current); // skipping bytes used for Compression method (2 bytes), last modification time and date (4 bytes) and CRC (4 bytes) long compressedSize = reader.ReadUInt32(); long uncompressedSize = reader.ReadUInt32(); int filenameLength = reader.ReadUInt16(); uint extraFieldLength = reader.ReadUInt16(); if (reader.BaseStream.Length < reader.BaseStream.Position + filenameLength + extraFieldLength) return false; reader.BaseStream.Seek(filenameLength, SeekOrigin.Current); // skipping Filename long endExtraFields = reader.BaseStream.Position + extraFieldLength; if (dataDescriptorBit == 0) { bool isUncompressedSizeInZip64 = uncompressedSize == ZipHelper.Mask32Bit; bool isCompressedSizeInZip64 = compressedSize == ZipHelper.Mask32Bit; Zip64ExtraField zip64; // Ideally we should also check if the minimumVersion is 64 bit or above, but there could zip files for which this version is not set correctly if (isUncompressedSizeInZip64 || isCompressedSizeInZip64) { zip64 = Zip64ExtraField.GetJustZip64Block(new SubReadStream(reader.BaseStream, reader.BaseStream.Position, extraFieldLength), isUncompressedSizeInZip64, isCompressedSizeInZip64, false, false); if (zip64.UncompressedSize != null) { uncompressedSize = zip64.UncompressedSize.Value; } if (zip64.CompressedSize != null) { compressedSize = zip64.CompressedSize.Value; } } reader.BaseStream.AdvanceToPosition(endExtraFields); } else { if (reader.BaseStream.Length < reader.BaseStream.Position + extraFieldLength + entry.CompressedLength + 4) { return false; } reader.BaseStream.Seek(extraFieldLength + entry.CompressedLength, SeekOrigin.Current); // seek to end of compressed file from which Data descriptor starts uint dataDescriptorSignature = reader.ReadUInt32(); bool wasDataDescriptorSignatureRead = false; int seekSize = 0; if (dataDescriptorSignature == DataDescriptorSignature) { wasDataDescriptorSignatureRead = true; seekSize = 4; } bool is64bit = entry._versionToExtract >= ZipVersionNeededValues.Zip64; seekSize += (is64bit ? 8 : 4) * 2; // if Zip64 read by 8 bytes else 4 bytes 2 times (compressed and uncompressed size) if (reader.BaseStream.Length < reader.BaseStream.Position + seekSize) { return false; } // dataDescriptorSignature is optional, if it was the DataDescriptorSignature we need to skip CRC 4 bytes else we can assume CRC is alreadyskipped if (wasDataDescriptorSignatureRead) reader.BaseStream.Seek(4, SeekOrigin.Current); if (is64bit) { compressedSize = reader.ReadInt64(); uncompressedSize = reader.ReadInt64(); } else { compressedSize = reader.ReadInt32(); uncompressedSize = reader.ReadInt32(); } reader.BaseStream.Seek(-seekSize - entry.CompressedLength - 4, SeekOrigin.Current); // Seek back to the beginning of compressed stream } if (entry.CompressedLength != compressedSize) { return false; } if (entry.Length != uncompressedSize) { return false; } return true; } } internal struct ZipCentralDirectoryFileHeader { public const uint SignatureConstant = 0x02014B50; public byte VersionMadeByCompatibility; public byte VersionMadeBySpecification; public ushort VersionNeededToExtract; public ushort GeneralPurposeBitFlag; public ushort CompressionMethod; public uint LastModified; // convert this on the fly public uint Crc32; public long CompressedSize; public long UncompressedSize; public ushort FilenameLength; public ushort ExtraFieldLength; public ushort FileCommentLength; public int DiskNumberStart; public ushort InternalFileAttributes; public uint ExternalFileAttributes; public long RelativeOffsetOfLocalHeader; public byte[] Filename; public byte[]? FileComment; public List<ZipGenericExtraField>? ExtraFields; // if saveExtraFieldsAndComments is false, FileComment and ExtraFields will be null // in either case, the zip64 extra field info will be incorporated into other fields public static bool TryReadBlock(BinaryReader reader, bool saveExtraFieldsAndComments, out ZipCentralDirectoryFileHeader header) { header = new ZipCentralDirectoryFileHeader(); if (reader.ReadUInt32() != SignatureConstant) return false; header.VersionMadeBySpecification = reader.ReadByte(); header.VersionMadeByCompatibility = reader.ReadByte(); header.VersionNeededToExtract = reader.ReadUInt16(); header.GeneralPurposeBitFlag = reader.ReadUInt16(); header.CompressionMethod = reader.ReadUInt16(); header.LastModified = reader.ReadUInt32(); header.Crc32 = reader.ReadUInt32(); uint compressedSizeSmall = reader.ReadUInt32(); uint uncompressedSizeSmall = reader.ReadUInt32(); header.FilenameLength = reader.ReadUInt16(); header.ExtraFieldLength = reader.ReadUInt16(); header.FileCommentLength = reader.ReadUInt16(); ushort diskNumberStartSmall = reader.ReadUInt16(); header.InternalFileAttributes = reader.ReadUInt16(); header.ExternalFileAttributes = reader.ReadUInt32(); uint relativeOffsetOfLocalHeaderSmall = reader.ReadUInt32(); header.Filename = reader.ReadBytes(header.FilenameLength); bool uncompressedSizeInZip64 = uncompressedSizeSmall == ZipHelper.Mask32Bit; bool compressedSizeInZip64 = compressedSizeSmall == ZipHelper.Mask32Bit; bool relativeOffsetInZip64 = relativeOffsetOfLocalHeaderSmall == ZipHelper.Mask32Bit; bool diskNumberStartInZip64 = diskNumberStartSmall == ZipHelper.Mask16Bit; Zip64ExtraField zip64; long endExtraFields = reader.BaseStream.Position + header.ExtraFieldLength; using (Stream str = new SubReadStream(reader.BaseStream, reader.BaseStream.Position, header.ExtraFieldLength)) { if (saveExtraFieldsAndComments) { header.ExtraFields = ZipGenericExtraField.ParseExtraField(str); zip64 = Zip64ExtraField.GetAndRemoveZip64Block(header.ExtraFields, uncompressedSizeInZip64, compressedSizeInZip64, relativeOffsetInZip64, diskNumberStartInZip64); } else { header.ExtraFields = null; zip64 = Zip64ExtraField.GetJustZip64Block(str, uncompressedSizeInZip64, compressedSizeInZip64, relativeOffsetInZip64, diskNumberStartInZip64); } } // There are zip files that have malformed ExtraField blocks in which GetJustZip64Block() silently bails out without reading all the way to the end // of the ExtraField block. Thus we must force the stream's position to the proper place. reader.BaseStream.AdvanceToPosition(endExtraFields); if (saveExtraFieldsAndComments) header.FileComment = reader.ReadBytes(header.FileCommentLength); else { reader.BaseStream.Position += header.FileCommentLength; header.FileComment = null; } header.UncompressedSize = zip64.UncompressedSize == null ? uncompressedSizeSmall : zip64.UncompressedSize.Value; header.CompressedSize = zip64.CompressedSize == null ? compressedSizeSmall : zip64.CompressedSize.Value; header.RelativeOffsetOfLocalHeader = zip64.LocalHeaderOffset == null ? relativeOffsetOfLocalHeaderSmall : zip64.LocalHeaderOffset.Value; header.DiskNumberStart = zip64.StartDiskNumber == null ? diskNumberStartSmall : zip64.StartDiskNumber.Value; return true; } } internal struct ZipEndOfCentralDirectoryBlock { public const uint SignatureConstant = 0x06054B50; public const int SignatureSize = sizeof(uint); // This is the minimum possible size, assuming the zip file comments variable section is empty public const int SizeOfBlockWithoutSignature = 18; // The end of central directory can have a variable size zip file comment at the end, but its max length can be 64K // The Zip File Format Specification does not explicitly mention a max size for this field, but we are assuming this // max size because that is the maximum value an ushort can hold. public const int ZipFileCommentMaxLength = ushort.MaxValue; public uint Signature; public ushort NumberOfThisDisk; public ushort NumberOfTheDiskWithTheStartOfTheCentralDirectory; public ushort NumberOfEntriesInTheCentralDirectoryOnThisDisk; public ushort NumberOfEntriesInTheCentralDirectory; public uint SizeOfCentralDirectory; public uint OffsetOfStartOfCentralDirectoryWithRespectToTheStartingDiskNumber; public byte[] ArchiveComment; public static void WriteBlock(Stream stream, long numberOfEntries, long startOfCentralDirectory, long sizeOfCentralDirectory, byte[]? archiveComment) { BinaryWriter writer = new BinaryWriter(stream); ushort numberOfEntriesTruncated = numberOfEntries > ushort.MaxValue ? ZipHelper.Mask16Bit : (ushort)numberOfEntries; uint startOfCentralDirectoryTruncated = startOfCentralDirectory > uint.MaxValue ? ZipHelper.Mask32Bit : (uint)startOfCentralDirectory; uint sizeOfCentralDirectoryTruncated = sizeOfCentralDirectory > uint.MaxValue ? ZipHelper.Mask32Bit : (uint)sizeOfCentralDirectory; writer.Write(SignatureConstant); writer.Write((ushort)0); // number of this disk writer.Write((ushort)0); // number of disk with start of CD writer.Write(numberOfEntriesTruncated); // number of entries on this disk's cd writer.Write(numberOfEntriesTruncated); // number of entries in entire CD writer.Write(sizeOfCentralDirectoryTruncated); writer.Write(startOfCentralDirectoryTruncated); // Should be valid because of how we read archiveComment in TryReadBlock: Debug.Assert((archiveComment == null) || (archiveComment.Length <= ZipFileCommentMaxLength)); writer.Write(archiveComment != null ? (ushort)archiveComment.Length : (ushort)0); // zip file comment length if (archiveComment != null) writer.Write(archiveComment); } public static bool TryReadBlock(BinaryReader reader, out ZipEndOfCentralDirectoryBlock eocdBlock) { eocdBlock = new ZipEndOfCentralDirectoryBlock(); if (reader.ReadUInt32() != SignatureConstant) return false; eocdBlock.Signature = SignatureConstant; eocdBlock.NumberOfThisDisk = reader.ReadUInt16(); eocdBlock.NumberOfTheDiskWithTheStartOfTheCentralDirectory = reader.ReadUInt16(); eocdBlock.NumberOfEntriesInTheCentralDirectoryOnThisDisk = reader.ReadUInt16(); eocdBlock.NumberOfEntriesInTheCentralDirectory = reader.ReadUInt16(); eocdBlock.SizeOfCentralDirectory = reader.ReadUInt32(); eocdBlock.OffsetOfStartOfCentralDirectoryWithRespectToTheStartingDiskNumber = reader.ReadUInt32(); ushort commentLength = reader.ReadUInt16(); eocdBlock.ArchiveComment = reader.ReadBytes(commentLength); return true; } } }
#region Copyright notice and license // Copyright 2019 The gRPC Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #endregion using System.IO.Pipelines; using Greet; using Grpc.AspNetCore.FunctionalTests.Infrastructure; using Grpc.AspNetCore.Server.Internal; using Grpc.Core; using Grpc.Tests.Shared; using Microsoft.Extensions.Logging; using NUnit.Framework; namespace Grpc.AspNetCore.FunctionalTests.Server { [TestFixture] public class DeadlineTests : FunctionalTestBase { [Test] public Task WriteUntilDeadline_SuccessResponsesStreamed_Deadline() => WriteUntilDeadline_SuccessResponsesStreamed_CoreAsync(async (request, responseStream, context) => { var i = 0; while (DateTime.UtcNow < context.Deadline) { var message = $"How are you {request.Name}? {i}"; await responseStream.WriteAsync(new HelloReply { Message = message }).DefaultTimeout(); i++; await Task.Delay(110); } // Ensure deadline timer has run var tcs = new TaskCompletionSource<object?>(TaskCreationOptions.RunContinuationsAsynchronously); context.CancellationToken.Register(() => tcs.SetResult(null)); await tcs.Task.DefaultTimeout(); }); [Test] public Task WriteUntilDeadline_SuccessResponsesStreamed_Token() => WriteUntilDeadline_SuccessResponsesStreamed_CoreAsync(async (request, responseStream, context) => { var i = 0; while (!context.CancellationToken.IsCancellationRequested) { var message = $"How are you {request.Name}? {i}"; await responseStream.WriteAsync(new HelloReply { Message = message }).DefaultTimeout(); i++; await Task.Delay(110); } }); public async Task WriteUntilDeadline_SuccessResponsesStreamed_CoreAsync(ServerStreamingServerMethod<HelloRequest, HelloReply> callHandler) { // Arrange var method = Fixture.DynamicGrpc.AddServerStreamingMethod<HelloRequest, HelloReply>(callHandler); var requestMessage = new HelloRequest { Name = "World" }; var requestStream = new MemoryStream(); MessageHelpers.WriteMessage(requestStream, requestMessage); var httpRequest = GrpcHttpHelper.Create(method.FullName); httpRequest.Headers.Add(GrpcProtocolConstants.TimeoutHeader, "200m"); httpRequest.Content = new GrpcStreamContent(requestStream); try { // Act var response = await Fixture.Client.SendAsync(httpRequest, HttpCompletionOption.ResponseHeadersRead).DefaultTimeout(); // Assert response.AssertIsSuccessfulGrpcRequest(); var responseStream = await response.Content.ReadAsStreamAsync().DefaultTimeout(); var pipeReader = PipeReader.Create(responseStream); var messageCount = 0; var readTask = Task.Run(async () => { while (true) { var greeting = await MessageHelpers.AssertReadStreamMessageAsync<HelloReply>(pipeReader).DefaultTimeout(); if (greeting != null) { Assert.AreEqual($"How are you World? {messageCount}", greeting.Message); messageCount++; } else { break; } } }); await readTask.DefaultTimeout(); Assert.AreNotEqual(0, messageCount); response.AssertTrailerStatus(StatusCode.DeadlineExceeded, "Deadline Exceeded"); } catch (Exception ex) when (Net.Client.Internal.GrpcProtocolHelpers.ResolveRpcExceptionStatusCode(ex) == StatusCode.Cancelled) { // Ignore exception from deadline abort } Assert.True(HasLog(LogLevel.Debug, "DeadlineExceeded", "Request with timeout of 00:00:00.2000000 has exceeded its deadline.")); await TestHelpers.AssertIsTrueRetryAsync( () => HasLog(LogLevel.Trace, "DeadlineStopped", "Request deadline stopped."), "Missing deadline stopped log.").DefaultTimeout(); } [Test] public async Task UnaryMethodErrorWithinDeadline() { static async Task<HelloReply> ThrowErrorWithinDeadline(HelloRequest request, ServerCallContext context) { await Task.Delay(10); throw new InvalidOperationException("An error."); } // Arrange SetExpectedErrorsFilter(writeContext => { if (writeContext.LoggerName == TestConstants.ServerCallHandlerTestName) { // Deadline happened before write if (writeContext.EventId.Name == "ErrorExecutingServiceMethod" && writeContext.State.ToString() == "Error when executing service method 'ThrowErrorWithinDeadline'." && writeContext.Exception!.Message == "An error.") { return true; } } return false; }); var method = Fixture.DynamicGrpc.AddUnaryMethod<HelloRequest, HelloReply>(ThrowErrorWithinDeadline, nameof(ThrowErrorWithinDeadline)); var requestMessage = new HelloRequest { Name = "World" }; var requestStream = new MemoryStream(); MessageHelpers.WriteMessage(requestStream, requestMessage); var httpRequest = GrpcHttpHelper.Create(method.FullName); httpRequest.Headers.Add(GrpcProtocolConstants.TimeoutHeader, "200m"); httpRequest.Content = new GrpcStreamContent(requestStream); // Act var response = await Fixture.Client.SendAsync(httpRequest, HttpCompletionOption.ResponseHeadersRead).DefaultTimeout(); // Assert response.AssertIsSuccessfulGrpcRequest(); response.AssertTrailerStatus(StatusCode.Unknown, "Exception was thrown by handler. InvalidOperationException: An error."); Assert.True(HasLog(LogLevel.Trace, "DeadlineStopped", "Request deadline stopped.")); } [TestCase(true)] [TestCase(false)] public async Task UnaryMethodDeadlineExceeded(bool throwErrorOnCancellation) { async Task<HelloReply> WaitUntilDeadline(HelloRequest request, ServerCallContext context) { try { await Task.Delay(1000, context.CancellationToken); } catch (OperationCanceledException) when (!throwErrorOnCancellation) { // nom nom nom } return new HelloReply(); } // Arrange SetExpectedErrorsFilter(writeContext => { if (writeContext.LoggerName == TestConstants.ServerCallHandlerTestName) { if (writeContext.EventId.Name == "ErrorExecutingServiceMethod" && writeContext.State.ToString() == "Error when executing service method 'WaitUntilDeadline-True'.") { return true; } } return false; }); var method = Fixture.DynamicGrpc.AddUnaryMethod<HelloRequest, HelloReply>(WaitUntilDeadline, $"{nameof(WaitUntilDeadline)}-{throwErrorOnCancellation}"); var requestMessage = new HelloRequest { Name = "World" }; var requestStream = new MemoryStream(); MessageHelpers.WriteMessage(requestStream, requestMessage); var httpRequest = GrpcHttpHelper.Create(method.FullName); httpRequest.Headers.Add(GrpcProtocolConstants.TimeoutHeader, "200m"); httpRequest.Content = new GrpcStreamContent(requestStream); try { // Act var response = await Fixture.Client.SendAsync(httpRequest, HttpCompletionOption.ResponseHeadersRead).DefaultTimeout(); // Assert response.AssertIsSuccessfulGrpcRequest(); response.AssertTrailerStatus(StatusCode.DeadlineExceeded, "Deadline Exceeded"); } catch (Exception ex) when (Net.Client.Internal.GrpcProtocolHelpers.ResolveRpcExceptionStatusCode(ex) == StatusCode.Cancelled) { // Ignore exception from deadline abort } Assert.True(HasLog(LogLevel.Debug, "DeadlineExceeded", "Request with timeout of 00:00:00.2000000 has exceeded its deadline.")); await TestHelpers.AssertIsTrueRetryAsync( () => HasLog(LogLevel.Trace, "DeadlineStopped", "Request deadline stopped."), "Missing deadline stopped log.").DefaultTimeout(); } [Test] public async Task WriteMessageAfterDeadline() { static async Task WriteUntilError(HelloRequest request, IServerStreamWriter<HelloReply> responseStream, ServerCallContext context) { for (var i = 0; i < 5; i++) { var message = $"How are you {request.Name}? {i}"; await responseStream.WriteAsync(new HelloReply { Message = message }).DefaultTimeout(); await Task.Delay(10); } var tcs = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously); context.CancellationToken.Register(s => ((TaskCompletionSource<bool>)s!).SetResult(true), tcs); await tcs.Task; await responseStream.WriteAsync(new HelloReply { Message = "Write after deadline" }).DefaultTimeout(); } // Arrange SetExpectedErrorsFilter(writeContext => { if (writeContext.LoggerName == TestConstants.ServerCallHandlerTestName) { // Deadline happened before write if (writeContext.EventId.Name == "ErrorExecutingServiceMethod" && writeContext.State.ToString() == "Error when executing service method 'WriteUntilError'.") { return true; } // Deadline happened during write (error raised from pipeline writer) if (writeContext.Exception is InvalidOperationException && writeContext.Exception.Message == "Writing is not allowed after writer was completed.") { return true; } } return false; }); using var httpEventListener = new HttpEventSourceListener(LoggerFactory); var method = Fixture.DynamicGrpc.AddServerStreamingMethod<HelloRequest, HelloReply>(WriteUntilError, nameof(WriteUntilError)); var requestMessage = new HelloRequest { Name = "World" }; var requestStream = new MemoryStream(); MessageHelpers.WriteMessage(requestStream, requestMessage); var httpRequest = GrpcHttpHelper.Create(method.FullName); httpRequest.Headers.Add(GrpcProtocolConstants.TimeoutHeader, "200m"); httpRequest.Content = new GrpcStreamContent(requestStream); try { // Act var response = await Fixture.Client.SendAsync(httpRequest, HttpCompletionOption.ResponseHeadersRead).DefaultTimeout(); // Assert response.AssertIsSuccessfulGrpcRequest(); var responseStream = await response.Content.ReadAsStreamAsync().DefaultTimeout(); var pipeReader = PipeReader.Create(responseStream); var messageCount = 0; var readTask = Task.Run(async () => { while (true) { var greeting = await MessageHelpers.AssertReadStreamMessageAsync<HelloReply>(pipeReader).DefaultTimeout(); if (greeting != null) { Assert.AreEqual($"How are you World? {messageCount}", greeting.Message); messageCount++; } else { break; } } }); await readTask.DefaultTimeout(); Assert.AreNotEqual(0, messageCount); response.AssertTrailerStatus(StatusCode.DeadlineExceeded, "Deadline Exceeded"); } catch (Exception ex) when (Net.Client.Internal.GrpcProtocolHelpers.ResolveRpcExceptionStatusCode(ex) == StatusCode.Cancelled) { // Ignore exception from deadline abort } Assert.True(HasLog(LogLevel.Debug, "DeadlineExceeded", "Request with timeout of 00:00:00.2000000 has exceeded its deadline.")); // The server has completed the response but is still running // Allow time for the server to complete var expectedErrorMessages = new List<string> { "Can't write the message because the request is complete.", "Writing is not allowed after writer was completed.", "Invalid ordering of calling StartAsync or CompleteAsync and Advance." }; await TestHelpers.AssertIsTrueRetryAsync(() => { var errorLogged = Logs.Any(r => r.EventId.Name == "ErrorExecutingServiceMethod" && r.State.ToString() == "Error when executing service method 'WriteUntilError'." && expectedErrorMessages.Contains(r.Exception!.Message)); return errorLogged; }, "Expected error not thrown.").DefaultTimeout(); await TestHelpers.AssertIsTrueRetryAsync( () => HasLog(LogLevel.Trace, "DeadlineStopped", "Request deadline stopped."), "Missing deadline stopped log.").DefaultTimeout(); } } }
using HoloToolkit.Unity; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using System; using Microsoft.MixedReality.Toolkit; using Microsoft.MixedReality.Toolkit.Utilities.Solvers; using Microsoft.MixedReality.Toolkit.LightingTools; public class MainController : MonoBehaviour { #region Constants private const string ARTICLE_URL = "http://www.roadtomr.com/2020/06/16/2835/envirolight-hl2/"; private const string ARTIST_URL = "https://www.digitalangel3d.com"; private const string DEVELOPER_URL = "https://jared.bienz.com/"; #endregion // Constants #region Member Variables private bool isSwitchingLightModes; private List<GameObject> screens = new List<GameObject>(); #endregion // Member Variables #region Inspector Fields [Tooltip("Toggle for enabling default lights.")] public Toggle DefaultLightsToggle; [Tooltip("Toggle for enabling environment lights.")] public Toggle EnvironmentLightsToggle; [Tooltip("Used for placing the whole scene.")] public LightCapture LightCapture; [Tooltip("Used for placing the whole scene.")] public PlacementController ScenePlacementController; [Tooltip("The GameObject that represents the whole scene.")] public GameObject SceneRoot; [Tooltip("Used for speaking notifications.")] public TextToSpeech TextToSpeech; [Tooltip("The About UI Panel.")] public GameObject UIAbout; [Tooltip("The Home UI Panel.")] public GameObject UIHome; [Tooltip("The Light Sources UI Panel.")] public GameObject UILights; [Tooltip("The Placement UI Panel.")] public GameObject UIPlace; #endregion #region Internal Methods /// <summary> /// Navigates to the specified UI screen. /// </summary> /// <param name="screen"> /// The screen to navigate to. /// </param> private void GoToScreen(GameObject screen) { // Disable all but current foreach (GameObject s in screens) { // Activate or deactivate s.SetActive(s == screen); } } /// <summary> /// Opens the specified URL in the system browser. /// </summary> /// <param name="url"> /// The URL to open. /// </param> private void OpenUrl(string url) { Debug.Log($"OpenUrl: Opening {url}"); TextToSpeech.StartSpeaking("Opening browser..."); #if WINDOWS_UWP UnityEngine.WSA.Application.InvokeOnUIThread(async () => { bool result = await global::Windows.System.Launcher.LaunchUriAsync(new System.Uri(url)); if (!result) { Debug.LogError("Launching URI failed to launch."); } }, false); #else Application.OpenURL(url); #endif } /// <summary> /// Switches light modes. /// </summary> /// <param name="environment"> /// Should we should to default or environment? /// </param> /// <param name="speak"> /// Should we speak the notification to the user. /// </param> private void UseLights(bool environment, bool speak=true) { // Avoid reentrance if (isSwitchingLightModes) { return; } // Confirm verbally if (speak) { TextToSpeech.StartSpeaking((environment ? "Environment lights" : "Default lights")); } // Make sure changing if (LightCapture.enabled == environment) { return; } isSwitchingLightModes = true; // Enable / Disable lighting containers // The order is important due to the way // Unity decides how normals are baked at runtime if (environment) { LightCapture.enabled = true; DefaultLightsToggle.isOn = false; EnvironmentLightsToggle.isOn = true; } else { LightCapture.enabled = false; EnvironmentLightsToggle.isOn = false; DefaultLightsToggle.isOn = true; } // Done isSwitchingLightModes = false; } #endregion // Internal Methods #region Overrides / Event Handlers private void OnLightsToggle(Toggle sender) { if (!isSwitchingLightModes) { UseLights(sender == EnvironmentLightsToggle); } } private void OnPlacingStopped() { // Go to home screen GoToScreen(UIHome); } #endregion // Overrides / Event Handlers #region Behavior Overrides void Start() { // Store UI screens screens.Add(UIAbout); screens.Add(UIHome); screens.Add(UILights); screens.Add(UIPlace); // Subscribe event handlers DefaultLightsToggle.onValueChanged.AddListener((b) => { if (b) OnLightsToggle(DefaultLightsToggle); }); EnvironmentLightsToggle.onValueChanged.AddListener((b) => { if (b) OnLightsToggle(EnvironmentLightsToggle); }); ScenePlacementController.TapToPlace.OnPlacingStopped.AddListener(OnPlacingStopped); // Hide the scene on start SceneRoot.SetActive(false); // Start placing ScenePlacementController.StartPlacement(); } #endregion // Behavior Overrides #region Public Methods /// <summary> /// Resets the environment scan. /// </summary> public void ResetEnvironmentLights() { LightCapture.Clear(); } /// <summary> /// Starts placement of the scene. /// </summary> public void StartPlacing() { GoToScreen(UIPlace); ScenePlacementController.StartPlacement(); } /// <summary> /// Navigates to the About UI screen. /// </summary> public void UIGoAbout() { GoToScreen(UIAbout); } /// <summary> /// Navigates to the Home UI screen. /// </summary> public void UIGoHome() { GoToScreen(UIHome); } /// <summary> /// Navigates to the Lights UI screen. /// </summary> public void UIGoLights() { GoToScreen(UILights); } /// <summary> /// Uses default lighting. /// </summary> public void UseDefaultLights() { // Switch mode UseLights(false); } /// <summary> /// Uses environment lighting. /// </summary> public void UseEnvironmentLights() { // Switch mode UseLights(true); } /// <summary> /// Visit the article for the sample. /// </summary> public void VisitArticle() { OpenUrl(ARTICLE_URL); } /// <summary> /// Visit the artists home page. /// </summary> public void VisitArtist() { OpenUrl(ARTIST_URL); } /// <summary> /// Visit the developers home page. /// </summary> public void VisitDeveloper() { OpenUrl(DEVELOPER_URL); } #endregion // Public Methods #region Public Properties /// <summary> /// Gets a value that indicates if environment lights are being used. /// </summary> /// <value> /// <c>true</c> if environment lights are being used; otherwise <c>false</c>. /// </value> public bool IsUsingEnvironment { get { return LightCapture.enabled; } } #endregion // Public Properties }
using System; using ChainUtils.BouncyCastle.Crypto.Parameters; using ChainUtils.BouncyCastle.Crypto.Utilities; namespace ChainUtils.BouncyCastle.Crypto.Engines { /** * A class that provides Blowfish key encryption operations, * such as encoding data and generating keys. * All the algorithms herein are from Applied Cryptography * and implement a simplified cryptography interface. */ public sealed class BlowfishEngine : IBlockCipher { private readonly static uint[] KP = { 0x243F6A88, 0x85A308D3, 0x13198A2E, 0x03707344, 0xA4093822, 0x299F31D0, 0x082EFA98, 0xEC4E6C89, 0x452821E6, 0x38D01377, 0xBE5466CF, 0x34E90C6C, 0xC0AC29B7, 0xC97C50DD, 0x3F84D5B5, 0xB5470917, 0x9216D5D9, 0x8979FB1B }, KS0 = { 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 }, KS1 = { 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 }, KS2 = { 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 }, KS3 = { 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 }; //==================================== // Useful constants //==================================== private static readonly int ROUNDS = 16; private const int BLOCK_SIZE = 8; // bytes = 64 bits private static readonly int SBOX_SK = 256; private static readonly int P_SZ = ROUNDS+2; private readonly uint[] S0, S1, S2, S3; // the s-boxes private readonly uint[] P; // the p-array private bool encrypting; private byte[] workingKey; public BlowfishEngine() { S0 = new uint[SBOX_SK]; S1 = new uint[SBOX_SK]; S2 = new uint[SBOX_SK]; S3 = new uint[SBOX_SK]; P = new uint[P_SZ]; } /** * initialise a Blowfish cipher. * * @param forEncryption whether or not we are for encryption. * @param parameters the parameters required to set up the cipher. * @exception ArgumentException if the parameters argument is * inappropriate. */ public void Init( bool forEncryption, ICipherParameters parameters) { if (!(parameters is KeyParameter)) throw new ArgumentException("invalid parameter passed to Blowfish init - " + parameters.GetType().ToString()); encrypting = forEncryption; workingKey = ((KeyParameter)parameters).GetKey(); SetKey(workingKey); } public string AlgorithmName { get { return "Blowfish"; } } public bool IsPartialBlockOkay { get { return false; } } public int ProcessBlock( byte[] input, int inOff, byte[] output, int outOff) { if (workingKey == null) { throw new InvalidOperationException("Blowfish not initialised"); } if ((inOff + BLOCK_SIZE) > input.Length) { throw new DataLengthException("input buffer too short"); } if ((outOff + BLOCK_SIZE) > output.Length) { throw new DataLengthException("output buffer too short"); } if (encrypting) { EncryptBlock(input, inOff, output, outOff); } else { DecryptBlock(input, inOff, output, outOff); } return BLOCK_SIZE; } public void Reset() { } public int GetBlockSize() { return BLOCK_SIZE; } //================================== // Private Implementation //================================== private uint F(uint x) { return (((S0[x >> 24] + S1[(x >> 16) & 0xff]) ^ S2[(x >> 8) & 0xff]) + S3[x & 0xff]); } /** * apply the encryption cycle to each value pair in the table. */ private void ProcessTable( uint xl, uint xr, uint[] table) { var size = table.Length; for (var s = 0; s < size; s += 2) { xl ^= P[0]; for (var i = 1; i < ROUNDS; i += 2) { xr ^= F(xl) ^ P[i]; xl ^= F(xr) ^ P[i + 1]; } xr ^= P[ROUNDS + 1]; table[s] = xr; table[s + 1] = xl; xr = xl; // end of cycle swap xl = table[s]; } } private void SetKey(byte[] key) { /* * - comments are from _Applied Crypto_, Schneier, p338 * please be careful comparing the two, AC numbers the * arrays from 1, the enclosed code from 0. * * (1) * Initialise the S-boxes and the P-array, with a fixed string * This string contains the hexadecimal digits of pi (3.141...) */ Array.Copy(KS0, 0, S0, 0, SBOX_SK); Array.Copy(KS1, 0, S1, 0, SBOX_SK); Array.Copy(KS2, 0, S2, 0, SBOX_SK); Array.Copy(KS3, 0, S3, 0, SBOX_SK); Array.Copy(KP, 0, P, 0, P_SZ); /* * (2) * Now, XOR P[0] with the first 32 bits of the key, XOR P[1] with the * second 32-bits of the key, and so on for all bits of the key * (up to P[17]). Repeatedly cycle through the key bits until the * entire P-array has been XOR-ed with the key bits */ var keyLength = key.Length; var keyIndex = 0; for (var i=0; i < P_SZ; i++) { // Get the 32 bits of the key, in 4 * 8 bit chunks uint data = 0x0000000; for (var j=0; j < 4; j++) { // create a 32 bit block data = (data << 8) | (uint)key[keyIndex++]; // wrap when we get to the end of the key if (keyIndex >= keyLength) { keyIndex = 0; } } // XOR the newly created 32 bit chunk onto the P-array P[i] ^= data; } /* * (3) * Encrypt the all-zero string with the Blowfish algorithm, using * the subkeys described in (1) and (2) * * (4) * Replace P1 and P2 with the output of step (3) * * (5) * Encrypt the output of step(3) using the Blowfish algorithm, * with the modified subkeys. * * (6) * Replace P3 and P4 with the output of step (5) * * (7) * Continue the process, replacing all elements of the P-array * and then all four S-boxes in order, with the output of the * continuously changing Blowfish algorithm */ ProcessTable(0, 0, P); ProcessTable(P[P_SZ - 2], P[P_SZ - 1], S0); ProcessTable(S0[SBOX_SK - 2], S0[SBOX_SK - 1], S1); ProcessTable(S1[SBOX_SK - 2], S1[SBOX_SK - 1], S2); ProcessTable(S2[SBOX_SK - 2], S2[SBOX_SK - 1], S3); } /** * Encrypt the given input starting at the given offset and place * the result in the provided buffer starting at the given offset. * The input will be an exact multiple of our blocksize. */ private void EncryptBlock( byte[] src, int srcIndex, byte[] dst, int dstIndex) { var xl = Pack.BE_To_UInt32(src, srcIndex); var xr = Pack.BE_To_UInt32(src, srcIndex+4); xl ^= P[0]; for (var i = 1; i < ROUNDS; i += 2) { xr ^= F(xl) ^ P[i]; xl ^= F(xr) ^ P[i + 1]; } xr ^= P[ROUNDS + 1]; Pack.UInt32_To_BE(xr, dst, dstIndex); Pack.UInt32_To_BE(xl, dst, dstIndex + 4); } /** * Decrypt the given input starting at the given offset and place * the result in the provided buffer starting at the given offset. * The input will be an exact multiple of our blocksize. */ private void DecryptBlock( byte[] src, int srcIndex, byte[] dst, int dstIndex) { var xl = Pack.BE_To_UInt32(src, srcIndex); var xr = Pack.BE_To_UInt32(src, srcIndex + 4); xl ^= P[ROUNDS + 1]; for (var i = ROUNDS; i > 0 ; i -= 2) { xr ^= F(xl) ^ P[i]; xl ^= F(xr) ^ P[i - 1]; } xr ^= P[0]; Pack.UInt32_To_BE(xr, dst, dstIndex); Pack.UInt32_To_BE(xl, dst, dstIndex + 4); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using PopForums.Configuration; using PopForums.Extensions; namespace PopForums.Services { public class TextParsingService : ITextParsingService { public TextParsingService(ISettingsManager settingsManager) { _settingsManager = settingsManager; } private ISettingsManager _settingsManager; public static string[] AllowedCloseableTags = {"b", "i", "code", "pre", "ul", "ol", "li", "url", "quote", "img"}; private readonly static Regex _tagPattern = new Regex(@"\[[\w""\?=&/;\+%\*\:~,\.\-\$\|@#]+\]", RegexOptions.Compiled | RegexOptions.IgnoreCase); private readonly static Regex _tagID = new Regex(@"\[/?(\w+)\=*.*?\]", RegexOptions.Compiled | RegexOptions.IgnoreCase); private readonly static Regex _protocolPattern = new Regex(@"(?<![\]""\>=])(((news|(ht|f)tp(s?))\://)[\w\-\*]+(\.[\w\-/~\*]+)*/?)([\w\?=&/;\+%\*\:~,\.\-\$\|@#])*", RegexOptions.Compiled | RegexOptions.IgnoreCase); private readonly static Regex _wwwPattern = new Regex(@"(?<!(\]|""|//))(?<=\s|^)(w{3}(\.[\w\-/~\*]+)*/?)([\?\w=&;\+%\*\:~,\-\$\|@#])*", RegexOptions.Compiled | RegexOptions.IgnoreCase); private readonly static Regex _emailPattern = new Regex(@"(?<=\s|\])(?<!(mailto:|""\]))([\w\.\-_']+)@(([\w\-]+\.)+[\w\-]+)", RegexOptions.Compiled | RegexOptions.IgnoreCase); private static readonly Regex _youTubePattern = new Regex(@"(?<![\]""\>=])(((http(s?))\://)[w*\.]*(youtu\.be|youtube\.com+))([\w\?=&/;\+%\*\:~,\.\-\$\|@#])*", RegexOptions.Compiled | RegexOptions.IgnoreCase); /// <summary> /// Converts forum code from the browser to HTML for storage. This method wraps <see cref="CleanForumCode(string)"/> and <see cref="ForumCodeToHtml(string)"/>, and censors the text. /// </summary> /// <param name="text">Text to parse.</param> /// <returns>Parsed text.</returns> public string ForumCodeToHtml(string text) { text = Censor(text); text = CleanForumCode(text); text = CleanForumCodeToHtml(text); if (text == "<p></p>") text = String.Empty; return text; } public string EscapeHtmlAndCensor(string text) { text = Censor(text); return EscapeHtmlTags(text); } /// <summary> /// Converts client HTML from the browser to HTML for storage. This method wraps <see cref="ClientHtmlToForumCode(string)"/> and <see cref="ForumCodeToHtml(string)"/>, and censors the text. /// </summary> /// <param name="text">Text to parse.</param> /// <returns>Parsed text.</returns> public string ClientHtmlToHtml(string text) { text = Censor(text); text = ClientHtmlToForumCode(text); text = CleanForumCode(text); return CleanForumCodeToHtml(text); } public string HtmlToClientHtml(string text) { text = text.Replace("<blockquote>", "[quote]"); text = text.Replace("</blockquote>", "[/quote]"); text = Regex.Replace(text, @" *target=""[_\w]*""", String.Empty, RegexOptions.IgnoreCase); text = Regex.Replace(text, @"(<iframe )(\S+ )*(src=""http://www.youtube.com/embed/)(\S+)("")( *\S+)*( */iframe>)", "http://www.youtube.com/watch?v=$4", RegexOptions.IgnoreCase); return text; } public string HtmlToForumCode(string text) { text = HtmlToClientHtml(text); text = ClientHtmlToForumCode(text); return text; } public string Censor(string text) { if (String.IsNullOrEmpty(text)) return String.Empty; // build the censored words list var words = _settingsManager.Current.CensorWords.Trim(); if (String.IsNullOrWhiteSpace(words)) return text; var cleanedCensorList = words.Replace(" ", " ").Replace("\r", " "); var list = cleanedCensorList.Split(new [] { ' ' }); // convert any stand alone words (with * before of after them) to spaces for (var i = 0; i < list.Length; i++) { list[i] = list[i].Replace("*", " "); } // now you've got your list of naughty words, clean them out of the text var newWord = String.Empty; for (var i = 0; i < list.Length; i++) { for (var j = 1; j <= list[i].Length; j++) newWord += _settingsManager.Current.CensorCharacter; text = Regex.Replace(text, list[i], newWord, RegexOptions.IgnoreCase); newWord = String.Empty; } return text; } /// <summary> /// Converts client HTML to forum code. Important: This method does NOT attempt to create valid HTML, as it assumes that the forum code /// will be cleaned. This method should generally not be called directly except for testing. /// </summary> /// <param name="text">Text to parse.</param> /// <returns>Parsed text.</returns> public string ClientHtmlToForumCode(string text) { text = text.Trim(); // replace line breaks, get block elements right text = text.Replace("\r\n", String.Empty); text = text.Replace("\n", String.Empty); text = Regex.Replace(text, @"((?<!(\A|<blockquote>|</blockquote>|</p>))(<blockquote>|<p>))", "</p>$1", RegexOptions.IgnoreCase); text = Regex.Replace(text, @"(</blockquote>|</p>)((?!(<p>|<blockquote>|</blockquote>))(.*</p>))", "$1<p>$2", RegexOptions.IgnoreCase); text = Regex.Replace(text, "^<p>", String.Empty, RegexOptions.IgnoreCase); text = Regex.Replace(text, "</p>$", String.Empty, RegexOptions.IgnoreCase); text = Regex.Replace(text, "<blockquote>", "\r\n[quote]", RegexOptions.IgnoreCase); text = Regex.Replace(text, "</blockquote>", "[/quote]\r\n", RegexOptions.IgnoreCase); text = Regex.Replace(text, "<p>", "\r\n", RegexOptions.IgnoreCase); text = Regex.Replace(text, "</p>", "\r\n", RegexOptions.IgnoreCase); text = Regex.Replace(text, "<br ?/?>", "\r\n", RegexOptions.IgnoreCase); text = Regex.Replace(text, @"\[quote\](?!(\r\n))", "[quote]\r\n", RegexOptions.IgnoreCase); text = Regex.Replace(text, @"(?<!(\r\n))\[/quote\]", "\r\n[/quote]", RegexOptions.IgnoreCase); // replace basic tags text = Regex.Replace(text, @"<em>", "[i]", RegexOptions.IgnoreCase); text = Regex.Replace(text, @"</em>", "[/i]", RegexOptions.IgnoreCase); text = Regex.Replace(text, @"<i>", "[i]", RegexOptions.IgnoreCase); text = Regex.Replace(text, @"</i>", "[/i]", RegexOptions.IgnoreCase); text = Regex.Replace(text, @"<strong>", "[b]", RegexOptions.IgnoreCase); text = Regex.Replace(text, @"</strong>", "[/b]", RegexOptions.IgnoreCase); text = Regex.Replace(text, @"<b>", "[b]", RegexOptions.IgnoreCase); text = Regex.Replace(text, @"</b>", "[/b]", RegexOptions.IgnoreCase); text = Regex.Replace(text, @"<code>", "[code]", RegexOptions.IgnoreCase); text = Regex.Replace(text, @"</code>", "[/code]", RegexOptions.IgnoreCase); text = Regex.Replace(text, @"<pre>", "[pre]", RegexOptions.IgnoreCase); text = Regex.Replace(text, @"</pre>", "[/pre]", RegexOptions.IgnoreCase); text = Regex.Replace(text, @"<li>", "[li]", RegexOptions.IgnoreCase); text = Regex.Replace(text, @"</li>", "[/li]", RegexOptions.IgnoreCase); text = Regex.Replace(text, @"<ol>", "[ol]", RegexOptions.IgnoreCase); text = Regex.Replace(text, @"</ol>", "[/ol]", RegexOptions.IgnoreCase); text = Regex.Replace(text, @"<ul>", "[ul]", RegexOptions.IgnoreCase); text = Regex.Replace(text, @"</ul>", "[/ul]", RegexOptions.IgnoreCase); text = Regex.Replace(text, @"</a>", "[/url]", RegexOptions.IgnoreCase); // replace img and a tags text = Regex.Replace(text, @"(<a href="")(\S+)""( *target=""?[_\w]*""?)*>", "[url=$2]", RegexOptions.IgnoreCase); text = Regex.Replace(text, @"(<img )(\S+ )*(src="")(\S+)("")( *\S+)*( */?>)", "[image=$4]", RegexOptions.IgnoreCase); text = Regex.Replace(text, @"(<iframe )(\S+ )*(src=""http://www.youtube.com/embed/)(\S+)("")( *\S+)*( */iframe>)", "[youtube=http://www.youtube.com/watch?v=$4]", RegexOptions.IgnoreCase); // catch remaining HTML as invalid text = Regex.Replace(text, @"<.*>", String.Empty, RegexOptions.IgnoreCase); // convert HTML escapes text = Regex.Replace(text, "&nbsp;", " ", RegexOptions.IgnoreCase); text = Regex.Replace(text, "&amp;", "&", RegexOptions.IgnoreCase); text = Regex.Replace(text, "&lt;", "<", RegexOptions.IgnoreCase); text = Regex.Replace(text, "&gt;", ">", RegexOptions.IgnoreCase); return text.Trim(); } /// <summary> /// Cleans forum code by making sure tags are properly closed, escapes HTML, removes images if settings require it, removes extra line breaks /// and marks up URL's and e-mail addresses as links. This method should generally not be called directly except for testing. /// </summary> /// <param name="text">Text with forum code to clean.</param> /// <returns>Cleaned forum code text.</returns> public string CleanForumCode(string text) { // ditch white space text = text.Trim(); // replace lonely \n (some browsers) text = Regex.Replace(text, @"((?<!\r)\n)", "\r\n", RegexOptions.Multiline | RegexOptions.IgnoreCase); // remove duplicate line breaks text = Regex.Replace(text, @"(\r\n){3,}", "\r\n\r\n", RegexOptions.Multiline); // handle images if (_settingsManager.Current.AllowImages) text = Regex.Replace(text, @"(\[image){1}(?!\=).+?\]", String.Empty, RegexOptions.IgnoreCase); else text = Regex.Replace(text, @"\[image=.+?\]", String.Empty, RegexOptions.IgnoreCase); // close all tags var stack = new Stack<string>(); var allMatches = _tagPattern.Match(text); var indexAdjustment = 0; while (allMatches.Success) { var tag = allMatches.ToString(); if (!tag.StartsWith("[/")) { // opening tag var tagID = _tagID.Replace(tag, "$1"); if (AllowedCloseableTags.Contains(tagID)) stack.Push(tagID); } else { // closing tag var tagID = _tagID.Replace(tag, "$1"); if (stack.Count == 0 || !stack.Contains(tagID)) { // prepend with opener if (tagID == "url") { var tagIndex = allMatches.Index; text = text.Remove(tagIndex + indexAdjustment, 6); indexAdjustment -= 6; } else if (tagID == "youtube") { var tagIndex = allMatches.Index; text = text.Remove(tagIndex + indexAdjustment, 10); indexAdjustment -= 10; } else { var opener = String.Format("[{0}]", tagID); text = opener + text; } } else if (AllowedCloseableTags.Contains(tagID) && tagID == stack.Peek()) stack.Pop(); else { // close then reopen tag var miniStack = new Stack<string>(); var tagIndex = allMatches.Index; while (tagID != stack.Peek()) { miniStack.Push(stack.Peek()); var closer = String.Format("[/{0}]", miniStack.Peek()); text = text.Insert(tagIndex + indexAdjustment, closer); indexAdjustment += closer.Length; stack.Pop(); } stack.Pop(); while (miniStack.Count > 0) { var opener = String.Format("[{0}]", miniStack.Peek()); text = text.Insert(tagIndex + indexAdjustment + tag.Length, opener); stack.Push(miniStack.Pop()); indexAdjustment += opener.Length; } } } allMatches = allMatches.NextMatch(); } while (stack.Count != 0) { // add closers var closer = String.Format("[/{0}]", stack.Peek()); text += closer; stack.Pop(); } // put URL's in url tags (plus youtube) if (_settingsManager.Current.AllowImages) text = _youTubePattern.Replace(text, match => String.Format("[youtube={0}]", match.Value)); text = _protocolPattern.Replace(text, match => String.Format("[url={0}]{1}[/url]", match.Value, match.Value.Trimmer(80))); text = _wwwPattern.Replace(text, match => String.Format("[url=http://{0}]{1}[/url]", match.Value, match.Value.Trimmer(80))); text = _emailPattern.Replace(text, match => String.Format("[url=mailto:{0}]{0}[/url]", match.Value)); // escape out rogue HTML tags text = EscapeHtmlTags(text); return text; } private static string EscapeHtmlTags(string text) { text = text.Replace("<", "&lt;"); text = text.Replace(">", "&gt;"); return text; } /// <summary> /// Converts forum code to HTML for storage. Important: This method does NOT attempt to create valid HTML, as it assumes that the forum code is /// already well-formed. This method should generally not be called directly except for testing. /// </summary> /// <param name="text">Text to parse.</param> /// <returns>Parsed text.</returns> public string CleanForumCodeToHtml(string text) { text = text.Trim(); // replace URL tags text = Regex.Replace(text, @"(\[url=""?)(\S+?)(""?\])", "<a href=\"$2\" target=\"_blank\">", RegexOptions.IgnoreCase); text = Regex.Replace(text, @"(<a href=\""mailto:)(\S+?)(\"" target=\""_blank\"">)", "<a href=\"mailto:$2\">", RegexOptions.IgnoreCase); text = text.Replace("[/url]", "</a>"); text = Regex.Replace(text, @"<(?=a)\b[^>]*>", match => match.Value.Replace("javascript:", String.Empty), RegexOptions.IgnoreCase); // replace image tags if (_settingsManager.Current.AllowImages) { text = Regex.Replace(text, @"(\[img\])(\S+?)(\[/img\])", "<img src=\"$2\" />", RegexOptions.IgnoreCase); text = Regex.Replace(text, @"(\[image=""?)(\S+?)(""?\])", "<img src=\"$2\" />", RegexOptions.IgnoreCase); text = ParseYouTubeTags(text); } else text = Regex.Replace(text, @"(\[image=""?)(\S+?)(""?\])", String.Empty, RegexOptions.IgnoreCase); // simple tags text = text.Replace("[i]", "<em>"); text = text.Replace("[/i]", "</em>"); text = text.Replace("[b]", "<strong>"); text = text.Replace("[/b]", "</strong>"); text = text.Replace("[code]", "<code>"); text = text.Replace("[/code]", "</code>"); text = text.Replace("[pre]", "<pre>"); text = text.Replace("[/pre]", "</pre>"); text = text.Replace("[li]", "<li>"); text = text.Replace("[/li]", "</li>"); text = text.Replace("[ol]", "<ol>"); text = text.Replace("[/ol]", "</ol>"); text = text.Replace("[ul]", "<ul>"); text = text.Replace("[/ul]", "</ul>"); // line breaks and block elements text = Regex.Replace(text, @"(\r\n){3,}", "\r\n\r\n"); if (!text.StartsWith("[quote]")) text = "<p>" + text; if (!text.EndsWith("[/quote]")) text += "</p>"; text = text.Replace("[quote]", "<blockquote>"); text = text.Replace("[/quote]", "</blockquote>"); text = Regex.Replace(text, @"(?<!(</blockquote>))\r\n\r\n(?!(<p>|<blockquote>|</blockquote>))", "</p><p>", RegexOptions.IgnoreCase); text = Regex.Replace(text, @"(?<=(</p>|<blockquote>|</blockquote>|\A))(\r\n)*<blockquote>", "<blockquote>", RegexOptions.IgnoreCase); text = Regex.Replace(text, @"(\r\n)+<blockquote>", "</p><blockquote>", RegexOptions.IgnoreCase); text = Regex.Replace(text, @"<blockquote>\r\n(?!(<p>|<blockquote>|</blockquote>))", "<blockquote><p>", RegexOptions.IgnoreCase); text = Regex.Replace(text, @"(?<!([</p>|<blockquote>|</blockquote>](\r\n)*))</blockquote>", "</p></blockquote>", RegexOptions.IgnoreCase); text = Regex.Replace(text, @"</blockquote>(\r\n){2,}(?!(</p>|<blockquote>|</blockquote>))", "</blockquote><p>", RegexOptions.IgnoreCase); text = Regex.Replace(text, @"</blockquote>(\r\n)*</blockquote>", "</blockquote></blockquote>", RegexOptions.IgnoreCase); text = Regex.Replace(text, @"(?<!(</p>|<blockquote>|</blockquote>|\A))<blockquote>", "</p><blockquote>", RegexOptions.IgnoreCase); text = Regex.Replace(text, @"<blockquote>(?!(<p>|<blockquote>|</blockquote>))", "<blockquote><p>", RegexOptions.IgnoreCase); text = Regex.Replace(text, @"(?<!(</p>|<blockquote>|</blockquote>))(\r\n)*</blockquote>", "</p></blockquote>", RegexOptions.IgnoreCase); text = Regex.Replace(text, @"</blockquote>(\r\n)*(?!(<p>|<blockquote>|</blockquote>|\Z))", "</blockquote><p>", RegexOptions.IgnoreCase); text = text.Replace("\r\n", "<br />"); return text; } private string ParseYouTubeTags(string text) { var width = _settingsManager.Current.YouTubeWidth; var height = _settingsManager.Current.YouTubeHeight; var youTubeTag = new Regex(@"(\[youtube=""?)(\S+?)(""?\])", RegexOptions.Compiled | RegexOptions.IgnoreCase); var matches = youTubeTag.Matches(text); foreach (Match item in matches) { var url = item.Groups[2].Value; var uri = new Uri(url); if (uri.Host.Contains("youtube")) { var q = uri.Query.Remove(0, 1).Split('&').Where(x => x.Contains("=")).Select(x => new KeyValuePair<string, string>(x.Split('=')[0], x.Split('=')[1])); var dictionary = q.ToDictionary(pair => pair.Key, pair => pair.Value); if (dictionary.Any(x => x.Key == "v")) { text = text.Replace(item.Value, String.Format(@"<iframe width=""{1}"" height=""{2}"" src=""http://www.youtube.com/embed/{0}"" frameborder=""0"" allowfullscreen></iframe>", dictionary["v"], width, height)); } } else if (uri.Host.Contains("youtu.be")) { var v = uri.Segments[1]; text = text.Replace(item.Value, String.Format(@"<iframe width=""{1}"" height=""{2}"" src=""http://www.youtube.com/embed/{0}"" frameborder=""0"" allowfullscreen></iframe>", v, width, height)); } } return text; } } }