content stringlengths 5 1.04M | avg_line_length float64 1.75 12.9k | max_line_length int64 2 244k | alphanum_fraction float64 0 0.98 | licenses list | repository_name stringlengths 7 92 | path stringlengths 3 249 | size int64 5 1.04M | lang stringclasses 2
values |
|---|---|---|---|---|---|---|---|---|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using LotteryLib.Model;
using LotteryLib.Tools;
namespace LotteryGuesserFrameworkWpf
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
//Lottery = new LotteryHandler(Enums.LotteryType.TheFiveNumberDraw, "Whem", true, true);
//LotteryHandler.LotteryModelEvent += LotteryHandlerOnLotteryModelEvent;
//Lottery.CalculateNumbers(Enums.TypesOfDrawn.All, Enums.GenerateType.EachByEach, 2);
//Lottery.CalculateNumbers(Enums.TypesOfDrawn.All, Enums.GenerateType.GetTheBest, 1000);
//Lottery.UseEarlierWeekPercentageForNumbersDraw(Enums.TypesOfDrawn.Calculated);
//Lottery.CalculateNumbers(Enums.TypesOfDrawn.ByDistributionBasedCurrentDraw, Enums.GenerateType.Unique, 1);
//Lottery.SaveDataToGoogleSheet();
}
}
| 30 | 116 | 0.741667 | [
"MIT"
] | Whem/lotteryGuesser | src/LotteryGuesserFrameworkWpf/LotteryGuesserFrameworkWpf/MainWindow.xaml.cs | 1,322 | C# |
using Atomiv.Infrastructure.Selenium.IntegrationTest.Pages;
namespace Atomiv.Infrastructure.Selenium.IntegrationTest.App
{
public class ToolsQAApp : App<ToolsQAAutomationPracticeFormPage>
{
public ToolsQAApp(Driver driver)
: base(driver)
{
}
public ToolsQAAutomationPracticeFormPage NavigateToPracticeFormPage()
{
return new ToolsQAAutomationPracticeFormPage(Finder, true);
}
}
} | 27.411765 | 77 | 0.686695 | [
"MIT"
] | atomiv/atomiv-cs | test/Infrastructure/Selenium.IntegrationTest/App/ToolsQAApp.cs | 468 | C# |
using Microsoft.EntityFrameworkCore;
using WebAppMovies.Models;
namespace WebAppMovies.Contexts
{
public class ApplicationContext : DbContext
{
#pragma warning disable CS8618 // Pole niedopuszczające wartości null musi zawierać wartość inną niż null podczas kończenia działania konstruktora. Rozważ zadeklarowanie pola jako dopuszczającego wartość null.
public ApplicationContext(DbContextOptions<ApplicationContext> options) : base(options) { }
#pragma warning restore CS8618 // Pole niedopuszczające wartości null musi zawierać wartość inną niż null podczas kończenia działania konstruktora. Rozważ zadeklarowanie pola jako dopuszczającego wartość null.
public DbSet<Developer> Developers { get; set; }
public DbSet<Project> Projects { get; set; }
}
}
| 46.705882 | 209 | 0.787154 | [
"MIT"
] | juliuszlosinski/.NET_Projects | .NET Core/ASP.NET/MoviesApp/WebAppMovies/Contexts/ApplicationContext.cs | 822 | C# |
using System;
using System.Linq;
using Newtonsoft.Json;
using System.Threading;
using System.Diagnostics;
using JabbR_Core.Services;
using JabbR_Core.Commands;
using JabbR_Core.ViewModels;
using JabbR_Core.Data.Models;
using System.Threading.Tasks;
using JabbR_Core.Infrastructure;
using System.Collections.Generic;
using JabbR_Core.Data.Repositories;
using Microsoft.AspNetCore.SignalR;
using Microsoft.Extensions.Options;
using Microsoft.EntityFrameworkCore;
namespace JabbR_Core.Hubs
{
public class Chat : Hub, INotificationService
{
// Never assigned to, always null
private readonly ICache _cache;
private readonly ILogger _logger;
private readonly IChatService _chatService;
private readonly ApplicationSettings _settings;
private readonly IJabbrRepository _repository;
private readonly IRecentMessageCache _recentMessageCache;
private static readonly TimeSpan _disconnectThreshold = TimeSpan.FromSeconds(10);
public Chat(
IJabbrRepository repository,
IOptions<ApplicationSettings> settings,
IRecentMessageCache recentMessageCache,
IChatService chatService)
{
// Request the injected object instances
_repository = repository;
_chatService = chatService;
_recentMessageCache = recentMessageCache;
_settings = settings.Value;
}
private string UserAgent
{
get
{
if (Context.Headers != null)
{
return Context.Headers["User-Agent"];
}
return null;
}
}
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)
{
// 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
_chatService.AddClient(user, Context.ConnectionId, UserAgent);
}
else
{
// Update some user values
_chatService.UpdateActivity(user, Context.ConnectionId, UserAgent);
_repository.CommitChanges();
}
ClientState clientState = GetClientState();
// This function is being manually called here to establish
// your identity to SignalR and update the UI to match. In
// original JabbR it isn't called explicitly anywhere, so
// something about the natural authentication data flow
// establishes this in SignalR for us. For now, call explicitly
//Delete this in the future (when auth is setup properly)
var userViewModel = new UserViewModel(user);
Clients.Caller.userNameChanged(userViewModel);
OnUserInitialize(clientState, user, reconnecting);
}
public List<LobbyRoomViewModel> GetRooms()
{
//return _lobbyRoomList;
return _repository.Rooms.Select(r => new LobbyRoomViewModel()
{
Name = r.Name,
Count = r.Users.Count,
Private = r.Private,
Closed = r.Closed,
Topic = r.Topic
}).ToList();
}
public IEnumerable<CommandMetaData> GetCommands()
{
return CommandManager.GetCommandsMetaData();
}
// More specific return type? Object[]? or cast to Array?
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 void LoadRooms(string[] roomNames)
{
string userId = Context.User.GetUserId();
ChatUser user = _repository.VerifyUserId(userId);
// Can't async whenall because we'd be hitting a single
// EF context with multiple concurrent queries.
var rooms = _repository.Rooms
.Where(r => roomNames.Contains(r.Name)).ToList();
foreach (var room in rooms)
{
if (room == null || (room.Private && !user.AllowedRooms.Select(u => u.ChatRoomKeyNavigation).Contains(room)))
{
continue;
}
RoomViewModel roomInfo = null;
while (true)
{
try
{
// If invoking roomLoaded fails don't get the roomInfo again
roomInfo = roomInfo ?? GetRoomInfoCore(room);
Clients.Caller.roomLoaded(roomInfo);
break;
}
catch (Exception ex)
{
// Logger is null
//_logger.Log(ex);
}
}
}
}
public void UpdateActivity()
{
string userId = Context.User.GetUserId();
ChatUser user = _repository.GetUserById(userId);
foreach (var room in user.Rooms.Select(u => u.ChatRoomKeyNavigation).ToList())
{
UpdateActivity(user, room);
}
//CheckStatus();
}
private void UpdateActivity(ChatUser user, ChatRoom room)
{
UpdateActivity(user);
OnUpdateActivity(user, room);
}
private void OnUpdateActivity(ChatUser user, ChatRoom room)
{
var userViewModel = new UserViewModel(user);
Clients.Group(room.Name).updateActivity(userViewModel, room.Name);
}
private void UpdateActivity(ChatUser user)
{
_chatService.UpdateActivity(user, Context.ConnectionId, UserAgent);
_repository.CommitChanges();
}
public bool Send(string content, string roomName)
{
var message = new ClientMessage
{
Content = content, // '/join light_meow'
Room = roomName, // 'Lobby'
};
return Send(message);
}
public bool Send(ClientMessage clientMessage)
{
//Commented out for resting purposes
// TODO: set env variable
//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();
ChatUser user = _repository.VerifyUserId(userId);
// this line breaks when we message in a new room
ChatRoom room = _repository.VerifyUserRoom(_cache, user, clientMessage.Room);
if (room == null || (room.Private && user.AllowedRooms.Select(r => r.ChatRoomKeyNavigation).ToList().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));
}
// Update activity *after* ensuring the user, this forces them to be active
UpdateActivity(user, room);
// Create a true unique id and save the message to the db
string id = Guid.NewGuid().ToString("d");
// Ensure the message is logged
ChatMessage chatMessage = _chatService.AddMessage(user, room, id, clientMessage.Content);
room.ChatMessages.Add(chatMessage);
// Save changes
_repository.CommitChanges();
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 CheckStatus()
{
if (OutOfSync)
{
Clients.Caller.outOfSync();
}
}
private bool OutOfSync
{
get
{
string version = Context.QueryString["version"];
if (String.IsNullOrEmpty(version))
{
return true;
}
//return new Version(version) != Constants.JabbRVersion;
return false;
}
}
public bool TryHandleCommand(string command, string room)
{
string clientId = Context.ConnectionId;
string userId = Context.User.GetUserId();
var commandManager = new CommandManager(clientId, UserAgent, userId, room, _chatService, _repository, _cache, this);
return commandManager.TryHandleCommand(command);
}
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.Select(r => r.ChatRoomKeyNavigation).Contains(room);
Clients.Caller.joinRoom(roomViewModel);
// 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);
}
}
public 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.Select(r => r.ChatRoomKeyNavigation).Contains(room)))
{
return null;
}
return GetRoomInfoCore(room);
//return new Task<RoomViewModel>(() => thing);
}
private 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 = _repository.GetMessagesByRoom(room)
.Take(50)
.OrderBy(o => o.When)
.ToList();
recentMessages = messages.Select(m => new MessageViewModel(m)).ToList();
_recentMessageCache.Add(room.Name, recentMessages);
}
List<ChatUser> onlineUsers = _repository.GetOnlineUsers(room).ToList();
return new RoomViewModel
{
Name = room.Name,
Users = from u in onlineUsers
select new UserViewModel(u),
Owners = _repository.GetRoomOwners(room).Online().Select(n => n.Name),
RecentMessages = recentMessages,
Topic = room.Topic ?? string.Empty,
Welcome = room.Welcome ?? String.Empty,
Closed = room.Closed
};
}
void INotificationService.LogOn(ChatUser user, string clientId)
{
LogOn(user, clientId, reconnecting: true);
}
void INotificationService.KickUser(ChatUser targetUser, ChatRoom room, ChatUser callingUser, string reason)
{
var targetUserViewModel = new UserViewModel(targetUser);
var callingUserViewModel = new UserViewModel(callingUser);
if (String.IsNullOrWhiteSpace(reason))
{
reason = null;
}
Clients.Group(room.Name).kick(targetUserViewModel, room.Name, callingUserViewModel, reason);
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.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, ChatUser callingUser)
{
// Kick the user from the room when they are unallowed
((INotificationService)this).KickUser(targetUser, targetRoom, callingUser, null);
// 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.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(user.Hash);
// Create the view model
var userViewModel = new UserViewModel(user);
// Tell all users in rooms to change the gravatar
foreach (var room in user.Rooms.Select(u => u.ChatRoomKeyNavigation))
{
Clients.Group(room.Name).changeGravatar(userViewModel, room.Name);
}
}
void INotificationService.OnSelfMessage(ChatRoom room, ChatUser user, string content)
{
Clients.Caller.sendMeMessage(user.Name, content, room.Name);
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.Select(r => r.ChatRoomKeyNavigation).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.ChatUserKeyNavigation.Name));
}
void INotificationService.ListOwners(ChatRoom room)
{
Clients.Caller.listOwners(room.Name, room.Owners.Select(s => s.ChatUserKeyNavigation.Name), room.CreatorKeyNavigation != null ? room.CreatorKeyNavigation.Name : null);
}
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
Clients.Caller.roomClosed(room.Name);
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)
{
var clients = new List<ChatClient>(user.ConnectedClients);
foreach (var client in clients)
{
DisconnectClient(client.Id);
Clients.Client(client.Id).logOut();
}
}
private void DisconnectClient(string clientId, bool useThreshold = false)
{
string userId = _chatService.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.ChatRoomKeyNavigation.Name).leave(userViewModel, room.ChatRoomKeyNavigation.Name);
}
}
}
void INotificationService.ShowUserInfo(ChatUser user)
{
string userId = Context.User.GetUserId();
Clients.Caller.showUserInfo(new
{
Name = user.Name,
OwnedRooms = user.OwnedRooms
.Select(r => r.ChatRoomKeyNavigation)
.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.Select(r => r.ChatRoomKeyNavigation).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);
}
private void LeaveRoom(ChatUser user, ChatRoom room)
{
var userViewModel = new UserViewModel(user);
//TODO Remove explicit hub call
Clients.Caller.leave(userViewModel, room.Name);
Clients.Group(room.Name).leave(userViewModel, room.Name);
foreach (var client in user.ConnectedClients)
{
Groups.Remove(client.Id, room.Name);
}
OnRoomChanged(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.Select(u => u.ChatRoomKeyNavigation))
{
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.Select(u => u.ChatRoomKeyNavigation))
{
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.Select(u => u.ChatRoomKeyNavigation))
{
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.Select(u => u.ChatRoomKeyNavigation))
{
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.Select(u => u.ChatRoomKeyNavigation))
{
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.Select(u => u.ChatRoomKeyNavigation))
{
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;
return "";
}
void INotificationService.BanUser(ChatUser targetUser, ChatUser callingUser, string reason)
{
var rooms = targetUser.Rooms.Select(x => x.ChatRoomKeyNavigation.Name).ToArray();
var targetUserViewModel = new UserViewModel(targetUser);
var callingUserViewModel = new UserViewModel(callingUser);
if (String.IsNullOrWhiteSpace(reason))
{
reason = null;
}
// We send down room so that other clients can display that the user has been banned
foreach (var room in rooms)
{
Clients.Group(room).ban(targetUserViewModel, room, callingUserViewModel, reason);
}
foreach (var client in targetUser.ConnectedClients)
{
foreach (var room in rooms)
{
// Remove the user from this the room group so he doesn't get the general ban message
Groups.Remove(client.Id, room);
}
}
}
void INotificationService.UnbanUser(ChatUser targetUser)
{
Clients.Caller.unbanUser(new
{
Name = targetUser.Name
});
}
void INotificationService.CheckBanned()
{
// Get all users that are banned
var users = _repository.Users.Where(u => u.IsBanned)
.Select(u => u.Name)
.OrderBy(u => u);
Clients.Caller.listUsers(users);
}
void INotificationService.CheckBanned(ChatUser user)
{
Clients.Caller.checkBanned(new
{
Name = user.Name,
IsBanned = user.IsBanned
});
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
// Let the DI Container handle disposing the repo
//_repository.Dispose();
}
base.Dispose(disposing);
}
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.ChatRoomKeyNavigation.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);
}
private void LogOn(ChatUser user, string clientId, bool reconnecting)
{
// When id, name, hash and unreadNotifications are uncommented we get this error
// 'Microsoft.AspNetCore.SignalR.Hubs.SignalProxy' does not contain a definition for 'name'
// When this is resolved we can get rid of the direct call to
// Clients.Caller.usernamechanged() on line 99
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 rooms = new List<RoomViewModel>();
var privateRooms = new List<LobbyRoomViewModel>();
var userViewModel = new UserViewModel(user);
var ownedRooms = user.OwnedRooms.Select(r => r.ChatRoomKey);
foreach (var room in user.Rooms.Select(u => u.ChatRoomKeyNavigation))
{
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)
{
foreach (var r in user.AllowedRooms.Select(r => r.ChatRoomKeyNavigation).ToList())
{
privateRooms.Add(new LobbyRoomViewModel
{
Name = r.Name,
Count = _repository.GetOnlineUsers(r).Count(),
Private = r.Private,
Closed = r.Closed,
Topic = r.Topic
});
}
// Initialize the chat with the rooms the user is in
Clients.Caller.logOn(rooms, privateRooms, user.Preferences);
}
}
}
}
| 35.75493 | 179 | 0.564195 | [
"MIT"
] | MachUpskillingFY17/JabbR-Core | src/JabbR-Core/Hubs/Chat.cs | 38,081 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("005.Hospital")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("005.Hospital")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("9090eec8-95c3-418b-9ed8-30c8652ddc06")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.756757 | 84 | 0.743737 | [
"MIT"
] | yangra/SoftUni | ProgrammingBasics/05.Loops/005.Hospital/Properties/AssemblyInfo.cs | 1,400 | C# |
#region Using Directives
using System;
using System.Data;
using System.Collections.Generic;
using System.Linq;
using System.Data.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml.Linq;
using System.IO;
#endregion
namespace KeepAliveHD.Database
{
public class DriveInfo
{
#region Members
public int ID { get; set; }
public string Drive { get; set; }
public List<string> VolumeNames { get; set; }
//public string VolumeName { get; set; }
/// <summary>
/// Operation type.
/// </summary>
public string Operation { get; set; }
/// <summary>
/// Time interval in minutes.
/// </summary>
public int TimeInterval { get; set; }
/// <summary>
/// Unit of time interval (second, minute, hour).
/// </summary>
public string TimeUnit { get; set; }
/// <summary>
/// Drive status.
/// </summary>
public int Status { get; set; }
public bool Connected { get; set; }
#endregion
}
}
| 21.038462 | 57 | 0.566728 | [
"MIT"
] | dws14159/KeepAliveHD | KeepAliveHD/Database/DriveInfo.cs | 1,096 | C# |
/*
* Copyright 2018 JDCLOUD.COM
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http:#www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* SCDN相关接口
* Openapi For JCLOUD cdn
*
* OpenAPI spec version: v1
* Contact: pid-cdn@jd.com
*
* NOTE: This class is auto generated by the jdcloud code generator program.
*/
using JDCloudSDK.Core.Client;
using JDCloudSDK.Core.Http;
using System;
using System.Collections.Generic;
using System.Text;
namespace JDCloudSDK.Cdn.Client
{
/// <summary>
/// 启用WAF白名单
/// </summary>
public class EnableWafWhiteRulesExecutor : JdcloudExecutor
{
/// <summary>
/// 启用WAF白名单接口的Http 请求方法
/// </summary>
public override string Method
{
get {
return "POST";
}
}
/// <summary>
/// 启用WAF白名单接口的Http资源请求路径
/// </summary>
public override string Url
{
get {
return "/domain/{domain}/wafWhiteRule:enable";
}
}
}
}
| 24.9 | 76 | 0.628514 | [
"Apache-2.0"
] | jdcloud-api/jdcloud-sdk-net | sdk/src/Service/Cdn/Client/EnableWafWhiteRulesExecutor.cs | 1,564 | C# |
using System;
using Unity.Entities;
using UnityEngine;
namespace ScriptsAndPrefabs.Player {
[GenerateAuthoringComponent]
[Serializable]
public struct PlayerSettings_AC : IComponentData {
[Header("Mouse sensibility")] public float sensibilityHor;
public float sensibilityVert;
public float bulletVelocity;
public float weaponCooldown;
[Header("Look mouse type")] public bool useRightClickLook;
}
} | 19.857143 | 60 | 0.784173 | [
"MIT"
] | nulleof/ar_ecs_demo | Assets/ScriptsAndPrefabs/Player/PlayerSettings_AC.cs | 417 | C# |
using BackEndBase.Application.Concretes;
using BackEndBase.Application.Interfaces;
using BackEndBase.DataAccess.Context;
using BackEndBase.DataAccess.Repositories;
using BackEndBase.Domain.Bus;
using BackEndBase.Domain.CommandHandlers;
using BackEndBase.Domain.Commands;
using BackEndBase.Domain.Events;
using BackEndBase.Domain.Interfaces.Data;
using BackEndBase.Domain.Interfaces.Notifications;
using BackEndBase.Domain.Interfaces.Services;
using BackEndBase.Domain.Notifications;
using BackEndBase.Domain.Services;
using BackEndBase.Infra.CrossCutting.Bus;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
namespace BackEndBase.Infra.CrossCutting.IoC
{
public static class NativeInjectorBootStrapper
{
public static void RegisterServices(IServiceCollection service)
{
service.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
service.AddScoped<BaseContext>();
//Application
service.AddScoped<IUserApplication, UserApplication>();
//Service
service.AddScoped<IUserService, UserService>();
service.AddScoped<ITokenService, TokenService>();
//Events
service.AddScoped<IDomainNotificationHandler<DomainNotification>, DomainNotificationHandler>();
//CommandHandler
service.AddScoped<IHandler<AddUserCommand>, UserCommandHandler>();
//Bus
service.AddScoped<IBus, InMemoryBus>();
//Repository
service.AddScoped<IUserRepository, UserRepository>();
}
}
} | 33.625 | 107 | 0.729244 | [
"MIT"
] | skellbr/BackEndBase | BackEndBase.Infra.CrossCutting.IoC/NativeInjectorBootStrapper.cs | 1,616 | C# |
// <copyright file="IGraph.cs" company="Microsoft Corporation">
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
// </copyright>
namespace Sample.IncidentBot.Interface
{
using System.Threading.Tasks;
using Microsoft.Graph;
/// <summary>
/// Interface for Graph.
/// </summary>
public interface IGraph
{
/// <summary>
/// Get graph service client.
/// </summary>
/// <returns>Graph service client.</returns>
GraphServiceClient GetGraphServiceClient();
/// <summary>
/// Creates online meeting.
/// </summary>
/// <param name="graphServiceClient">GraphServiceClient instance.</param>
/// <param name="onlineMeeting">OnlineMeeting instance.</param>
/// <returns>Online meeting details.</returns>
Task<OnlineMeeting> CreateOnlineMeetingAsync(GraphServiceClient graphServiceClient, OnlineMeeting onlineMeeting);
}
}
| 31.935484 | 121 | 0.650505 | [
"MIT"
] | Saikrishna-MSFT/microsoft-graph-comms-samples | Samples/V1.0Samples/RemoteMediaSamples/IncidentBot/Interface/IGraph.cs | 992 | C# |
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using RyanJuan.Minerva.Common;
namespace RyanJuan.Minerva.SqlClientHelper
{
public static partial class MinervaSqlClient
{
/// <summary>
/// 執行查詢,並傳回查詢所傳回的結果集中唯一一筆資料,如果沒有資料,則為預設值。
/// 如果結果集中有多個項目,則這個方法會擲回例外狀況。
/// <para>
/// 會以 <see cref="SqlCommand.Parameters"/> 呼叫
/// <see cref="AddWithValues(SqlParameterCollection, object[])"/> 以存入參數。
/// </para>
/// </summary>
/// <typeparam name="T">查詢結果的資料型別。</typeparam>
/// <param name="command"><see cref="SqlCommand"/> 物件。</param>
/// <param name="parameters">用於查詢的參數物件。</param>
/// <returns>查詢結果。</returns>
/// <exception cref="ArgumentNullException"></exception>
/// <exception cref="ArgumentException"></exception>
/// <exception cref="InvalidCastException"></exception>
/// <exception cref="SqlException"></exception>
/// <exception cref="System.IO.IOException"></exception>
/// <exception cref="InvalidOperationException"></exception>
/// <exception cref="ObjectDisposedException"></exception>
public static T FetchFirst<T>(
this SqlCommand command,
params object[] parameters)
{
return s_core.FetchFirst<T>(
command,
parameters);
}
/// <summary>
/// 非同步版本的 <see cref="FetchFirst{T}(SqlCommand, object[])"/>。
/// 執行查詢,並傳回查詢所傳回的結果集中唯一一筆資料,如果沒有資料,則為預設值。
/// 如果結果集中有多個項目,則這個方法會擲回例外狀況。
/// <para>
/// 會以 <see cref="SqlCommand.Parameters"/> 呼叫
/// <see cref="AddWithValues(SqlParameterCollection, object[])"/> 以存入參數。
/// </para>
/// </summary>
/// <typeparam name="T">查詢結果的資料型別。</typeparam>
/// <param name="command"><see cref="SqlCommand"/> 物件。</param>
/// <param name="parameters">用於查詢的參數物件。</param>
/// <returns>查詢結果。</returns>
/// <exception cref="ArgumentNullException"></exception>
/// <exception cref="ArgumentException"></exception>
/// <exception cref="InvalidCastException"></exception>
/// <exception cref="SqlException"></exception>
/// <exception cref="System.IO.IOException"></exception>
/// <exception cref="InvalidOperationException"></exception>
/// <exception cref="ObjectDisposedException"></exception>
public static async Task<T> FetchFirstAsync<T>(
this SqlCommand command,
params object[] parameters)
{
return await command.FetchFirstAsync<T>(
CancellationToken.None,
parameters);
}
/// <summary>
/// 非同步版本的 <see cref="FetchFirst{T}(SqlCommand, object[])"/>。
/// 執行查詢,並傳回查詢所傳回的結果集中唯一一筆資料,如果沒有資料,則為預設值。
/// 如果結果集中有多個項目,則這個方法會擲回例外狀況。
/// 取消語彙基元可用於要求在命令逾時之前取消作業。
/// <para>
/// 會以 <see cref="SqlCommand.Parameters"/> 呼叫
/// <see cref="AddWithValues(SqlParameterCollection, object[])"/> 以存入參數。
/// </para>
/// </summary>
/// <typeparam name="T">查詢結果的資料型別。</typeparam>
/// <param name="command"><see cref="SqlCommand"/> 物件。</param>
/// <param name="cancellationToken">取消指令。</param>
/// <param name="parameters">用於查詢的參數物件。</param>
/// <returns>查詢結果。</returns>
/// <exception cref="ArgumentNullException"></exception>
/// <exception cref="ArgumentException"></exception>
/// <exception cref="InvalidCastException"></exception>
/// <exception cref="SqlException"></exception>
/// <exception cref="System.IO.IOException"></exception>
/// <exception cref="InvalidOperationException"></exception>
/// <exception cref="ObjectDisposedException"></exception>
public static async Task<T> FetchFirstAsync<T>(
this SqlCommand command,
CancellationToken cancellationToken,
params object[] parameters)
{
return await s_core.FetchFirstAsync<T>(
command,
cancellationToken,
parameters);
}
}
}
| 41.114286 | 80 | 0.589993 | [
"MIT"
] | JTOne123/Minerva | RyanJuan.Minerva.SqlClient/FetchFirst.cs | 5,009 | C# |
// Copyright 2018 Maintainers of NUKE.
// Distributed under the MIT License.
// https://github.com/nuke-build/nuke/blob/master/LICENSE
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace Nuke.Common.Execution
{
internal class StronglyConnectedComponent<T> : IEnumerable<Vertex<T>>
{
private readonly LinkedList<Vertex<T>> _list;
public StronglyConnectedComponent()
{
_list = new LinkedList<Vertex<T>>();
}
public void Add(Vertex<T> vertex)
{
_list.AddLast(vertex);
}
public int Count => _list.Count;
public bool IsCycle => _list.Count > 1;
public IEnumerator<Vertex<T>> GetEnumerator()
{
return _list.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return _list.GetEnumerator();
}
}
}
| 22.853659 | 73 | 0.614728 | [
"MIT"
] | Bloemert/nuke-build-common | source/Nuke.Common/Execution/StronglyConnectedComponent.cs | 937 | C# |
// ********************************************************************************************************
// Product Name: DotSpatial.Symbology.dll
// Description: Contains the business logic for symbology layers and symbol categories.
// ********************************************************************************************************
// The contents of this file are subject to the MIT License (MIT)
// you may not use this file except in compliance with the License. You may obtain a copy of the License at
// http://dotspatial.codeplex.com/license
//
// Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF
// ANY KIND, either expressed or implied. See the License for the specific language governing rights and
// limitations under the License.
//
// The Original Code is from MapWindow.dll version 6.0
//
// The Initial Developer of this Original Code is Ted Dunsford. Created 9/28/2009 10:45:02 AM
//
// Contributor(s): (Open source contributors should list themselves and their modifications here).
//
// ********************************************************************************************************
namespace DotSpatial.Symbology
{
/// <summary>
/// IntervalMethods
/// </summary>
public enum IntervalMethod
{
/// <summary>
/// A numeric value fixes a constant separation between breaks.
/// </summary>
DefinedInterval,
/// <summary>
/// The breaks are set to being evenly spaced.
/// </summary>
EqualInterval,
/// <summary>
/// Breaks are calculated according to the following restrictions:
/// 1) break sizes follow a geometric progression
/// 2) the number of breaks is specified
/// 3) the sum of squares of the counts per bin is minimized
/// </summary>
Geometrical,
/// <summary>
/// Breaks start equally placed, but can be positioned manually instead.
/// </summary>
Manual,
/// <summary>
/// Jenks natural breaks looks for "clumping" in the data and
/// attempts to group according to the clumps.
/// </summary>
NaturalBreaks,
/// <summary>
/// The breaks are positioned to ensure close to equal quantities
/// in each break.
/// </summary>
Quantile,
/// <summary>
/// Not sure how this works yet. Something to do with standard deviations.
/// </summary>
StandardDeviation,
}
} | 42.064516 | 108 | 0.543712 | [
"MIT"
] | sdrmaps/dotspatial | Source/DotSpatial.Symbology/IntervalMethod.cs | 2,608 | C# |
using System.Collections.Generic;
using System.Xml;
namespace ODataClientXmlFiltering
{
class Program
{
static void removeNodes(XmlDocument _xmlDoc, HashSet<string> _namesToKeep)
{
bool elementDeleted = false;
do
{
elementDeleted = false;
XmlNodeList nodes = _xmlDoc.SelectNodes("//*");
foreach (XmlNode node in nodes)
{
if (node.Name == "EntityType")
{
if (!_namesToKeep.Contains(node.Attributes.GetNamedItem("Name").Value))
{
node.ParentNode.RemoveChild(node);
elementDeleted = true;
}
}
else if (node.Name == "EnumType")
{
if (!_namesToKeep.Contains(node.Attributes.GetNamedItem("Name").Value))
{
node.ParentNode.RemoveChild(node);
elementDeleted = true;
}
}
else if (node.Name == "Action")
{
node.ParentNode.RemoveChild(node);
elementDeleted = true;
}
else if (node.Name == "EntityContainer")
{
if (node.HasChildNodes)
{
foreach (XmlNode childNode in node.ChildNodes)
{
if (childNode.Name == "EntitySet")
{
if (!_namesToKeep.Contains(childNode.Attributes.GetNamedItem("Name").Value))
{
childNode.ParentNode.RemoveChild(childNode);
elementDeleted = true;
}
}
}
}
}
}
} while (elementDeleted);
}
static void calcNamesToKeepChildNodes(XmlNode _node, HashSet<string> _namesToKeep)
{
if (_node.Attributes != null && _node.Attributes.GetNamedItem("Type") != null)
{
string typeString = _node.Attributes.GetNamedItem("Type").Value;
if (typeString.Contains("Collection("))
{
typeString = typeString.Substring(typeString.IndexOf("Collection(") + 11);
typeString = typeString.Substring(0, typeString.Length - 1);
}
if (typeString.Contains("Microsoft.Dynamics.DataEntities"))
{
typeString = typeString.Substring(typeString.IndexOf("Microsoft.Dynamics.DataEntities") + 32);
if (!_namesToKeep.Contains(typeString))
{
_namesToKeep.Add(typeString);
}
}
}
if (_node.HasChildNodes)
{
foreach (XmlNode childNode in _node.ChildNodes)
{
calcNamesToKeepChildNodes(childNode, _namesToKeep);
}
}
}
static void calcNamesToKeep(XmlDocument _xmlDoc, HashSet<string> _namesToKeep)
{
int namesBefore = _namesToKeep.Count;
XmlNodeList nodes = _xmlDoc.SelectNodes("//*");
foreach (XmlNode node in nodes)
{
if (node.Attributes != null && node.Attributes.GetNamedItem("Name") != null &&
_namesToKeep.Contains(node.Attributes.GetNamedItem("Name").Value))
{
if (node.HasChildNodes)
{
calcNamesToKeepChildNodes(node, _namesToKeep);
}
}
}
if (_namesToKeep.Count > namesBefore)
{
calcNamesToKeep(_xmlDoc, _namesToKeep);
}
}
static void removeNavigationProperty(XmlDocument _xmlDoc)
{
bool elementDeleted = false;
do
{
elementDeleted = false;
XmlNodeList nodes = _xmlDoc.SelectNodes("//*");
foreach (XmlNode node in nodes)
{
if (node.Name == "EntityType" && node.HasChildNodes)
{
foreach (XmlNode childNode in node.ChildNodes)
{
if (childNode.Name == "NavigationProperty")
{
childNode.ParentNode.RemoveChild(childNode);
elementDeleted = true;
}
}
}
}
} while (elementDeleted);
}
static void Main(string[] args)
{
HashSet<string> namesToKeep = new HashSet<string>();
namesToKeep.Add("Resources");
namesToKeep.Add("SalesOrderHeadersV2");
namesToKeep.Add("SalesOrderHeaderV2");
namesToKeep.Add("SalesOrderLines");
namesToKeep.Add("SalesOrderLine");
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(@"C:\Temp\ODataMetaXml\metaProd.xml");
removeNavigationProperty(xmlDoc);
calcNamesToKeep(xmlDoc, namesToKeep);
removeNodes(xmlDoc, namesToKeep);
xmlDoc.Save(@"C:\Temp\ODataMetaXml\reducedMetaProd.xml");
}
}
}
| 36.17284 | 114 | 0.438225 | [
"MIT"
] | PaulHeisterkamp/d365fo.blog | Tools/ODataClientXmlFiltering/ODataClientXmlFiltering/Program.cs | 5,862 | C# |
using CrossCuttingLayer;
using MassTransit;
using System;
using System.Threading.Tasks;
namespace Microservice.TodoApp.Notification
{
public class TodoConsumerNotification : IConsumer<Todo>
{
public async Task Consume(ConsumeContext<Todo> context)
{
await Console.Out.WriteLineAsync($"Notification sent: todo id {context.Message.Id}");
}
}
} | 26.066667 | 97 | 0.705882 | [
"MIT"
] | Amitpnk/Microservice-Communication-with-RabbitMQ-MassTransit | src/Microservice.TodoApp.Notification/TodoConsumerNotification.cs | 393 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using Xunit;
namespace System.Reflection.Emit.Tests
{
public class TypeBuilderCreateType
{
[Theory]
[InlineData(TypeAttributes.Abstract)]
[InlineData(TypeAttributes.AnsiClass)]
[InlineData(TypeAttributes.AutoClass)]
[InlineData(TypeAttributes.BeforeFieldInit)]
[InlineData(TypeAttributes.ClassSemanticsMask | TypeAttributes.Abstract)]
[InlineData(TypeAttributes.Public)]
[InlineData(TypeAttributes.Sealed)]
[InlineData(TypeAttributes.SequentialLayout)]
[InlineData(TypeAttributes.Serializable)]
[InlineData(TypeAttributes.SpecialName)]
[InlineData(TypeAttributes.StringFormatMask)]
[InlineData(TypeAttributes.UnicodeClass)]
public void CreateType(TypeAttributes attributes)
{
TypeBuilder type = Helpers.DynamicType(attributes);
Type createdType = type.CreateType();
Assert.Equal(type.Name, createdType.Name);
TypeInfo typeInfo = type.CreateTypeInfo();
Assert.Equal(typeInfo, createdType.GetTypeInfo());
// Verify MetadataToken
Assert.Equal(type.MetadataToken, typeInfo.MetadataToken);
TypeInfo typeFromToken = (TypeInfo)type.Module.ResolveType(typeInfo.MetadataToken);
Assert.Equal(createdType, typeFromToken);
}
[Theory]
[ActiveIssue("https://github.com/dotnet/runtime/issues/2389", TestRuntimes.Mono)]
[InlineData(TypeAttributes.ClassSemanticsMask)]
[InlineData(TypeAttributes.HasSecurity)]
[InlineData(TypeAttributes.LayoutMask)]
[InlineData(TypeAttributes.NestedAssembly)]
[InlineData(TypeAttributes.NestedFamANDAssem)]
[InlineData(TypeAttributes.NestedFamily)]
[InlineData(TypeAttributes.NestedFamORAssem)]
[InlineData(TypeAttributes.NestedPrivate)]
[InlineData(TypeAttributes.NestedPublic)]
[InlineData(TypeAttributes.ReservedMask)]
[InlineData(TypeAttributes.RTSpecialName)]
public void CreateType_BadAttributes(TypeAttributes attributes)
{
try
{
TypeBuilder type = Helpers.DynamicType(attributes);
Type createdType = type.CreateType();
}
catch (System.InvalidOperationException)
{
Assert.Equal(TypeAttributes.ClassSemanticsMask, attributes);
return;
}
catch (System.ArgumentException)
{
return; // All others should fail with this exception
}
Assert.True(false, "Type creation should have failed.");
}
[Fact]
public void CreateType_NestedType()
{
TypeBuilder type = Helpers.DynamicType(TypeAttributes.NotPublic);
type.DefineNestedType("NestedType");
Type createdType = type.CreateType();
Assert.Equal(type.Name, createdType.Name);
}
[Fact]
public void CreateType_GenericType()
{
TypeBuilder type = Helpers.DynamicType(TypeAttributes.NotPublic);
type.DefineGenericParameters("T");
Type createdType = type.CreateType();
Assert.Equal(type.Name, createdType.Name);
}
}
}
| 37.586957 | 95 | 0.643146 | [
"MIT"
] | 333fred/runtime | src/libraries/System.Reflection.Emit/tests/TypeBuilder/TypeBuilderCreateType.cs | 3,458 | C# |
/*
Copyright 2016 Esri
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Text;
using ESRI.ArcGIS.esriSystem;
namespace TestApp
{
class Program
{
private static LicenseInitializer m_AOLicenseInitializer = new LicenseInitializer();
[STAThread]
static void Main(string[] args)
{
//ESRI License Initializer generated code.
m_AOLicenseInitializer.InitializeApplication(new esriLicenseProductCode[] { esriLicenseProductCode.esriLicenseProductCodeEngine },
new esriLicenseExtensionCode[] { });
Console.WriteLine("Creating container object");
//create a new instance of the test object which will internally clone our clonable object
TestClass t = new TestClass();
t.Test();
Console.WriteLine("Done, hit any key to continue.");
Console.ReadKey();
//ESRI License Initializer generated code.
//Do not make any call to ArcObjects after ShutDownApplication()
m_AOLicenseInitializer.ShutdownApplication();
}
}
}
| 30.862745 | 136 | 0.729987 | [
"Apache-2.0"
] | alx1808/arcobjects-sdk-community-samples | Net/SDK_General/ClonableObject/CSharp/TestApp/Program.cs | 1,574 | C# |
using NUnit.Framework;
using RefactoringEssentials.CSharp.Diagnostics;
namespace RefactoringEssentials.Tests.CSharp.Diagnostics
{
[TestFixture]
public class ReplaceWithOfTypeLastOrDefaultTests : CSharpDiagnosticTestBase
{
[Test]
public void TestCaseBasic()
{
Analyze<ReplaceWithOfTypeLastOrDefaultAnalyzer>(@"using System.Linq;
class Test
{
public void Foo(object[] obj)
{
$obj.Select(q => q as Test).LastOrDefault(q => q != null)$;
}
}", @"using System.Linq;
class Test
{
public void Foo(object[] obj)
{
obj.OfType<Test>().LastOrDefault();
}
}");
}
[Test]
public void TestCaseBasicWithFollowUpExpresison()
{
Analyze<ReplaceWithOfTypeLastOrDefaultAnalyzer>(@"using System.Linq;
class Test
{
public void Foo(object[] obj)
{
$obj.Select(q => q as Test).LastOrDefault(q => q != null && Foo(q))$;
}
}", @"using System.Linq;
class Test
{
public void Foo(object[] obj)
{
obj.OfType<Test>().LastOrDefault(q => Foo(q));
}
}");
}
[Test]
public void TestDisable()
{
Analyze<ReplaceWithOfTypeLastOrDefaultAnalyzer>(@"using System.Linq;
class Test
{
public void Foo(object[] obj)
{
#pragma warning disable " + CSharpDiagnosticIDs.ReplaceWithOfTypeLastOrDefaultAnalyzerID + @"
obj.Select (q => q as Test).LastOrDefault (q => q != null);
}
}");
}
[Test]
public void TestJunk()
{
Analyze<ReplaceWithOfTypeLastOrDefaultAnalyzer>(@"using System.Linq;
class Test
{
public void Foo(object[] obj)
{
obj.Select (x => q as Test).LastOrDefault (q => q != null);
}
}");
Analyze<ReplaceWithOfTypeLastOrDefaultAnalyzer>(@"using System.Linq;
class Test
{
public void Foo(object[] obj)
{
obj.Select (q => q as Test).LastOrDefault (q => 1 != null);
}
}");
}
}
}
| 22.034091 | 93 | 0.61114 | [
"MIT"
] | Wagnerp/RefactoringEssentials | Tests/CSharp/Diagnostics/ReplaceWithOfTypeLastOrDefaultTests.cs | 1,939 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace teknikServisPro
{
public partial class SERVIS_FISLERI : ComponentFactory.Krypton.Toolkit.KryptonForm
{
public SERVIS_FISLERI()
{
InitializeComponent();
}
carkSQLHelper.carkMsSQLHelper helper = new carkSQLHelper.carkMsSQLHelper();
DefaultStyles styleHelper = new DefaultStyles();
private void SERVIS_FISLERI_Load(object sender, EventArgs e)
{
styleHelper.dataGridStyle(dataGridView1);
//dataGridView1.SelectionMode = DataGridViewSelectionMode.CellSelect;
Thread thread = new Thread(new ThreadStart(getDefault));
thread.Start();
this.KeyUp += new System.Windows.Forms.KeyEventHandler(KeyEvent);
}
private void KeyEvent(object sender, KeyEventArgs e) //Keyup Event
{
if (e.KeyCode == Keys.F5)
{
getDefault();
}
}
public string COLS = "SERVIS_ID,UNVANI,TELEFON,CEP_TELEFON,FIS_TARIHI,FIS_NUMARASI,DURUMU,CIHAZ_MARKASI,SERVIS_ACIKLAMASI,TUTAR,ODENEN,KALAN,KAYIT_TARIHI,DUZENLENME_TARIHI";
public void getDefault()
{
DateTime dtTime1 = Convert.ToDateTime(date1.Text);
DateTime dtTime2 = Convert.ToDateTime(date2.Text);
string dateFormat1 = dtTime1.Year + "-" + dtTime1.Month + "-" + dtTime1.Day;
string dateFormat2 = dtTime2.Year + "-" + dtTime2.Month + "-" + dtTime2.Day;
this.Invoke((MethodInvoker)delegate
{
this.Cursor = Cursors.WaitCursor;
dataGridView1.DataSource = helper.getDataTable("SELECT " + COLS + " FROM SERVIS_FISLERI INNER JOIN CARI_KARTLAR_V2 ON SERVIS_FISLERI.MUSTERI_ID=CARI_KARTLAR_V2.ID WHERE FIS_TARIHI BETWEEN CONVERT(datetime, '" + dateFormat1 + "') AND CONVERT(datetime, '" + dateFormat2 + "') ORDER BY SERVIS_ID DESC");
this.Cursor = Cursors.Default;
});
}
private void dataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
styleHelper.dataGridReName(dataGridView1);
styleHelper.dataGridFormatNumber(dataGridView1);
styleHelper.dataGridColWidth(dataGridView1, dataGridView1.Tag.ToString());
dataGridView1.ColumnWidthChanged += new DataGridViewColumnEventHandler(styleHelper.testFunc);
double drTutar = 0;
double drOdenen = 0;
double drKalan = 0;
int drRecord = 0;
foreach (DataGridViewRow dr in dataGridView1.Rows)
{
double tutar = double.Parse(dr.Cells["TUTAR"].Value.ToString());
double odenen = double.Parse(dr.Cells["ODENEN"].Value.ToString());
double kalan = double.Parse(dr.Cells["KALAN"].Value.ToString());
drTutar += tutar;
drOdenen += odenen;
drKalan += kalan;
drRecord++;
}
sumIskonto.Text ="TUTAR : " + drTutar.ToString("N2");
sumKdv.Text = "ÖDENEN : " + drOdenen.ToString("N2");
sumGenelToplam.Text = "KALAN : " + drKalan.ToString("N2");
sumRecord.Text = "KAYIT : " + drRecord.ToString();
}
public void searchProcess2()
{
DateTime dtTime1 = Convert.ToDateTime(date1.Text);
DateTime dtTime2 = Convert.ToDateTime(date2.Text);
string dateFormat1 = dtTime1.Year + "-" + dtTime1.Month + "-" + dtTime1.Day;
string dateFormat2 = dtTime2.Year + "-" + dtTime2.Month + "-" + dtTime2.Day;
string query = "1=1 ";
query += " AND (FIS_TARIHI BETWEEN CONVERT(datetime, '" + dateFormat1 + "') AND CONVERT(datetime, '" + dateFormat2 + "'))";
//string[] likeColumns = helper.getColumnsNames("CARI_KARTLAR_V2");
string[] likeColumns =
{
"FIS_NUMARASI",
"CIHAZ_MARKASI",
"CIHAZ_IMEI",
"TESLIM_ALAN",
"TESLIM_EDEN",
"SERVIS_ACIKLAMASI",
"DURUMU",
"UNVANI",
"TELEFON",
"CEP_TELEFON",
"VERGI_NUMARASI",
"FIS_TARIHI",
"KAYIT_TARIHI",
"DUZENLENME_TARIHI"
};
if (likeColumns.Length > 0)
{
for (int i = 0; i < likeColumns.Length; i++)
{
if (i == 0)
{
query += " AND (" + likeColumns[i] + " LIKE N'%" + toolStripTextBox1.Text + "%' ";
}
else
{
query += " OR " + likeColumns[i] + " LIKE N'%" + toolStripTextBox1.Text + "%' ";
}
}
}
query += " ) ";
dataGridView1.DataSource = helper.getDataTable("SELECT " + COLS + " FROM SERVIS_FISLERI INNER JOIN CARI_KARTLAR_V2 ON SERVIS_FISLERI.MUSTERI_ID=CARI_KARTLAR_V2.ID WHERE " + query);
}
private void toolStripTextBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (Char)Keys.Enter)
{
searchProcess2();
}
}
private void toolStripTextBox1_TextChanged(object sender, EventArgs e)
{
searchProcess2();
}
private void yENİSTOKKARTIToolStripMenuItem_Click(object sender, EventArgs e)
{
YENI_SERVIS_FISI frm = new YENI_SERVIS_FISI();
frm.ShowDialog();
getDefault();
}
private void dataGridView1_DoubleClick(object sender, EventArgs e)
{
YENI_SERVIS_FISI frm = new YENI_SERVIS_FISI();
frm.ITEM_ID =int.Parse(dataGridView1.SelectedRows[0].Cells[0].Value.ToString());
frm.ShowDialog();
// getDefault();
}
private void date1_ValueChanged(object sender, EventArgs e)
{
if (toolStripTextBox1.Text.Length == 0)
{
getDefault();
}
else
{
searchProcess2();
}
}
private void date2_ValueChanged(object sender, EventArgs e)
{
if (toolStripTextBox1.Text.Length == 0)
{
getDefault();
}
else
{
searchProcess2();
}
}
private void fİŞEGİTToolStripMenuItem_Click(object sender, EventArgs e)
{
YENI_SERVIS_FISI frm = new YENI_SERVIS_FISI();
frm.ITEM_ID = int.Parse(dataGridView1.SelectedRows[0].Cells[0].Value.ToString());
frm.ShowDialog();
}
private void iÇERİĞİSÜZToolStripMenuItem_Click(object sender, EventArgs e)
{
int rowindex = dataGridView1.CurrentCell.RowIndex;
int columnindex = dataGridView1.CurrentCell.ColumnIndex;
toolStripTextBox1.Text = dataGridView1.Rows[rowindex].Cells[columnindex].Value.ToString();
}
}
}
| 36.942308 | 317 | 0.538912 | [
"MIT"
] | barisguzellik/teknikServisPro | SERVIS_FISLERI.cs | 7,696 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace VueNote.WebApi.ViewModels
{
public class RemoveNoteForm
{
[Range(1, int.MaxValue)]
public int NoteId { get; set; }
}
}
| 20.8125 | 44 | 0.726727 | [
"MIT"
] | brightman9/VueNote | VueNote.WebApi/ViewModels/RemoveNoteForm.cs | 335 | C# |
namespace Simulator
{
partial class Graph
{
/// <summary>
/// Variable del diseñador requerida.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Limpiar los recursos que se estén utilizando.
/// </summary>
/// <param name="disposing">true si los recursos administrados se deben eliminar; false en caso contrario, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Código generado por el Diseñador de componentes
/// <summary>
/// Método necesario para admitir el Diseñador. No se puede modificar
/// el contenido del método con el editor de código.
/// </summary>
private void InitializeComponent()
{
this.SuspendLayout();
//
// Graph
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.DoubleBuffered = true;
this.Name = "Graph";
this.Load += new System.EventHandler(this.Graph_Load);
this.Paint += new System.Windows.Forms.PaintEventHandler(this.Graph_Paint);
this.ResumeLayout(false);
}
#endregion
}
}
| 31.729167 | 129 | 0.561392 | [
"MIT"
] | Agus-git/UziScript | firmware/Simulator/Simulator/Graph.Designer.cs | 1,533 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace ArdalisRating
{
//Removed for dependency iversion principle
//public class DefaultRatingContext : IRatingContext
//{
// public RatingEngine Engine { get; set ; }
// public Rater CreateRaterForPolicy(Policy policy, IRatingContext context)
// {
// return new RaterFactory().Create(policy, context);
// }
// public Policy GetPolicyFromJsonString(string policyJson)
// {
// return new JsonPolicySerializer().GetPolicyFromJsonString(policyJson);
// }
// public Policy GetPolicyFromXmlString(string policyXml)
// {
// throw new NotImplementedException();
// }
// public string LoadPolicyFromFile()
// {
// return new FilePolicySource().GetPolicyFromSource();
// }
// public string LoadPolicyFromURI(string uri)
// {
// throw new NotImplementedException();
// }
// public void Log(string message)
// {
// new ConsoleLogger().Log(message);
// }
//}
}
| 26 | 84 | 0.59528 | [
"MIT"
] | thodoriskonstantoulias/CSharp-SOLID_Principles | ArdalisRating/DefaultRatingContext.cs | 1,146 | C# |
using UnityEngine;
using UnityEngine.UI;
public class CaptionsManager : MonoBehaviour
{
public Text captions;
bool isCaptionsOn = true;
void Start()
{
}
public void SetCaptionsText(string message)
{
//UnityEngine.WSA.Application.InvokeOnAppThread(() =>
//{
// Display captions if they are enabled
captions.text = (isCaptionsOn) ? message : "";
//}, false);
}
}
| 18.24 | 61 | 0.585526 | [
"MIT"
] | TobiahZ/HoloBot | Assets/Scripts/CaptionsManager.cs | 466 | C# |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
// Template Source: Templates\CSharp\Requests\IEntityCollectionPage.cs.tt
namespace Microsoft.Graph
{
using System;
using Newtonsoft.Json;
/// <summary>
/// The interface IDefaultManagedAppProtectionAppsCollectionPage.
/// </summary>
[JsonConverter(typeof(InterfaceConverter<DefaultManagedAppProtectionAppsCollectionPage>))]
public interface IDefaultManagedAppProtectionAppsCollectionPage : ICollectionPage<ManagedMobileApp>
{
/// <summary>
/// Gets the next page <see cref="IDefaultManagedAppProtectionAppsCollectionRequest"/> instance.
/// </summary>
IDefaultManagedAppProtectionAppsCollectionRequest NextPageRequest { get; }
/// <summary>
/// Initializes the NextPageRequest property.
/// </summary>
void InitializeNextPageRequest(IBaseClient client, string nextPageLinkString);
}
}
| 40.40625 | 153 | 0.636504 | [
"MIT"
] | AzureMentor/msgraph-sdk-dotnet | src/Microsoft.Graph/Requests/Generated/IDefaultManagedAppProtectionAppsCollectionPage.cs | 1,293 | C# |
using System;
using System.Threading;
using System.Threading.Tasks;
using Binance.Client.Websocket.Subscriptions;
using Binance.Client.Websocket.Websockets;
using Xunit;
namespace Binance.Client.Websocket.Tests.Integration
{
public class BinanceWebsocketCommunicatorTests
{
[Fact]
public async Task OnStarting_ShouldGetInfoResponse()
{
var url = BinanceValues.ApiWebsocketUrl;
using (var communicator = new BinanceWebsocketCommunicator(url))
{
var receivedEvent = new ManualResetEvent(false);
communicator.MessageReceived.Subscribe(msg =>
{
receivedEvent.Set();
});
communicator.Url = new Uri(url + "stream?streams=btcusdt@trade");
await communicator.Start();
receivedEvent.WaitOne(TimeSpan.FromSeconds(30));
}
}
}
}
| 27.823529 | 81 | 0.613108 | [
"Apache-2.0"
] | ColossusFX/binance-client-websocket | test_integration/Binance.Client.Websocket.Tests.Integration/BinanceWebsocketCommunicatorTests.cs | 946 | C# |
using AspNetCore.VersionInfo.Models.Collectors;
using AspNetCore.VersionInfo.Services;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
namespace AspNetCore.VersionInfo.Middleware
{
internal class ApiEndpoint
{
private readonly IServiceScopeFactory _serviceScopeFactory;
public ApiEndpoint(RequestDelegate next, IServiceScopeFactory serviceScopeFactory)
{
this._serviceScopeFactory = serviceScopeFactory;
}
public async Task InvokeAsync(HttpContext context)
{
string responseContent = string.Empty;
using (var scope = _serviceScopeFactory.CreateScope())
{
var infoHandler = scope.ServiceProvider.GetService<IInfoCollector>();
var versionInfo = infoHandler.AggregateData() as FlatCollectorResult;
responseContent = JsonSerializer.Serialize(versionInfo);
}
context.Response.ContentType = Constants.DEFAULT_API_RESPONSE_CONTENT_TYPE;
await context.Response.WriteAsync(responseContent);
}
}
}
| 31.7 | 90 | 0.707413 | [
"Apache-2.0"
] | salem84/AspNetCore.VersionInfo | src/AspNetCore.VersionInfo/Middleware/ApiEndpoint.cs | 1,270 | C# |
namespace compare_exe
{
partial class FrmAbout
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing) {
if (disposing && (components != null)) {
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent() {
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FrmAbout));
this.txtVersion = new System.Windows.Forms.TextBox();
this.panel1 = new System.Windows.Forms.Panel();
this.label1 = new System.Windows.Forms.Label();
this.btOk = new System.Windows.Forms.Button();
this.linkLabel1 = new System.Windows.Forms.LinkLabel();
this.pictureBox2 = new System.Windows.Forms.PictureBox();
this.textBox3 = new System.Windows.Forms.TextBox();
this.textBox1 = new System.Windows.Forms.TextBox();
this.label7 = new System.Windows.Forms.Label();
this.label4 = new System.Windows.Forms.Label();
this.label6 = new System.Windows.Forms.Label();
this.label5 = new System.Windows.Forms.Label();
this.panel1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBox2)).BeginInit();
this.SuspendLayout();
//
// txtVersion
//
this.txtVersion.BackColor = System.Drawing.SystemColors.Control;
this.txtVersion.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.txtVersion.Location = new System.Drawing.Point(103, 55);
this.txtVersion.Name = "txtVersion";
this.txtVersion.ReadOnly = true;
this.txtVersion.Size = new System.Drawing.Size(183, 13);
this.txtVersion.TabIndex = 0;
this.txtVersion.TabStop = false;
//
// panel1
//
this.panel1.Controls.Add(this.label1);
this.panel1.Controls.Add(this.btOk);
this.panel1.Dock = System.Windows.Forms.DockStyle.Bottom;
this.panel1.Location = new System.Drawing.Point(0, 74);
this.panel1.Name = "panel1";
this.panel1.Size = new System.Drawing.Size(357, 38);
this.panel1.TabIndex = 75;
//
// label1
//
this.label1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.label1.BackColor = System.Drawing.Color.DarkGray;
this.label1.Location = new System.Drawing.Point(3, 0);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(351, 1);
this.label1.TabIndex = 66;
//
// btOk
//
this.btOk.Anchor = System.Windows.Forms.AnchorStyles.Right;
this.btOk.Location = new System.Drawing.Point(261, 8);
this.btOk.Name = "btOk";
this.btOk.Size = new System.Drawing.Size(90, 24);
this.btOk.TabIndex = 0;
this.btOk.Text = "Close";
this.btOk.UseVisualStyleBackColor = true;
this.btOk.Click += new System.EventHandler(this.btOk_Click);
//
// linkLabel1
//
this.linkLabel1.Location = new System.Drawing.Point(100, 38);
this.linkLabel1.Name = "linkLabel1";
this.linkLabel1.Size = new System.Drawing.Size(254, 13);
this.linkLabel1.TabIndex = 0;
this.linkLabel1.TabStop = true;
this.linkLabel1.Text = "https://code.google.com/p/excel-batch-compare/";
this.linkLabel1.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.linkLabel1_LinkClicked);
//
// pictureBox2
//
this.pictureBox2.Image = ((System.Drawing.Image)(resources.GetObject("pictureBox2.Image")));
this.pictureBox2.Location = new System.Drawing.Point(8, 5);
this.pictureBox2.Name = "pictureBox2";
this.pictureBox2.Size = new System.Drawing.Size(40, 41);
this.pictureBox2.TabIndex = 73;
this.pictureBox2.TabStop = false;
//
// textBox3
//
this.textBox3.BackColor = System.Drawing.SystemColors.Control;
this.textBox3.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.textBox3.Location = new System.Drawing.Point(101, 22);
this.textBox3.Margin = new System.Windows.Forms.Padding(5, 3, 3, 3);
this.textBox3.Name = "textBox3";
this.textBox3.ReadOnly = true;
this.textBox3.Size = new System.Drawing.Size(185, 13);
this.textBox3.TabIndex = 0;
this.textBox3.TabStop = false;
this.textBox3.Text = "Florent BREHERET";
//
// textBox1
//
this.textBox1.BackColor = System.Drawing.SystemColors.Control;
this.textBox1.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.textBox1.Location = new System.Drawing.Point(101, 6);
this.textBox1.Margin = new System.Windows.Forms.Padding(5, 3, 3, 3);
this.textBox1.Name = "textBox1";
this.textBox1.ReadOnly = true;
this.textBox1.Size = new System.Drawing.Size(185, 13);
this.textBox1.TabIndex = 0;
this.textBox1.TabStop = false;
this.textBox1.Text = "Excel Batch Compare";
//
// label7
//
this.label7.AutoSize = true;
this.label7.Location = new System.Drawing.Point(49, 22);
this.label7.Name = "label7";
this.label7.Size = new System.Drawing.Size(44, 13);
this.label7.TabIndex = 67;
this.label7.Text = "Author :";
//
// label4
//
this.label4.AutoSize = true;
this.label4.Location = new System.Drawing.Point(49, 38);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(52, 13);
this.label4.TabIndex = 69;
this.label4.Text = "Website :";
//
// label6
//
this.label6.AutoSize = true;
this.label6.Location = new System.Drawing.Point(49, 54);
this.label6.Name = "label6";
this.label6.Size = new System.Drawing.Size(48, 13);
this.label6.TabIndex = 71;
this.label6.Text = "Version :";
//
// label5
//
this.label5.AutoSize = true;
this.label5.Location = new System.Drawing.Point(49, 6);
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(50, 13);
this.label5.TabIndex = 70;
this.label5.Text = "Product :";
//
// FrmAbout
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(357, 112);
this.Controls.Add(this.txtVersion);
this.Controls.Add(this.panel1);
this.Controls.Add(this.linkLabel1);
this.Controls.Add(this.pictureBox2);
this.Controls.Add(this.textBox3);
this.Controls.Add(this.textBox1);
this.Controls.Add(this.label7);
this.Controls.Add(this.label4);
this.Controls.Add(this.label6);
this.Controls.Add(this.label5);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
this.Name = "FrmAbout";
this.ShowIcon = false;
this.ShowInTaskbar = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "About";
this.Shown += new System.EventHandler(this.FrmAbout_Shown);
this.panel1.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.pictureBox2)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.TextBox txtVersion;
private System.Windows.Forms.Panel panel1;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Button btOk;
private System.Windows.Forms.LinkLabel linkLabel1;
private System.Windows.Forms.PictureBox pictureBox2;
private System.Windows.Forms.TextBox textBox3;
private System.Windows.Forms.TextBox textBox1;
private System.Windows.Forms.Label label7;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.Label label6;
private System.Windows.Forms.Label label5;
}
} | 46.669811 | 152 | 0.566505 | [
"BSD-2-Clause"
] | ArtyomBayok/excel-batch-compare | comp-exe/FrmAbout.Designer.cs | 9,896 | C# |
using System;
using System.Collections.Generic;
namespace OpenDMS.Storage.Providers.CouchDB.EngineMethods
{
public class CreateNewVersion : Base
{
private CreateVersionArgs _args;
public CreateNewVersion(EngineRequest request, CreateVersionArgs args)
: base(request)
{
_args = args;
}
public override void Execute()
{
Transactions.Transaction t;
Transactions.Processes.CreateNewVersion process;
process = new Transactions.Processes.CreateNewVersion(_request.Database, _args,
_request.RequestingPartyType, _request.Session, _request.Database.Server.Timeout,
_request.Database.Server.Timeout, _request.Database.Server.BufferSize, _request.Database.Server.BufferSize);
t = new Transactions.Transaction(process);
AttachSubscriber(process, _request.OnActionChanged);
AttachSubscriber(process, _request.OnAuthorizationDenied);
AttachSubscriber(process, _request.OnComplete);
AttachSubscriber(process, _request.OnError);
AttachSubscriber(process, _request.OnProgress);
AttachSubscriber(process, _request.OnTimeout);
t.Execute();
}
}
}
| 35.864865 | 125 | 0.648078 | [
"Apache-2.0"
] | 274706834/opendms-dot-net | OpenDMS.Storage/Providers/CouchDB/EngineMethods/CreateNewVersion.cs | 1,329 | C# |
namespace Armut.Iyzipay.Model
{
public sealed class Status
{
private readonly string value;
public static readonly Status SUCCESS = new Status("success");
public static readonly Status FAILURE = new Status("failure");
private Status(string value)
{
this.value = value;
}
public override string ToString()
{
return value;
}
}
}
| 20.952381 | 70 | 0.568182 | [
"MIT"
] | Blind-Striker/iyzipay-dotnet-client | Iyzipay/Model/Status.cs | 442 | C# |
// Copyright 2005, 2006 - Morten Nielsen (www.iter.dk)
//
// This file is part of SharpMap.
// SharpMap is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// SharpMap is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
// You should have received a copy of the GNU Lesser General Public License
// along with SharpMap; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
namespace GeoAPI.CoordinateSystems
{
/// <summary>
/// The IProjection interface defines the standard information stored with projection
/// objects. A projection object implements a coordinate transformation from a geographic
/// coordinate system to a projected coordinate system, given the ellipsoid for the
/// geographic coordinate system. It is expected that each coordinate transformation of
/// interest, e.g., Transverse Mercator, Lambert, will be implemented as a COM class of
/// coType Projection, supporting the IProjection interface.
/// </summary>
public interface IProjection : IInfo
{
/// <summary>
/// Gets number of parameters of the projection.
/// </summary>
int NumParameters { get; }
/// <summary>
/// Gets the projection classification name (e.g. 'Transverse_Mercator').
/// </summary>
string ClassName { get; }
/// <summary>
/// Gets an indexed parameter of the projection.
/// </summary>
/// <param name="index">Index of parameter</param>
/// <returns>n'th parameter</returns>
ProjectionParameter GetParameter(int index);
/// <summary>
/// Gets an named parameter of the projection.
/// </summary>
/// <remarks>The parameter name is case insensitive</remarks>
/// <param name="name">Name of parameter</param>
/// <returns>parameter or null if not found</returns>
ProjectionParameter GetParameter(string name);
}
}
| 39.482143 | 90 | 0.725464 | [
"MIT"
] | JeyssonXD/Sistema-Alerta-OT | packages/GeoAPI.CoordinateSystems.1.7.5/src/CoordinateSystems/IProjection.cs | 2,211 | C# |
using SFA.DAS.SharedOuterApi.Interfaces;
namespace SFA.DAS.EmployerIncentives.InnerApi.Requests
{
public class GetHealthRequest : IGetApiRequest
{
public string GetUrl => "ping";
}
} | 22.555556 | 54 | 0.724138 | [
"MIT"
] | SkillsFundingAgency/das-apim-endpoints | src/SFA.DAS.EmployerIncentives/InnerApi/Requests/GetHealthRequest.cs | 203 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Places.Models")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Places.Models")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("6e7c5aaf-88e8-468e-b638-e799957cf03e")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.810811 | 84 | 0.744103 | [
"MIT"
] | Ico093/TelerikAcademy | WebServesesAndCloud/Homework/02.WebAPIArchitecture/WebAPIArchitecture/Places.Models/Properties/AssemblyInfo.cs | 1,402 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DataServer.Events;
using DataServer.Models;
namespace DataServer.Repository
{
public interface IFullNameRepository
{
Task<FullName> GetById(string id);
Task<bool> SaveEvent(IEvent eventData);
}
}
| 20.470588 | 47 | 0.744253 | [
"MIT"
] | Salgat/EventSourcing-Demo | DataServer/DataServer/Repository/IFullNameRepository.cs | 350 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
namespace Microsoft.Azure.PowerShell.Cmdlets.Websites.Models.Api20210201
{
using static Microsoft.Azure.PowerShell.Cmdlets.Websites.Runtime.Extensions;
/// <summary>Publishing Credentials Policies entity collection ARM resource.</summary>
public partial class PublishingCredentialsPoliciesCollection :
Microsoft.Azure.PowerShell.Cmdlets.Websites.Models.Api20210201.IPublishingCredentialsPoliciesCollection,
Microsoft.Azure.PowerShell.Cmdlets.Websites.Models.Api20210201.IPublishingCredentialsPoliciesCollectionInternal
{
/// <summary>Internal Acessors for NextLink</summary>
string Microsoft.Azure.PowerShell.Cmdlets.Websites.Models.Api20210201.IPublishingCredentialsPoliciesCollectionInternal.NextLink { get => this._nextLink; set { {_nextLink = value;} } }
/// <summary>Backing field for <see cref="NextLink" /> property.</summary>
private string _nextLink;
/// <summary>Link to next page of resources.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.Websites.Origin(Microsoft.Azure.PowerShell.Cmdlets.Websites.PropertyOrigin.Owned)]
public string NextLink { get => this._nextLink; }
/// <summary>Backing field for <see cref="Value" /> property.</summary>
private Microsoft.Azure.PowerShell.Cmdlets.Websites.Models.Api20210201.ICsmPublishingCredentialsPoliciesEntity[] _value;
/// <summary>Collection of resources.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.Websites.Origin(Microsoft.Azure.PowerShell.Cmdlets.Websites.PropertyOrigin.Owned)]
public Microsoft.Azure.PowerShell.Cmdlets.Websites.Models.Api20210201.ICsmPublishingCredentialsPoliciesEntity[] Value { get => this._value; set => this._value = value; }
/// <summary>Creates an new <see cref="PublishingCredentialsPoliciesCollection" /> instance.</summary>
public PublishingCredentialsPoliciesCollection()
{
}
}
/// Publishing Credentials Policies entity collection ARM resource.
public partial interface IPublishingCredentialsPoliciesCollection :
Microsoft.Azure.PowerShell.Cmdlets.Websites.Runtime.IJsonSerializable
{
/// <summary>Link to next page of resources.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.Websites.Runtime.Info(
Required = false,
ReadOnly = true,
Description = @"Link to next page of resources.",
SerializedName = @"nextLink",
PossibleTypes = new [] { typeof(string) })]
string NextLink { get; }
/// <summary>Collection of resources.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.Websites.Runtime.Info(
Required = true,
ReadOnly = false,
Description = @"Collection of resources.",
SerializedName = @"value",
PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.Websites.Models.Api20210201.ICsmPublishingCredentialsPoliciesEntity) })]
Microsoft.Azure.PowerShell.Cmdlets.Websites.Models.Api20210201.ICsmPublishingCredentialsPoliciesEntity[] Value { get; set; }
}
/// Publishing Credentials Policies entity collection ARM resource.
internal partial interface IPublishingCredentialsPoliciesCollectionInternal
{
/// <summary>Link to next page of resources.</summary>
string NextLink { get; set; }
/// <summary>Collection of resources.</summary>
Microsoft.Azure.PowerShell.Cmdlets.Websites.Models.Api20210201.ICsmPublishingCredentialsPoliciesEntity[] Value { get; set; }
}
} | 55.112676 | 192 | 0.717097 | [
"MIT"
] | Agazoth/azure-powershell | src/Websites/Websites.Autorest/generated/api/Models/Api20210201/PublishingCredentialsPoliciesCollection.cs | 3,843 | C# |
using System.Collections.Generic;
using System.Linq;
using FluentAssertions;
using Xunit;
using DeviceDetectorNET.Parser.Client;
using DeviceDetectorNET.Tests.Class.Client;
using DeviceDetectorNET.Yaml;
namespace DeviceDetectorNET.Tests.Parser.Client
{
[Trait("Category", "FeedReader")]
public class FeedReaderTest
{
private readonly List<ClientFixture> _fixtureData;
public FeedReaderTest()
{
var path = $"{Utils.CurrentDirectory()}\\{@"Parser\Client\fixtures\feed_reader.yml"}";
var parser = new YamlParser<List<ClientFixture>>();
_fixtureData = parser.ParseFile(path);
//replace null
_fixtureData = _fixtureData.Select(f =>
{
f.client.version = f.client.version ?? "";
return f;
}).ToList();
}
[Fact]
public void FeedReaderTestParse()
{
var feedReaderParser = new FeedReaderParser();
foreach (var fixture in _fixtureData)
{
feedReaderParser.SetUserAgent(fixture.user_agent);
var result = feedReaderParser.Parse();
result.Success.Should().BeTrue("Match should be with success");
result.Match.Name.ShouldBeEquivalentTo(fixture.client.name,"Names should be equal");
result.Match.Type.ShouldBeEquivalentTo(fixture.client.type, "Types should be equal");
result.Match.Version.ShouldBeEquivalentTo(fixture.client.version, "Versions should be equal");
}
}
}
}
| 33.375 | 110 | 0.616729 | [
"Apache-2.0"
] | OlegIvanov/DeviceDetector.NET | test/DeviceDetector.NET.Tests/Parser/Client/FeedReaderTest.cs | 1,604 | C# |
using UnityEngine;
using UnityEngine.UI;
public class MailPreview : MonoBehaviour
{
public Text nameText, contentText, dateText;
public MailManager.Mail mail { private set; get; }
public void SetWindowInfo(MailManager.Mail mail)
{
this.mail = mail;
nameText.text = mail.name;
contentText.text = mail.content;
dateText.text = mail.date;
if (!mail.isRead)
{
Button b = GetComponent<Button>();
ColorBlock colors = b.colors;
colors.normalColor = new Color(211f / 255f, 245f / 255f, 1f);
b.colors = colors;
}
}
}
| 24.5 | 73 | 0.596546 | [
"Apache-2.0"
] | Xwilarg/FPH | Assets/Scripts/Mails/MailPreview.cs | 639 | C# |
// --------------------------------------------------------------------------------------------------------------------
// <copyright company="Chocolatey" file="ConfigCommand.cs">
// Copyright 2017 - Present Chocolatey Software, LLC
// Copyright 2014 - 2017 Rob Reynolds, the maintainers of Chocolatey, and RealDimensions Software, LLC
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using chocolatey;
using chocolatey.infrastructure.commandline;
using ChocolateyGui.Common.Attributes;
using ChocolateyGui.Common.Models;
using ChocolateyGui.Common.Properties;
using ChocolateyGui.Common.Services;
using Serilog;
namespace ChocolateyGui.Common.Commands
{
[LocalizedCommandFor("config", nameof(Resources.ConfigCommand_Description))]
public class ConfigCommand : BaseCommand, ICommand
{
private static readonly ILogger Logger = Log.ForContext<ConfigCommand>();
private readonly IConfigService _configService;
public ConfigCommand(IConfigService configService)
{
_configService = configService;
}
public virtual void ConfigureArgumentParser(OptionSet optionSet, ChocolateyGuiConfiguration configuration)
{
optionSet
.Add(
"name=",
L(nameof(Resources.ConfigCommand_NameOption)),
option => configuration.ConfigCommand.Name = option.remove_surrounding_quotes())
.Add(
"value=",
L(nameof(Resources.ConfigCommand_ValueOption)),
option => configuration.ConfigCommand.ConfigValue = option.remove_surrounding_quotes())
.Add(
"g|global",
L(nameof(Resources.GlobalOption)),
option => configuration.Global = option != null);
}
public virtual void HandleAdditionalArgumentParsing(IList<string> unparsedArguments, ChocolateyGuiConfiguration configuration)
{
configuration.Input = string.Join(" ", unparsedArguments);
var command = ConfigCommandType.Unknown;
var unparsedCommand = unparsedArguments.DefaultIfEmpty(string.Empty).FirstOrDefault().to_string().Replace("-", string.Empty);
Enum.TryParse(unparsedCommand, true, out command);
if (command == ConfigCommandType.Unknown)
{
if (!string.IsNullOrWhiteSpace(unparsedCommand))
{
Logger.Warning(L(nameof(Resources.ConfigCommand_UnknownCommandError), unparsedCommand, "list"));
}
command = ConfigCommandType.List;
}
configuration.ConfigCommand.Command = command;
if ((configuration.ConfigCommand.Command == ConfigCommandType.List || !string.IsNullOrWhiteSpace(configuration.ConfigCommand.Name)) && unparsedArguments.Count > 1)
{
Logger.Error(L(nameof(Resources.ConfigCommand_SingleConfigError)));
Environment.Exit(-1);
}
if (string.IsNullOrWhiteSpace(configuration.ConfigCommand.Name) && unparsedArguments.Count >= 2)
{
configuration.ConfigCommand.Name = unparsedArguments[1];
}
if (string.IsNullOrWhiteSpace(configuration.ConfigCommand.ConfigValue) && unparsedArguments.Count >= 3)
{
configuration.ConfigCommand.ConfigValue = unparsedArguments[2];
}
}
public virtual void HandleValidation(ChocolateyGuiConfiguration configuration)
{
if (configuration.ConfigCommand.Command != ConfigCommandType.List &&
string.IsNullOrWhiteSpace(configuration.ConfigCommand.Name))
{
Logger.Error(L(nameof(Resources.ConfigCommand_MissingNameOptionError), configuration.ConfigCommand.Command.to_string(), "--name"));
Environment.Exit(-1);
}
if (configuration.ConfigCommand.Command == ConfigCommandType.Set &&
string.IsNullOrWhiteSpace(configuration.ConfigCommand.ConfigValue))
{
Logger.Error(L(nameof(Resources.ConfigCommand_MissingValueOptionError), configuration.ConfigCommand.Command.to_string(), "--value"));
Environment.Exit(-1);
}
}
public virtual void HelpMessage(ChocolateyGuiConfiguration configuration)
{
Logger.Warning(L(nameof(Resources.ConfigCommand_Title)));
Logger.Information(string.Empty);
Logger.Information(L(nameof(Resources.ConfigCommand_Help)));
Logger.Information(string.Empty);
Logger.Warning(L(nameof(Resources.Command_Usage)));
Logger.Information(@"
chocolateyguicli config [list]|get|set|unset [<options/switches>]
");
Logger.Warning(L(nameof(Resources.Command_Examples)));
Logger.Information(@"
chocolateyguicli config
chocolateyguicli config list
chocolateyguicli config get outdatedPackagesCacheDurationInMinutes
chocolateyguicli config get --name outdatedPackagesCacheDurationInMinutes
chocolateyguicli config set outdatedPackagesCacheDurationInMinutes 60
chocolateyguicli config set --name outdatedPackagesCacheDurationInMinutes --value 60
chocolateyguicli config unset outdatedPackagesCacheDurationInMinutes
chocolateyguicli config unset --name outdatedPackagesCacheDurationInMinutes
");
PrintExitCodeInformation();
}
public virtual void Run(ChocolateyGuiConfiguration config)
{
switch (config.ConfigCommand.Command)
{
case ConfigCommandType.List:
_configService.ListSettings(config);
break;
case ConfigCommandType.Get:
_configService.GetConfigValue(config);
break;
case ConfigCommandType.Set:
_configService.SetConfigValue(config);
break;
case ConfigCommandType.Unset:
_configService.UnsetConfigValue(config);
break;
}
}
}
} | 44.821918 | 176 | 0.604829 | [
"Apache-2.0"
] | BearerPipelineTest/ChocolateyGUI | Source/ChocolateyGui.Common/Commands/ConfigCommand.cs | 6,546 | C# |
using Robust.Shared.Analyzers;
using Robust.Shared.GameObjects;
namespace Content.Server.Mining.Components;
[RegisterComponent, ComponentProtoName("Mineable")]
[Friend(typeof(MineableSystem))]
public class MineableComponent : Component
{
public float BaseMineTime = 1.0f;
}
| 23.416667 | 51 | 0.797153 | [
"MIT"
] | Antares-30XX/Antares | Content.Server/Mining/Components/MineableComponent.cs | 283 | C# |
using EnvDTE;
using EnvDTE80;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using System;
using System.ComponentModel.Design;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using Tweakster.VisualStudio.Toolkit.Constant;
using Tweakster.VisualStudio.Toolkit.Execute;
using Tweakster.VisualStudio.Toolkit.Logging;
using Tweakster.VisualStudio.Toolkit.Services;
namespace Tweakster.Commands.General
{
internal sealed class Xml2ClassCommand
{
private static string _xmlSelectedPath;
public static async Task InitializeAsync(AsyncPackage package)
{
await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(package.DisposalToken);
var commandService = await package.GetServiceAsync<IMenuCommandService, OleMenuCommandService>();
var dte = await package.GetServiceAsync<DTE, DTE2>();
var uiShell = await package.GetServiceAsync<SVsUIShell, IVsUIShell>();
var cmdId = new CommandID(PackageGuids.guidCommands, PackageIds.Xml2Class);
var menuItem = new OleMenuCommand((s, e) => Execute(package, uiShell), cmdId);
menuItem.BeforeQueryStatus += (s, e) => _xmlSelectedPath = CanExecute(s, ".xml");
commandService.AddCommand(menuItem);
}
private static string CanExecute(object s, string ext)
{
var oleMenuCommand = s as OleMenuCommand;
oleMenuCommand.Visible = false;
var selected = VsDte.VsSolution.GetSelectedFiles();
if (selected?.Count() == 1)
{
var extension = Path.GetExtension(selected.ElementAt(0));
if (string.Equals(extension, ext, StringComparison.OrdinalIgnoreCase))
{
oleMenuCommand.Visible = true;
return selected.ElementAt(0);
}
}
return string.Empty;
}
private static void Execute(AsyncPackage package, IVsUIShell _)
{
Function.Run<Xml2ClassCommand>(() =>
{
if (!File.Exists(_xmlSelectedPath))
return;
var xmlContent = File.ReadAllText(_xmlSelectedPath);
Clipboard.SetText(xmlContent);
var directory = Path.GetDirectoryName(_xmlSelectedPath);
var classFilename = $"{Path.GetFileNameWithoutExtension(_xmlSelectedPath)}.cs";
var classFullPath = Path.Combine(directory, classFilename);
if (File.Exists(classFullPath))
{
var msg = $"File '{classFullPath}' already exists in this location. Do you want to replace it?";
OutputWindowHelper.WarningWriteLine(msg);
var messageBoxResult = MessageBox.Show(msg, "File Exists", MessageBoxButton.YesNo, MessageBoxImage.Question);
if (messageBoxResult == MessageBoxResult.No)
return;
File.Delete(classFullPath);
}
File.AppendAllText(classFullPath, string.Empty);
var projectItem = VsDte.Instance.Solution.FindProjectItem(_xmlSelectedPath);
var projectItemClass = projectItem.ProjectItems.AddFromFile(classFullPath);
VsShellUtilities.OpenDocument(package, classFullPath);
VsDte.Instance.ExecuteCommand(CommandKeys.Edit.PasteXMLAsClasses);
Clipboard.Clear();
var wfpTextView = PackageService.GetTextView();
if (wfpTextView != null)
{
var snapshot = wfpTextView.TextSnapshot;
var currentSnapshot = snapshot.TextBuffer.CurrentSnapshot;
if (snapshot != null && currentSnapshot != null)
{
var text = snapshot.GetText();
var textFixed = "namespace Xml2ClassRoot\r\n{" + text + "}";
using (var edit = wfpTextView.TextBuffer.CreateEdit())
{
edit.Delete(0, text.Length);
edit.Insert(0, textFixed);
edit.Apply();
}
VsDte.Instance.ExecuteCommand(CommandKeys.Edit.FormatDocument);
projectItemClass.Save();
}
}
});
}
}
}
| 38.652542 | 129 | 0.583425 | [
"Apache-2.0"
] | nbduong/Tweakster | src/Tweakster/Commands/General/Xml2ClassCommand.cs | 4,563 | C# |
using System.Collections.Generic;
namespace Ninja_Price.API.PoeNinja.Classes
{
public class UniqueJewels
{
public class Sparkline
{
public List<object> Data { get; set; }
public double TotalChange { get; set; }
}
public class Line
{
public int Id { get; set; }
public string Name { get; set; }
public string Icon { get; set; }
public int MapTier { get; set; }
public int LevelRequired { get; set; }
public string BaseType { get; set; }
public int StackSize { get; set; }
public string Variant { get; set; }
public object ProphecyText { get; set; }
public object ArtFilename { get; set; }
public int Links { get; set; }
public int ItemClass { get; set; }
public Sparkline Sparkline { get; set; }
public List<object> ImplicitModifiers { get; set; }
public List<object> ExplicitModifiers { get; set; }
public string FlavourText { get; set; }
public string ItemType { get; set; }
public double ChaosValue { get; set; }
public double ExaltedValue { get; set; }
public int Count { get; set; }
}
public class RootObject
{
public List<Line> Lines { get; set; }
}
}
} | 40.97619 | 63 | 0.439279 | [
"MIT"
] | DeadlyCrush/DeadlyTrade | POExileDirection/API/UniqueJewels.cs | 1,723 | C# |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the kinesisanalyticsv2-2018-05-23.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using System.Net;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.KinesisAnalyticsV2.Model
{
/// <summary>
/// Describes code configuration for a Java-based Kinesis Data Analytics application.
/// </summary>
public partial class ApplicationCodeConfiguration
{
private CodeContent _codeContent;
private CodeContentType _codeContentType;
/// <summary>
/// Gets and sets the property CodeContent.
/// <para>
/// The location and type of the application code.
/// </para>
/// </summary>
public CodeContent CodeContent
{
get { return this._codeContent; }
set { this._codeContent = value; }
}
// Check to see if CodeContent property is set
internal bool IsSetCodeContent()
{
return this._codeContent != null;
}
/// <summary>
/// Gets and sets the property CodeContentType.
/// <para>
/// Specifies whether the code content is in text or zip format.
/// </para>
/// </summary>
[AWSProperty(Required=true)]
public CodeContentType CodeContentType
{
get { return this._codeContentType; }
set { this._codeContentType = value; }
}
// Check to see if CodeContentType property is set
internal bool IsSetCodeContentType()
{
return this._codeContentType != null;
}
}
} | 30.25974 | 116 | 0.639056 | [
"Apache-2.0"
] | atpyatt/aws-sdk-net | sdk/src/Services/KinesisAnalyticsV2/Generated/Model/ApplicationCodeConfiguration.cs | 2,330 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
using NPolyglot.LanguageDesign;
namespace NPolyglot.Core
{
public class TransformWithCompiledTransforms : AppDomainIsolatedTask
{
[Required]
public ITaskItem[] TransformsDlls { get; set; }
[Required]
public ITaskItem[] ParsedFiles { get; set; }
[Required]
public string OutputDir { get; set; }
[Output]
public ITaskItem[] GeneratedOutput { get; set; }
public override bool Execute()
{
try
{
Log.LogMessage(MessageImportance.Low, "Starting task");
Log.LogMessage(MessageImportance.Low, "Assemblies to load: {0}", string.Join("; ", TransformsDlls.Select(x => Path.GetFullPath(x.ItemSpec))));
AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;
var assemblies =
from dll in TransformsDlls
let path = Path.GetFullPath(dll.ItemSpec)
select Assembly.LoadFile(path);
Log.LogMessage(MessageImportance.Low, "Loaded assemblies");
Log.LogMessage(MessageImportance.Low, "Transform candidates: {0}", string.Join(", ", assemblies.SelectMany(x => x.GetTypes())));
var transformTypes =
from a in assemblies
from t in a.GetTypes()
where t.IsTransform()
select t;
var transforms = transformTypes
.Select(x => x.GetDefaultConstructor().Invoke(new object[0]))
.Select(x => (ICodedTransform)new ReflectionBasedTransformWrapper(x))
.ToDictionary(x => x.ExportName, x => x);
Log.LogMessage(MessageImportance.Low, "Found tarnsforms: {0}", string.Join(", ", transforms.Select(x => x.Key)));
var output = new List<ITaskItem>();
foreach (var file in ParsedFiles.Where(IsFileValidForTransform))
{
var templateKey = file.GetTemplate();
ICodedTransform transform;
if (!transforms.TryGetValue(templateKey, out transform))
{
continue;
}
var obj = file.GetObject();
var result = transform.Transform(obj);
var outputFilename = Path.GetFileNameWithoutExtension(file.ItemSpec) + ".cs";
var outputPath = Path.Combine(OutputDir, outputFilename);
File.WriteAllText(outputPath, result);
output.Add(new TaskItem(outputPath));
}
GeneratedOutput = output.ToArray();
return true;
}
catch (Exception e)
{
Log.LogError("Failed to transform DSL files: {0}", e);
return false;
}
}
private bool IsFileValidForTransform(ITaskItem item) =>
item.MetadataNames.Cast<string>().Contains(MetadataNames.Object) &&
item.MetadataNames.Cast<string>().Contains(MetadataNames.Template);
private Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
{
var alreadyLoaded = AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault(x => x.FullName == args.Name);
if (alreadyLoaded != null)
{
return alreadyLoaded;
}
var name = args.Name.Split(',')[0];
var path = Path.GetDirectoryName(args.RequestingAssembly.Location);
var assemblies = Directory.GetFiles(path, $"{name}.dll");
var found = assemblies.FirstOrDefault();
if (found == null)
{
Log.LogMessage(MessageImportance.Low, "Failed to find assembly '{0}' for '{1}'", args.Name, args.RequestingAssembly.FullName);
return Assembly.Load(args.Name);
}
Log.LogMessage(MessageImportance.Low, "Found assembly '{0}' for '{1}'", found, args.RequestingAssembly.FullName);
return Assembly.LoadFile(found);
}
}
}
| 37.741379 | 158 | 0.563728 | [
"MIT"
] | Artemigos/NPolyglot | src/NPolyglot.Core/TransformWithCompiledTransforms.cs | 4,378 | C# |
// Copyright 2016-2021, Pulumi Corporation
using System;
using System.Collections.Generic;
using System.IO;
namespace Pulumi.Automation
{
/// <summary>
/// A Pulumi project manifest. It describes metadata applying to all sub-stacks created from the project.
/// </summary>
public class ProjectSettings
{
internal static IEqualityComparer<ProjectSettings> Comparer { get; } = new ProjectSettingsComparer();
public string Name { get; set; }
public ProjectRuntime Runtime { get; set; }
public string? Main { get; set; }
public string? Description { get; set; }
public string? Author { get; set; }
public string? Website { get; set; }
public string? License { get; set; }
public string? Config { get; set; }
public ProjectTemplate? Template { get; set; }
public ProjectBackend? Backend { get; set; }
public ProjectSettings(
string name,
ProjectRuntime runtime)
{
this.Name = name;
this.Runtime = runtime;
}
public ProjectSettings(
string name,
ProjectRuntimeName runtime)
: this(name, new ProjectRuntime(runtime))
{
}
internal static ProjectSettings Default(string name) =>
new ProjectSettings(name, new ProjectRuntime(ProjectRuntimeName.Dotnet)) { Main = Directory.GetCurrentDirectory() };
internal bool IsDefault
{
get
{
return Comparer.Equals(this, Default(this.Name));
}
}
private sealed class ProjectSettingsComparer : IEqualityComparer<ProjectSettings>
{
bool IEqualityComparer<ProjectSettings>.Equals(ProjectSettings? x, ProjectSettings? y)
{
if (x == null)
{
return y == null;
}
if (y == null)
{
return false;
}
if (ReferenceEquals(x, y))
{
return true;
}
return x.Name == y.Name &&
ProjectRuntime.Comparer.Equals(x.Runtime, y.Runtime) &&
x.Main == y.Main &&
x.Description == y.Description &&
x.Author == y.Author &&
x.Website == y.Website &&
x.License == y.License &&
x.Config == y.Config &&
ProjectTemplate.Comparer.Equals(x.Template, y.Template) &&
ProjectBackend.Comparer.Equals(x.Backend, y.Backend);
}
int IEqualityComparer<ProjectSettings>.GetHashCode(ProjectSettings obj)
{
// fields with custom Comparer skipped for efficiency
return HashCode.Combine(
obj.Name,
obj.Main,
obj.Description,
obj.Author,
obj.Website,
obj.License,
obj.Config,
obj.Backend
);
}
}
}
}
| 29.790909 | 128 | 0.496491 | [
"Apache-2.0"
] | 64bit/pulumi | sdk/dotnet/Pulumi.Automation/ProjectSettings.cs | 3,279 | C# |
// 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.Windows.Forms
{
/// <summary>
/// Specifies the <see cref='System.Windows.Forms.ComboBox'/> style.
/// </summary>
public enum ComboBoxStyle
{
/// <summary>
/// The text portion is editable. The list portion is always visible.
/// </summary>
Simple = 0,
/// <summary>
/// The text portion is editable. The user must click the arrow button to
/// display the list portion.
/// </summary>
DropDown = 1,
/// <summary>
/// The user cannot directly edit the text portion. The user must click
/// the arrow button to display the list portion.
/// </summary>
DropDownList = 2,
}
}
| 31.1 | 81 | 0.60343 | [
"MIT"
] | ArrowCase/winforms | src/System.Windows.Forms/src/System/Windows/Forms/ComboBoxStyle.cs | 935 | C# |
using UnityEngine;
using UnityEngine.Rendering.Universal;
namespace StencilShadowGenerator.Core.RenderFeature
{
public class ShadowVolumeRenderingFeature : ScriptableRendererFeature
{
[SerializeField] private ShadowVolumeRenderingSettings settings = new ShadowVolumeRenderingSettings();
private ShadowVolumeRenderPass _renderPass;
/// <inheritdoc/>
public override void Create()
{
_renderPass = new ShadowVolumeRenderPass(settings);
}
public override void AddRenderPasses(ScriptableRenderer renderer, ref RenderingData renderingData)
{
renderer.EnqueuePass(_renderPass);
}
}
} | 31.227273 | 110 | 0.710335 | [
"MIT"
] | rhedgeco/UnityShadowVolumeGenerator | Assets/StencilShadowGenerator/Core/RenderFeature/ShadowVolumeRenderingFeature.cs | 687 | C# |
using System.Diagnostics;
using System.Runtime.Serialization;
using Solitons.Data;
namespace Solitons.Common
{
/// <summary>
///
/// </summary>
public abstract class SerializationCallback :
ISerializationCallback
{
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
protected virtual void OnDeserialization(object sender) {}
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
protected virtual void OnSerialized(object? sender) { }
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
protected virtual void OnSerializing(object? sender) { }
[DebuggerStepThrough]
void IDeserializationCallback.OnDeserialization(object sender) => OnDeserialization(sender);
[DebuggerStepThrough]
void ISerializationCallback.OnSerialized(object? sender) => OnSerialized(sender);
[DebuggerStepThrough]
void ISerializationCallback.OnSerializing(object? sender) => OnSerializing(sender);
}
}
| 27.512195 | 100 | 0.606383 | [
"MIT"
] | AlexeyEvlampiev/Solitons.Core | src/Solitons.Core/Common/SerializationCallback.cs | 1,130 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.ApplicationModel;
using Windows.ApplicationModel.Activation;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
namespace Hanselman.UWP
{
/// <summary>
/// Provides application-specific behavior to supplement the default Application class.
/// </summary>
sealed partial class App : Application
{
/// <summary>
/// Initializes the singleton application object. This is the first line of authored code
/// executed, and as such is the logical equivalent of main() or WinMain().
/// </summary>
public App()
{
InitializeComponent();
Suspending += OnSuspending;
Shiny.UwpShinyHost.Init(new Startup());
}
/// <summary>
/// Invoked when the application is launched normally by the end user. Other entry points
/// will be used such as when the application is launched to open a specific file.
/// </summary>
/// <param name="e">Details about the launch request and process.</param>
protected override void OnLaunched(LaunchActivatedEventArgs e)
{
#if DEBUG
if (System.Diagnostics.Debugger.IsAttached)
{
DebugSettings.EnableFrameRateCounter = true;
}
#endif
var rootFrame = Window.Current.Content as Frame;
// Do not repeat app initialization when the Window already has content,
// just ensure that the window is active
if (rootFrame == null)
{
// Create a Frame to act as the navigation context and navigate to the first page
rootFrame = new Frame();
rootFrame.NavigationFailed += OnNavigationFailed;
Xamarin.Forms.Forms.Init(e);
if (e.PreviousExecutionState == ApplicationExecutionState.Terminated)
{
//TODO: Load state from previously suspended application
}
// Place the frame in the current Window
Window.Current.Content = rootFrame;
}
if (rootFrame.Content == null)
{
// When the navigation stack isn't restored navigate to the first page,
// configuring the new page by passing required information as a navigation
// parameter
rootFrame.Navigate(typeof(MainPage), e.Arguments);
}
// Ensure the current window is active
Window.Current.Activate();
}
/// <summary>
/// Invoked when Navigation to a certain page fails
/// </summary>
/// <param name="sender">The Frame which failed navigation</param>
/// <param name="e">Details about the navigation failure</param>
void OnNavigationFailed(object sender, NavigationFailedEventArgs e)
{
throw new Exception("Failed to load Page " + e.SourcePageType.FullName);
}
/// <summary>
/// Invoked when application execution is being suspended. Application state is saved
/// without knowing whether the application will be terminated or resumed with the contents
/// of memory still intact.
/// </summary>
/// <param name="sender">The source of the suspend request.</param>
/// <param name="e">Details about the suspend request.</param>
void OnSuspending(object sender, SuspendingEventArgs e)
{
var deferral = e.SuspendingOperation.GetDeferral();
//TODO: Save application state and stop any background activity
deferral.Complete();
}
}
}
| 37.357798 | 99 | 0.616159 | [
"MIT"
] | AzureAdvocateBit/Hanselman.Forms-1 | src/UWP/App.xaml.cs | 4,074 | C# |
using System;
using Aop.Api.Domain;
using System.Collections.Generic;
using Aop.Api.Response;
namespace Aop.Api.Request
{
/// <summary>
/// AOP API: alipay.user.antarchive.face.identify
/// </summary>
public class AlipayUserAntarchiveFaceIdentifyRequest : IAopRequest<AlipayUserAntarchiveFaceIdentifyResponse>
{
/// <summary>
/// 蚂蚁档案人像管理平台人像比对服务
/// </summary>
public string BizContent { get; set; }
#region IAopRequest Members
private bool needEncrypt=false;
private string apiVersion = "1.0";
private string terminalType;
private string terminalInfo;
private string prodCode;
private string notifyUrl;
private string returnUrl;
private AopObject bizModel;
private Dictionary<string, string> udfParams; //add user-defined text parameters
public void SetNeedEncrypt(bool needEncrypt){
this.needEncrypt=needEncrypt;
}
public bool GetNeedEncrypt(){
return this.needEncrypt;
}
public void SetNotifyUrl(string notifyUrl){
this.notifyUrl = notifyUrl;
}
public string GetNotifyUrl(){
return this.notifyUrl;
}
public void SetReturnUrl(string returnUrl){
this.returnUrl = returnUrl;
}
public string GetReturnUrl(){
return this.returnUrl;
}
public void SetTerminalType(String terminalType){
this.terminalType=terminalType;
}
public string GetTerminalType(){
return this.terminalType;
}
public void SetTerminalInfo(String terminalInfo){
this.terminalInfo=terminalInfo;
}
public string GetTerminalInfo(){
return this.terminalInfo;
}
public void SetProdCode(String prodCode){
this.prodCode=prodCode;
}
public string GetProdCode(){
return this.prodCode;
}
public string GetApiName()
{
return "alipay.user.antarchive.face.identify";
}
public void SetApiVersion(string apiVersion){
this.apiVersion=apiVersion;
}
public string GetApiVersion(){
return this.apiVersion;
}
public void PutOtherTextParam(string key, string value)
{
if(this.udfParams == null)
{
this.udfParams = new Dictionary<string, string>();
}
this.udfParams.Add(key, value);
}
public IDictionary<string, string> GetParameters()
{
AopDictionary parameters = new AopDictionary();
parameters.Add("biz_content", this.BizContent);
if(udfParams != null)
{
parameters.AddAll(this.udfParams);
}
return parameters;
}
public AopObject GetBizModel()
{
return this.bizModel;
}
public void SetBizModel(AopObject bizModel)
{
this.bizModel = bizModel;
}
#endregion
}
}
| 25.967742 | 113 | 0.567081 | [
"Apache-2.0"
] | 554393109/alipay-sdk-net-all | AlipaySDKNet.Standard/Request/AlipayUserAntarchiveFaceIdentifyRequest.cs | 3,252 | C# |
using System.Collections.Generic;
using Newtonsoft.Json;
namespace BlInfoApiWrapper.Dto
{
public class PostCustomerInvoiceResponseItem
{
[JsonProperty(PropertyName = "amountInLocalCurrency")]
public decimal AmountInLocalCurrency { get; set; }
[JsonProperty(PropertyName = "amountInOriginalCurrency")]
public decimal AmountInOriginalCurrency { get; set; }
[JsonProperty(PropertyName = "amountPaidInLocalCurrency")]
public decimal AmountPaidInLocalCurrency { get; set; }
[JsonProperty(PropertyName = "amountPaidInOriginalCurrency")]
public decimal AmountPaidInOriginalCurrency { get; set; }
[JsonProperty(PropertyName = "associatedCustomerPayments")]
public List<GetPaymentResponseItem> AssociatedCustomerPayments { get; set; }
[JsonProperty(PropertyName = "currency")]
public string Currency { get; set; }
[JsonProperty(PropertyName = "customerId")]
public string CustomerId { get; set; }
[JsonProperty(PropertyName = "customerName")]
public string CustomerName { get; set; }
[JsonProperty(PropertyName = "dateOfLatestPayment")]
public string DateOfLatestPayment { get; set; }
[JsonProperty(PropertyName = "deliveryBox")]
public string DeliveryBox { get; set; }
[JsonProperty(PropertyName = "deliveryStreet")]
public string DeliveryStreet { get; set; }
[JsonProperty(PropertyName = "deliveryCity")]
public string DeliveryCity { get; set; }
[JsonProperty(PropertyName = "deliveryZip")]
public string DeliveryZip { get; set; }
[JsonProperty(PropertyName = "documentIds")]
public List<string> DocumentIds { get; set; }
[JsonProperty(PropertyName = "dueDate")]
public string DueDate { get; set; }
[JsonProperty(PropertyName = "externalInvoiceId")]
public int? ExternalInvoiceId { get; set; }
[JsonProperty(PropertyName = "invoiceDate")]
public string InvoiceDate { get; set; }
[JsonProperty(PropertyName = "invoiceNumber")]
public int InvoiceNumber { get; set; }
[JsonProperty(PropertyName = "journalEntryDate")]
public string JournalEntryDate { get; set; }
[JsonProperty(PropertyName = "journalEntryId")]
public int JournalEntryId { get; set; }
[JsonProperty(PropertyName = "journalId")]
public string JournalId { get; set; }
[JsonProperty(PropertyName = "numberOfRemindersSent")]
public int NumberOfRemindersSent { get; set; }
[JsonProperty(PropertyName = "orderNumber")]
public int OrderNumber { get; set; }
[JsonProperty(PropertyName = "paid")]
public bool Paid { get; set; }
[JsonProperty(PropertyName = "paymentType")]
public int PaymentType { get; set; }
[JsonProperty(PropertyName = "preliminary")]
public bool Preliminary { get; set; }
[JsonProperty(PropertyName = "receivableAccount")]
public string ReceivableAccount { get; set; }
[JsonProperty(PropertyName = "registeredByUser")]
public string RegisteredByUser { get; set; }
[JsonProperty(PropertyName = "type")]
public string Type { get; set; }
[JsonProperty(PropertyName = "projectId")]
public string ProjectId { get; set; }
[JsonProperty(PropertyName = "subLedgerEntries")]
public List<GetLedgerEntryResponseItem> SubLedgerEntries { get; set; }
public PostCustomerInvoiceResponseItem()
{
AssociatedCustomerPayments = new List<GetPaymentResponseItem>();
Currency = string.Empty;
CustomerId = string.Empty;
CustomerName = string.Empty;
DateOfLatestPayment = string.Empty;
DeliveryBox = string.Empty;
DeliveryCity = string.Empty;
DeliveryStreet = string.Empty;
DeliveryZip = string.Empty;
DocumentIds = new List<string>();
DueDate = string.Empty;
InvoiceDate = string.Empty;
JournalEntryDate = string.Empty;
JournalId = string.Empty;
ReceivableAccount = string.Empty;
RegisteredByUser = string.Empty;
Type = string.Empty;
ProjectId = string.Empty;
SubLedgerEntries = new List<GetLedgerEntryResponseItem>();
}
}
} | 42.711538 | 84 | 0.642729 | [
"MIT"
] | JimmyAtSchotte/BlinfoApiWrapper | src/Dto/PostCustomerInvoiceResponseItem.cs | 4,444 | C# |
// ------------------------------------------------------------------------------
// 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.
// <auto-generated/>
// Template Source: Templates\CSharp\Requests\IMethodRequest.cs.tt
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Threading;
/// <summary>
/// The interface IWorkbookFunctionsImSumRequest.
/// </summary>
public partial interface IWorkbookFunctionsImSumRequest : IBaseRequest
{
/// <summary>
/// Gets the request body.
/// </summary>
WorkbookFunctionsImSumRequestBody RequestBody { get; }
/// <summary>
/// Issues the POST request.
/// </summary>
System.Threading.Tasks.Task<WorkbookFunctionResult> PostAsync();
/// <summary>
/// Issues the POST request.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The task to await for async call.</returns>
System.Threading.Tasks.Task<WorkbookFunctionResult> PostAsync(
CancellationToken cancellationToken);
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="value">The expand value.</param>
/// <returns>The request object to send.</returns>
IWorkbookFunctionsImSumRequest Expand(string value);
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="value">The select value.</param>
/// <returns>The request object to send.</returns>
IWorkbookFunctionsImSumRequest Select(string value);
}
}
| 33.15873 | 153 | 0.585448 | [
"MIT"
] | OfficeGlobal/msgraph-beta-sdk-dotnet | src/Microsoft.Graph/Requests/Generated/IWorkbookFunctionsImSumRequest.cs | 2,089 | C# |
using Aragas.Core.Data;
using Aragas.Core.Extensions;
using Aragas.Core.Interfaces;
using Aragas.Core.Packets;
using MineLib.Core.Data;
using MineLib.Core.Data.Anvil;
using MineLib.Core.Data.Structs;
using MineLib.Core.Extensions;
using System;
using Aragas.Core.IO;
namespace MineLib.PacketBuilder.Server.Play
{
public class ChatMessage2Packet : ProtobufPacket
{
public String Message;
public override VarInt ID { get { return 1; } }
public override ProtobufPacket ReadPacket(PacketDataReader reader)
{
Message = reader.Read(Message);
return this;
}
public override ProtobufPacket WritePacket(PacketStream stream)
{
stream.Write(Message);
return this;
}
}
} | 20.473684 | 74 | 0.679949 | [
"MIT"
] | MineLib/ProtocolModern | Packets/Server/Play/0x01_ChatMessage2Packet.cs | 778 | C# |
public static class Tool
{
public static int ReturnSomethingUseful() {
return 0;
}
public static int AnotherUsefulThing() {
return 0;
}
}
| 16 | 47 | 0.590909 | [
"MIT"
] | RJ45toCerebrum/PackageRepo | Runtime/Tool.cs | 178 | C# |
using Streamiz.Kafka.Net.Kafka;
using Streamiz.Kafka.Net.Mock.Kafka;
using Streamiz.Kafka.Net.Mock.Pipes;
using Streamiz.Kafka.Net.Processors;
using Streamiz.Kafka.Net.Processors.Internal;
using Streamiz.Kafka.Net.SerDes;
using Streamiz.Kafka.Net.State;
using Streamiz.Kafka.Net.State.Internal;
using Streamiz.Kafka.Net.Stream;
using Streamiz.Kafka.Net.Stream.Internal;
using System;
using System.Collections.Generic;
using System.Threading;
namespace Streamiz.Kafka.Net.Mock
{
/// <summary>
/// This class makes it easier to write tests to verify the behavior of topologies created with <see cref="Topology"/> or
/// <see cref="StreamBuilder" />.
/// <para>
/// <see cref="TopologyTestDriver"/> is <see cref="IDisposable"/>. Be warning to dispose or use <code>using</code> keyword in your unit tests.
/// </para>
/// You can test simple topologies that have a single processor, or very complex topologies that have multiple sources,
/// processors, sinks, or sub-topologies.
/// Best of all, the class works without a real Kafka broker, so the tests execute very quickly with very little overhead.
/// <p>
/// Using the <see cref="TopologyTestDriver"/> in tests is easy: simply instantiate the driver and provide a <see cref="Topology"/>
/// (cf. <see cref="StreamBuilder.Build()"/>) and <see cref="IStreamConfig"/>, <see cref="CreateInputTopic{K, V}(string, ISerDes{K}, ISerDes{V})"/>
/// and use a <see cref="TestInputTopic{K, V}"/> to supply an input records to the topology,
/// and then <see cref="CreateOuputTopic{K, V}(string, TimeSpan, ISerDes{K}, ISerDes{V})"/> and use a <see cref="TestOutputTopic{K, V}"/> to read and
/// verify any output records by the topology.
/// </p>
/// <p>
/// Although the driver doesn't use a real Kafka broker, it does simulate Kafka Cluster in memory <see cref="MockConsumer"/> and
/// <see cref="MockProducer"/> that read and write raw {@code byte[]} messages.
/// </p>
/// <example>
/// Driver setup
/// <code>
/// static void Main(string[] args)
/// {
/// var config = new StreamConfig<StringSerDes, StringSerDes>();
/// config.ApplicationId = "test-test-driver-app";
///
/// StreamBuilder builder = new StreamBuilder();
///
/// builder.Stream<string, string>("test").Filter((k, v) => v.Contains("test")).To("test-output");
///
/// Topology t = builder.Build();
///
/// using (var driver = new TopologyTestDriver(t, config))
/// {
/// var inputTopic = driver.CreateInputTopic<string, string>("test");
/// var outputTopic = driver.CreateOuputTopic<string, string>("test-output", TimeSpan.FromSeconds(5));
/// inputTopic.PipeInput("test", "test-1234");
/// var r = outputTopic.ReadKeyValue();
/// // YOU SOULD ASSERT HERE
/// }
/// }
/// </code>
/// </example>
/// </summary>
public class TopologyTestDriver : IDisposable
{
/// <summary>
/// Test driver behavior mode
/// </summary>
public enum Mode
{
/// <summary>
/// Each record in send synchronous.
/// This is the default mode use in <see cref="TopologyTestDriver"/>.
/// </summary>
SYNC_TASK,
/// <summary>
/// A Cluster Kafka is emulated in memory with topic, partitions, etc ...
/// Also, if you send 1:1, 2:2, 3:3 in a topic, you could have in destination topic this order : 1:1, 3:3, 2:2.
/// If your unit test use record order, please <see cref="Mode.SYNC_TASK"/>
/// </summary>
ASYNC_CLUSTER_IN_MEMORY
}
private readonly CancellationTokenSource tokenSource = new CancellationTokenSource();
private readonly InternalTopologyBuilder topologyBuilder;
private readonly IStreamConfig configuration;
private readonly IStreamConfig topicConfiguration;
private readonly IDictionary<string, IPipeInput> inputs = new Dictionary<string, IPipeInput>();
private readonly IDictionary<string, IPipeOutput> outputs = new Dictionary<string, IPipeOutput>();
private readonly IBehaviorTopologyTestDriver behavior = null;
/// <summary>
/// Create a new test diver instance.
/// </summary>
/// <param name="topology">Topology to be tested</param>
/// <param name="config">Configuration for topology. One property will be modified : <see cref="IStreamConfig.NumStreamThreads"/> will set to 1</param>
/// <param name="mode">Topology driver mode</param>
public TopologyTestDriver(Topology topology, IStreamConfig config, Mode mode = Mode.SYNC_TASK)
: this(topology.Builder, config, mode)
{ }
private TopologyTestDriver(InternalTopologyBuilder builder, IStreamConfig config, Mode mode)
: this(builder, config, mode, null)
{
}
internal TopologyTestDriver(InternalTopologyBuilder builder, IStreamConfig config, Mode mode, IKafkaSupplier supplier)
{
topologyBuilder = builder;
configuration = config;
// ONLY 1 thread for test driver (use only for ASYNC_CLUSTER_IN_MEMORY)
configuration.NumStreamThreads = 1;
configuration.Guarantee = ProcessingGuarantee.AT_LEAST_ONCE;
topicConfiguration = config.Clone();
topicConfiguration.ApplicationId = $"test-driver-{configuration.ApplicationId}";
var clientId = string.IsNullOrEmpty(configuration.ClientId) ? $"{configuration.ApplicationId.ToLower()}-{Guid.NewGuid()}" : configuration.ClientId;
// sanity check
topologyBuilder.BuildTopology();
topologyBuilder.RewriteTopology(configuration);
switch (mode)
{
case Mode.SYNC_TASK:
behavior = new TaskSynchronousTopologyDriver(
clientId,
topologyBuilder,
configuration,
topicConfiguration,
supplier,
tokenSource.Token);
break;
case Mode.ASYNC_CLUSTER_IN_MEMORY:
behavior = new ClusterInMemoryTopologyDriver(
clientId,
topologyBuilder,
configuration,
topicConfiguration,
supplier,
tokenSource.Token);
break;
}
behavior.StartDriver();
}
/// <summary>
/// Close the driver, its topology, and all processors.
/// </summary>
public void Dispose()
{
tokenSource.Cancel();
foreach (var k in inputs)
k.Value.Dispose();
foreach (var k in outputs)
k.Value.Dispose();
behavior.Dispose();
}
#region Create Input Topic
/// <summary>
/// Create <see cref="TestInputTopic{K, V}"/> to be used for piping records to topic.
/// The key and value serializer as specified in the <see cref="IStreamConfig"/> are used.
/// </summary>
/// <typeparam name="K">key type</typeparam>
/// <typeparam name="V">value type</typeparam>
/// <param name="topicName">the name of the topic</param>
/// <returns><see cref="TestInputTopic{K, V}"/> instance</returns>
public TestInputTopic<K, V> CreateInputTopic<K, V>(string topicName)
=> CreateInputTopic<K, V>(topicName, null, null);
/// <summary>
/// Create <see cref="TestInputTopic{K, V}"/> to be used for piping records to topic
/// </summary>
/// <typeparam name="K">key type</typeparam>
/// <typeparam name="V">value type</typeparam>
/// <param name="keySerdes">Key serializer</param>
/// <param name="valueSerdes">Value serializer</param>
/// <param name="topicName">the name of the topic</param>
/// <returns><see cref="TestInputTopic{K, V}"/> instance</returns>
public TestInputTopic<K, V> CreateInputTopic<K, V>(string topicName, ISerDes<K> keySerdes, ISerDes<V> valueSerdes)
{
var input = behavior.CreateInputTopic(topicName, keySerdes, valueSerdes);
inputs.Add(topicName, input.Pipe);
return input;
}
/// <summary>
/// Create <see cref="TestInputTopic{K, V}"/> to be used for piping records to topic
/// </summary>
/// <typeparam name="K">key type</typeparam>
/// <typeparam name="V">value type</typeparam>
/// <typeparam name="KS">Key serializer type</typeparam>
/// <typeparam name="VS">Value serializer type</typeparam>
/// <param name="topicName">the name of the topic</param>
/// <returns><see cref="TestInputTopic{K, V}"/> instance</returns>
public TestInputTopic<K, V> CreateInputTopic<K, V, KS, VS>(string topicName)
where KS : ISerDes<K>, new()
where VS : ISerDes<V>, new()
=> CreateInputTopic(topicName, new KS(), new VS());
#endregion
#region Create Output Topic
/// <summary>
/// Create <see cref="TestOutputTopic{K, V}"/> to be used for reading records from topic.
/// The key and value serializer as specified in the <see cref="IStreamConfig"/> are used.
/// By default, the consume timeout is set to 1 seconds.
/// </summary>
/// <typeparam name="K">Key type</typeparam>
/// <typeparam name="V">Value type</typeparam>
/// <param name="topicName">the name of the topic</param>
/// <returns><see cref="TestOutputTopic{K, V}"/> instance</returns>
public TestOutputTopic<K, V> CreateOuputTopic<K, V>(string topicName)
=> CreateOuputTopic<K, V>(topicName, TimeSpan.FromSeconds(1), null, null);
/// <summary>
/// Create <see cref="TestOutputTopic{K, V}"/> to be used for reading records from topic.
/// </summary>
/// <typeparam name="K">Key type</typeparam>
/// <typeparam name="V">Value type</typeparam>
/// <param name="topicName">the name of the topic</param>
/// <param name="consumeTimeout">Consumer timeout</param>
/// <param name="keySerdes">Key deserializer</param>
/// <param name="valueSerdes">Value deserializer</param>
/// <returns><see cref="TestOutputTopic{K, V}"/> instance</returns>
public TestOutputTopic<K, V> CreateOuputTopic<K, V>(string topicName, TimeSpan consumeTimeout, ISerDes<K> keySerdes = null, ISerDes<V> valueSerdes = null)
{
var output = behavior.CreateOutputTopic(topicName, consumeTimeout, keySerdes, valueSerdes);
outputs.Add(topicName, output.Pipe);
return output;
}
/// <summary>
/// Create <see cref="TestOutputTopic{K, V}"/> to be used for reading records from topic.
/// By default, the consume timeout is set to 5 seconds.
/// </summary>
/// <typeparam name="K">Key type</typeparam>
/// <typeparam name="V">Value type</typeparam>
/// <typeparam name="KS">Key serializer type</typeparam>
/// <typeparam name="VS">Value serializer type</typeparam>
/// <param name="topicName">the name of the topic</param>
/// <returns><see cref="TestOutputTopic{K, V}"/> instance</returns>
public TestOutputTopic<K, V> CreateOuputTopic<K, V, KS, VS>(string topicName)
where KS : ISerDes<K>, new()
where VS : ISerDes<V>, new()
=> CreateOuputTopic<K, V, KS, VS>(topicName, TimeSpan.FromSeconds(5));
/// <summary>
/// Create <see cref="TestOutputTopic{K, V}"/> to be used for reading records from topic.
/// </summary>
/// <typeparam name="K">Key type</typeparam>
/// <typeparam name="V">Value type</typeparam>
/// <typeparam name="KS">Key serializer type</typeparam>
/// <typeparam name="VS">Value serializer type</typeparam>
/// <param name="topicName">the name of the topic</param>
/// <param name="consumeTimeout">Consumer timeout</param>
/// <returns><see cref="TestOutputTopic{K, V}"/> instance</returns>
public TestOutputTopic<K, V> CreateOuputTopic<K, V, KS, VS>(string topicName, TimeSpan consumeTimeout)
where KS : ISerDes<K>, new()
where VS : ISerDes<V>, new()
=> CreateOuputTopic<K, V>(topicName, consumeTimeout, new KS(), new VS());
#endregion
#region Create Multi Input Topic
/// <summary>
/// Create <see cref="TestMultiInputTopic{K, V}"/> to be used for piping records to multiple topics in same time.
/// Need to call <see cref="TestMultiInputTopic{K, V}.Flush"/> at the end of writting !
/// The key and value serializer as specified in the <see cref="IStreamConfig"/> are used.
/// </summary>
/// <typeparam name="K">key type</typeparam>
/// <typeparam name="V">value type</typeparam>
/// <param name="topics">the list of topics</param>
/// <returns><see cref="TestMultiInputTopic{K, V}"/> instance</returns>
public TestMultiInputTopic<K, V> CreateMultiInputTopic<K, V>(params string[] topics)
=> CreateMultiInputTopic<K, V>(null, null, topics);
/// <summary>
/// Create <see cref="TestMultiInputTopic{K, V}"/> to be used for piping records to multiple topics in same time.
/// Need to call <see cref="TestMultiInputTopic{K, V}.Flush"/> at the end of writting !
/// </summary>
/// <typeparam name="K">key type</typeparam>
/// <typeparam name="V">value type</typeparam>
/// <param name="keySerdes">key serializer instance</param>
/// <param name="valueSerdes">value serializer instance</param>
/// <param name="topics">the list of topics</param>
/// <returns><see cref="TestMultiInputTopic{K, V}"/> instance</returns>
public TestMultiInputTopic<K, V> CreateMultiInputTopic<K, V>(ISerDes<K> keySerdes, ISerDes<V> valueSerdes, params string[] topics)
{
var multi = behavior.CreateMultiInputTopic(topics, keySerdes, valueSerdes);
foreach (var topic in topics)
inputs.Add(topic, multi.GetPipe(topic));
return multi;
}
/// <summary>
/// Create <see cref="TestMultiInputTopic{K, V}"/> to be used for piping records to multiple topics in same time.
/// Need to call <see cref="TestMultiInputTopic{K, V}.Flush"/> at the end of writting !
/// The key and value serializer as specified in the type parameters.
/// </summary>
/// <typeparam name="K">key type</typeparam>
/// <typeparam name="V">value type</typeparam>
/// <typeparam name="KS">key serializer type</typeparam>
/// <typeparam name="VS">value serializer type</typeparam>
/// <param name="topics">the list of topics</param>
/// <returns><see cref="TestMultiInputTopic{K, V}"/> instance</returns>
public TestMultiInputTopic<K, V> CreateMultiInputTopic<K, V, KS, VS>(params string[] topics)
where KS : ISerDes<K>, new()
where VS : ISerDes<V>, new()
=> CreateMultiInputTopic(new KS(), new VS(), topics);
#endregion
#region Store
/// <summary>
/// Get the <see cref="IReadOnlyKeyValueStore{K, V}"/> or <see cref="ITimestampedKeyValueStore{K, V}"/> with the given name.
/// The store can be a "regular" or global store.
/// <p>
/// If the registered store is a <see cref="ITimestampedKeyValueStore{K, V}"/> this method will return a value-only query
/// interface.
/// </p>
/// </summary>
/// <typeparam name="K">key type</typeparam>
/// <typeparam name="V">value type</typeparam>
/// <param name="name">the name of the store</param>
/// <returns>the key value store, or null if no <see cref="IReadOnlyKeyValueStore{K, V}"/> or <see cref="ITimestampedKeyValueStore{K, V}"/> has been registered with the given name</returns>
public IReadOnlyKeyValueStore<K, V> GetKeyValueStore<K, V>(string name)
{
var store = behavior.GetStateStore<K, V>(name);
if (store is ITimestampedKeyValueStore<K, V>)
return new ReadOnlyKeyValueStoreFacade<K, V>(store as ITimestampedKeyValueStore<K, V>);
else if (store is IReadOnlyKeyValueStore<K, V>)
return (IReadOnlyKeyValueStore<K, V>)store;
else
return null;
}
/// <summary>
/// Get the <see cref="IReadOnlyWindowStore{K, V}"/> or <see cref="ITimestampedWindowStore{K, V}"/> with the given name.
/// The store can be a "regular" or global store.
/// <p>
/// If the registered store is a <see cref="ITimestampedWindowStore{K, V}"/> this method will return a value-only query
/// interface.
/// </p>
/// </summary>
/// <typeparam name="K">key type</typeparam>
/// <typeparam name="V">value type</typeparam>
/// <param name="name">the name of the store</param>
/// <returns>the key value store, or null if no <see cref="IReadOnlyWindowStore{K, V}"/> or <see cref="ITimestampedWindowStore{K, V}"/> has been registered with the given name</returns>
public IReadOnlyWindowStore<K, V> GetWindowStore<K, V>(string name)
{
var store = behavior.GetStateStore<K, V>(name);
if (store is ITimestampedWindowStore<K, V>)
return new ReadOnlyWindowStoreFacade<K, V>(store as ITimestampedWindowStore<K, V>);
else if (store is IReadOnlyWindowStore<K, V>)
return (IReadOnlyWindowStore<K, V>)store;
else
return null;
}
#endregion
#region Property
/// <summary>
/// Indicate if <see cref="TopologyTestDriver"/> is running or not.
/// </summary>
public bool IsRunning => behavior.IsRunning;
/// <summary>
/// Indicate if <see cref="TopologyTestDriver"/> is stopped or not.
/// </summary>
public bool IsStopped => behavior.IsStopped;
/// <summary>
/// Indicate if <see cref="TopologyTestDriver"/> is in error or not.
/// </summary>
public bool IsError => behavior.IsError;
#endregion
}
} | 47.650633 | 197 | 0.598874 | [
"MIT"
] | Mladenovic/kafka-streams-dotnet | core/Mock/TopologyTestDriver.cs | 18,824 | C# |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Game.Beatmaps;
using osu.Game.Rulesets.Judgements;
using osu.Game.Rulesets.Mania.Objects;
using osu.Game.Rulesets.Scoring;
using osu.Game.Rulesets.UI;
namespace osu.Game.Rulesets.Mania.Scoring
{
internal class ManiaScoreProcessor : ScoreProcessor<ManiaHitObject>
{
/// <summary>
/// The hit HP multiplier at OD = 0.
/// </summary>
private const double hp_multiplier_min = 0.75;
/// <summary>
/// The hit HP multiplier at OD = 0.
/// </summary>
private const double hp_multiplier_mid = 0.85;
/// <summary>
/// The hit HP multiplier at OD = 0.
/// </summary>
private const double hp_multiplier_max = 1;
/// <summary>
/// The MISS HP multiplier at OD = 0.
/// </summary>
private const double hp_multiplier_miss_min = 0.5;
/// <summary>
/// The MISS HP multiplier at OD = 5.
/// </summary>
private const double hp_multiplier_miss_mid = 0.75;
/// <summary>
/// The MISS HP multiplier at OD = 10.
/// </summary>
private const double hp_multiplier_miss_max = 1;
/// <summary>
/// The MISS HP multiplier. This is multiplied to the miss hp increase.
/// </summary>
private double hpMissMultiplier = 1;
/// <summary>
/// The HIT HP multiplier. This is multiplied to hit hp increases.
/// </summary>
private double hpMultiplier = 1;
public ManiaScoreProcessor(DrawableRuleset<ManiaHitObject> drawableRuleset)
: base(drawableRuleset)
{
}
protected override void ApplyBeatmap(Beatmap<ManiaHitObject> beatmap)
{
base.ApplyBeatmap(beatmap);
BeatmapDifficulty difficulty = beatmap.BeatmapInfo.BaseDifficulty;
hpMultiplier = BeatmapDifficulty.DifficultyRange(difficulty.DrainRate, hp_multiplier_min, hp_multiplier_mid, hp_multiplier_max);
hpMissMultiplier = BeatmapDifficulty.DifficultyRange(difficulty.DrainRate, hp_multiplier_miss_min, hp_multiplier_miss_mid, hp_multiplier_miss_max);
}
protected override void SimulateAutoplay(Beatmap<ManiaHitObject> beatmap)
{
while (true)
{
base.SimulateAutoplay(beatmap);
if (!HasFailed)
break;
hpMultiplier *= 1.01;
hpMissMultiplier *= 0.98;
Reset(false);
}
}
protected override double HealthAdjustmentFactorFor(JudgementResult result)
=> result.Type == HitResult.Miss ? hpMissMultiplier : hpMultiplier;
public override HitWindows CreateHitWindows() => new ManiaHitWindows();
}
}
| 33.722222 | 160 | 0.595387 | [
"MIT"
] | AyakuraYuki/osu | osu.Game.Rulesets.Mania/Scoring/ManiaScoreProcessor.cs | 2,948 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace CarSalesman
{
public class Engine
{
private string model;
private int power;
private int? displacement;
private string efficiency;
public Engine(string model, int power)
{
this.Model = model;
this.Power = power;
}
public Engine(string model, int power, int? displacement)
: this(model, power)
{
this.Displacement = displacement;
}
public Engine(string model, int power, string efficiency)
: this(model, power)
{
this.Efficiency = efficiency;
}
public Engine(string model, int power, int? displacement, string efficiency)
: this(model, power)
{
this.Displacement = displacement;
this.Efficiency = efficiency;
}
public string Efficiency
{
get { return efficiency; }
private set { efficiency = value; }
}
public int? Displacement
{
get { return displacement; }
private set { displacement = value; }
}
public int Power
{
get { return power; }
private set { power = value; }
}
public string Model
{
get { return model; }
private set { model = value; }
}
public override string ToString()
{
StringBuilder builder = new StringBuilder();
builder.AppendLine($" {Model}:");
builder.AppendLine($" Power: {Power}");
builder.AppendLine($" Displacement: {(Displacement == null ? "n/a" : Displacement.ToString())}");
builder.AppendLine($" Efficiency: {(Efficiency == null ? "n/a" : Efficiency.ToString())}");
return builder.ToString();
}
}
}
| 25.828947 | 112 | 0.522669 | [
"MIT"
] | nelov87/C-OOP-Basics | Defining Classes/Defining Classes/10. Car Salesman/Engine.cs | 1,965 | C# |
using DNA.CastleMinerZ.Inventory;
using DNA.IO;
using DNA.Net;
using DNA.Net.GamerServices;
using Microsoft.Xna.Framework;
using System.IO;
namespace DNA.CastleMinerZ.Net
{
public class DetonateRocketMessage : CastleMinerZMessage
{
public Vector3 Location;
public ExplosiveTypes ExplosiveType;
public InventoryItemIDs ItemType;
public bool HitDragon;
public override MessageTypes MessageType
{
get
{
return MessageTypes.System;
}
}
protected override SendDataOptions SendDataOptions
{
get
{
return SendDataOptions.Reliable;
}
}
private DetonateRocketMessage()
{
}
public static void Send(LocalNetworkGamer from, Vector3 location, ExplosiveTypes explosiveType, InventoryItemIDs itemType, bool hitDragon)
{
DetonateRocketMessage sendInstance = Message.GetSendInstance<DetonateRocketMessage>();
sendInstance.Location = location;
sendInstance.HitDragon = hitDragon;
sendInstance.ExplosiveType = explosiveType;
sendInstance.ItemType = itemType;
sendInstance.DoSend(from);
}
protected override void SendData(BinaryWriter writer)
{
writer.Write(Location);
writer.Write(HitDragon);
writer.Write((byte)ExplosiveType);
writer.Write((byte)ItemType);
}
protected override void RecieveData(BinaryReader reader)
{
Location = reader.ReadVector3();
HitDragon = reader.ReadBoolean();
ExplosiveType = (ExplosiveTypes)reader.ReadByte();
ItemType = (InventoryItemIDs)reader.ReadByte();
}
}
}
| 22.343284 | 140 | 0.750835 | [
"MIT"
] | JettSettie/CastleMinerZsrc | DNA.CastleMinerZ.Net/DetonateRocketMessage.cs | 1,497 | C# |
using System;
using System.Xml.Serialization;
namespace Aop.Api.Response
{
/// <summary>
/// ZhimaCreditContractBorrowDelayResponse.
/// </summary>
public class ZhimaCreditContractBorrowDelayResponse : AopResponse
{
}
}
| 18.846154 | 69 | 0.706122 | [
"Apache-2.0"
] | Varorbc/alipay-sdk-net-all | AlipaySDKNet/Response/ZhimaCreditContractBorrowDelayResponse.cs | 245 | C# |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Linq;
using Ionic.Zip;
using Kudu.Contracts.Settings;
using Kudu.Contracts.SiteExtensions;
using Kudu.Contracts.Tracing;
using Kudu.Core.Infrastructure;
using Kudu.Core.Tracing;
using Newtonsoft.Json.Linq;
using NuGet.Client;
namespace Kudu.Core.SiteExtensions
{
public static class FeedExtensionsV2
{
/// <summary>
/// HttpClient timeout
/// </summary>
public static TimeSpan HttpClientTimeout { get; set; } = DeploymentSettingsExtension.DefaultHttpClientTimeout;
/// <summary>
/// Return the feed URL to directly query nuget v2 api by search term,
/// always include pre-released
/// </summary>
internal static string GetFeedUrl(string filter)
{
String searchTerm = "tags:AzureSiteExtension";
if (String.IsNullOrWhiteSpace(filter))
{
// No user provided search string: just search by tag
searchTerm = "tags:AzureSiteExtension";
}
else if (filter.Contains(":"))
{
// User provided complex query with fields: add it as is to the tag field query
searchTerm = $"tags:AzureSiteExtension {filter}";
}
else
{
// User provided simple string: treat it as a title. This is not ideal behavior, but
// is the best we can do based on how nuget.org works
searchTerm = $"tags:AzureSiteExtension title:\"{filter}\"";
}
return $"https://www.nuget.org/api/v2/Search?searchTerm=%27{searchTerm}%27&includePrerelease=true&semVerLevel=2.0.0";
}
// <summary>
/// Query result by search term, always include pre-released
/// </summary>
public static async Task<IEnumerable<SiteExtensionInfo>> SearchLocalRepo(string siteExtensionRootPath, string searchTerm, SearchFilter filterOptions = null, int skip = 0, int take = 1000)
{
List<SiteExtensionInfo> extensions = new List<SiteExtensionInfo>();
if (!Directory.Exists(siteExtensionRootPath))
{
return extensions;
}
// always include pre-release package
if (filterOptions == null)
{
filterOptions = new SearchFilter();
}
filterOptions.IncludePrerelease = true; // keep the good old behavior
List<string> installedPackages = new List<string>(Directory.EnumerateDirectories(siteExtensionRootPath));
int countEntries = 0;
foreach (string extDir in installedPackages)
{
string nupkgFile = Directory.GetFiles(extDir, "*.nupkg", SearchOption.TopDirectoryOnly).FirstOrDefault();
if (nupkgFile == null)
{
continue;
}
if (skip > 0)
{
--skip;
continue;
}
string packageId = extDir.Substring(extDir.LastIndexOf("\\", StringComparison.OrdinalIgnoreCase) + 1);
if (countEntries++ > take)
{
break;
}
string content = null;
using (ZipFile nupkgZipFile = OperationManager.Attempt(() => ZipFile.Read(nupkgFile), delayBeforeRetry: 1000, shouldRetry: ex => ex is IOException))
{
ZipEntry entry = nupkgZipFile[string.Format("{0}.nuspec", packageId)];
if (entry != null)
{
using (var reader = new StreamReader(entry.OpenReader()))
{
content = await reader.ReadToEndAsync();
}
}
else
{
throw new InvalidOperationException($"{packageId}.nuspec does not exist in {nupkgFile}!");
}
}
if (string.IsNullOrEmpty(content))
{
throw new InvalidOperationException($"{packageId}.nuspec contains empty content!");
}
if (string.IsNullOrEmpty(searchTerm) || content.Contains(searchTerm))
{
using (var reader = XmlReader.Create(new System.IO.StringReader(content)))
{
reader.ReadToDescendant("metadata");
var extInfo = new SiteExtensionInfo((XElement)XNode.ReadFrom(reader));
extensions.Add(extInfo);
}
}
}
return extensions;
}
/// <summary>
/// <para>Query source repository for a package base on given package id and version</para>
/// <para>Will also query pre-release and unlisted packages</para>
/// </summary>
/// <param name="packageId">Package id, must not be null</param>
/// <param name="version">Package version, must not be null</param>
/// <returns>Package metadata</returns>
public static async Task<SiteExtensionInfo> GetPackageByIdentity(string packageId, string version = null)
{
if (string.IsNullOrEmpty(version))
{
return (await PackageCacheInfo.GetPackagesFromNugetAPI()).FirstOrDefault(a => a.Id != null && a.Id == packageId);
}
else
{
string address = null;
try
{
JObject json = null;
using (var client = new HttpClient(new HttpClientHandler { AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate }) { Timeout = HttpClientTimeout })
{
address = $"https://azuresearch-usnc.nuget.org/query?q=tags:AzureSiteExtension%20packageid:{packageId}&prerelease=true&semVerLevel=2.0.0";
using (var response = await client.GetAsync(address))
{
response.EnsureSuccessStatusCode();
json = JObject.Parse(await response.Content.ReadAsStringAsync());
}
json = (JObject)json.Value<JArray>("data").FirstOrDefault();
if (json == null)
{
return null;
}
json = (JObject)json.Value<JArray>("versions").FirstOrDefault(j => j.Value<string>("version") == version);
if (json == null)
{
return null;
}
address = json.Value<string>("@id");
using (var response = await client.GetAsync(address))
{
response.EnsureSuccessStatusCode();
json = JObject.Parse(await response.Content.ReadAsStringAsync());
}
address = json.Value<string>("catalogEntry");
using (var response = await client.GetAsync(address))
{
response.EnsureSuccessStatusCode();
json = JObject.Parse(await response.Content.ReadAsStringAsync());
}
return new SiteExtensionInfo(json);
}
}
catch (Exception ex)
{
if (!string.IsNullOrEmpty(address))
{
throw;
}
throw new InvalidOperationException($"Http request to {address} failed with {ex.Message}", ex);
}
}
}
/// <summary>
/// Helper function to download package from given url, and place package (only 'content' folder from package) to given folder
/// </summary>
/// <param name="identity">Package identity</param>
/// <param name="destinationFolder">Folder where we copy the package content (content folder only) to</param>
/// <param name="pathToLocalCopyOfNupkg">File path where we copy the nudpk to</param>
/// <returns></returns>
public static async Task DownloadPackageToFolder(string packageId, string packageVersion, string destinationFolder, string pathToLocalCopyOfNupkg)
{
using (var client = new HttpClient { Timeout = HttpClientTimeout })
{
var uri = new Uri(String.Format("https://www.nuget.org/api/v2/package/{0}/{1}", packageId, packageVersion));
var response = await client.GetAsync(uri);
using (Stream packageStream = await response.Content.ReadAsStreamAsync())
{
using (ZipFile zipFile = ZipFile.Read(packageStream))
{
// we only care about stuff under "content" folder
int substringStartIndex = @"content/".Length;
IEnumerable<ZipEntry> contentEntries = zipFile.Entries.Where(e => e.FileName.StartsWith(@"content/", StringComparison.InvariantCultureIgnoreCase));
foreach (var entry in contentEntries)
{
string entryFileName = Uri.UnescapeDataString(entry.FileName);
string fullPath = Path.Combine(destinationFolder, entryFileName.Substring(substringStartIndex));
if (entry.IsDirectory)
{
FileSystemHelpers.EnsureDirectory(fullPath.Replace('/', '\\'));
continue;
}
FileSystemHelpers.EnsureDirectory(Path.GetDirectoryName(fullPath));
using (Stream writeStream = FileSystemHelpers.OpenWrite(fullPath))
{
// reset length of file stream
writeStream.SetLength(0);
// let the thread go with itself, so that once file finishes writing, doesn't need to request thread context from main thread
await entry.OpenReader().CopyToAsync(writeStream).ConfigureAwait(false);
}
}
}
// set position back to the head of stream
packageStream.Position = 0;
// save a copy of the nupkg at last
WriteStreamToFile(packageStream, pathToLocalCopyOfNupkg);
}
}
}
public static async Task UpdateLocalPackage(string siteExntentionsRootPath, string packageId, string packageVersion, string destinationFolder, string pathToLocalCopyOfNupkg, ITracer tracer)
{
tracer.Trace("Performing incremental package update for {0}", packageId);
using (var client = new HttpClient { Timeout = HttpClientTimeout })
{
var uri = new Uri(String.Format("https://www.nuget.org/api/v2/package/{0}/{1}", packageId, packageVersion));
var response = await client.GetAsync(uri);
using (Stream newPackageStream = await response.Content.ReadAsStreamAsync())
{
// update file
var localPackage = (await FeedExtensionsV2.SearchLocalRepo(siteExntentionsRootPath, packageId)).FirstOrDefault();
if (localPackage == null)
{
throw new FileNotFoundException(string.Format(CultureInfo.InvariantCulture, "Package {0} not found from local repo.", packageId));
}
string nupkgFile = Directory.GetFiles(Path.Combine(siteExntentionsRootPath, packageId), "*.nupkg", SearchOption.TopDirectoryOnly).FirstOrDefault();
using (ZipFile oldPackageZip = ZipFile.Read(nupkgFile))
using (ZipFile newPackageZip = ZipFile.Read(newPackageStream))
{
// we only care about stuff under "content" folder
IEnumerable<ZipEntry> oldContentEntries = oldPackageZip.Entries.Where(e => e.FileName.StartsWith(@"content/", StringComparison.InvariantCultureIgnoreCase));
IEnumerable<ZipEntry> newContentEntries = newPackageZip.Entries.Where(e => e.FileName.StartsWith(@"content/", StringComparison.InvariantCultureIgnoreCase));
List<ZipEntry> filesNeedToUpdate = new List<ZipEntry>();
Dictionary<string, ZipEntry> indexedOldFiles = new Dictionary<string, ZipEntry>();
foreach (var item in oldContentEntries)
{
indexedOldFiles.Add(item.FileName.ToLowerInvariant(), item);
}
foreach (var newEntry in newContentEntries)
{
var fileName = newEntry.FileName.ToLowerInvariant();
if (indexedOldFiles.ContainsKey(fileName))
{
// file name existed, only update if file has been touched
ZipEntry oldEntry = indexedOldFiles[fileName];
if (oldEntry.LastModified != newEntry.LastModified)
{
filesNeedToUpdate.Add(newEntry);
}
// remove from old index files buffer, the rest will be files that need to be deleted
indexedOldFiles.Remove(fileName);
}
else
{
// new files
filesNeedToUpdate.Add(newEntry);
}
}
int substringStartIndex = @"content/".Length;
foreach (var entry in filesNeedToUpdate)
{
string entryFileName = Uri.UnescapeDataString(entry.FileName);
string fullPath = Path.Combine(destinationFolder, entryFileName.Substring(substringStartIndex));
if (entry.IsDirectory)
{
using (tracer.Step("Ensure directory: {0}", fullPath))
{
FileSystemHelpers.EnsureDirectory(fullPath.Replace('/', '\\'));
}
continue;
}
using (tracer.Step("Adding/Updating file: {0}", fullPath))
{
FileSystemHelpers.EnsureDirectory(Path.GetDirectoryName(fullPath));
using (Stream writeStream = FileSystemHelpers.OpenWrite(fullPath))
{
// reset length of file stream
writeStream.SetLength(0);
// let the thread go with itself, so that once file finishes writing, doesn't need to request thread context from main thread
await entry.OpenReader().CopyToAsync(writeStream).ConfigureAwait(false);
}
}
}
foreach (var entry in indexedOldFiles.Values)
{
string entryFileName = Uri.UnescapeDataString(entry.FileName);
string fullPath = Path.Combine(destinationFolder, entryFileName.Substring(substringStartIndex));
if (entry.IsDirectory)
{
// in case the two zip file was created from different tool. some tool will include folder as seperate entry, some don`t.
// to be sure that folder is meant to be deleted, double check there is no files under it
var entryNameInLower = entryFileName.ToLower();
if (!string.Equals(destinationFolder, fullPath, StringComparison.OrdinalIgnoreCase)
&& newContentEntries.FirstOrDefault(e => e.FileName.ToLowerInvariant().StartsWith(entryNameInLower)) == null)
{
using (tracer.Step("Deleting directory: {0}", fullPath))
{
FileSystemHelpers.DeleteDirectorySafe(fullPath);
}
}
continue;
}
using (tracer.Step("Deleting file: {0}", fullPath))
{
FileSystemHelpers.DeleteFileSafe(fullPath);
}
}
}
// update nupkg
newPackageStream.Position = 0;
using (tracer.Step("Updating nupkg file."))
{
WriteStreamToFile(newPackageStream, pathToLocalCopyOfNupkg);
if (!packageVersion.Equals(localPackage.Version))
{
using (tracer.Step("New package has difference version {0} from old package {1}. Remove old nupkg file.", packageVersion, localPackage.Version))
{
// if version is difference, nupkg file name will be difference. will need to clean up the old one.
var oldNupkg = pathToLocalCopyOfNupkg.Replace(
string.Format(CultureInfo.InvariantCulture, "{0}.{1}.nupkg", packageId, packageVersion),
string.Format(CultureInfo.InvariantCulture, "{0}.{1}.nupkg", localPackage.Id, localPackage.Version));
FileSystemHelpers.DeleteFileSafe(oldNupkg);
}
}
}
}
}
}
private static void WriteStreamToFile(Stream stream, string filePath)
{
string packageFolderPath = Path.GetDirectoryName(filePath);
FileSystemHelpers.EnsureDirectory(packageFolderPath);
using (Stream writeStream = FileSystemHelpers.OpenWrite(filePath))
{
OperationManager.Attempt(() =>
{
// reset length of file stream
writeStream.SetLength(0);
stream.CopyTo(writeStream);
});
}
}
public class PackageCacheInfo
{
private static ConcurrentDictionary<string, PackageCacheInfo> PackageCaches = new ConcurrentDictionary<string, PackageCacheInfo>(StringComparer.OrdinalIgnoreCase);
public DateTime ExpiredUtc { get; set; }
public List<SiteExtensionInfo> Extensions { get; set; }
public static async Task<List<SiteExtensionInfo>> GetPackagesFromNugetAPI(string filter = null, string feedUrl = null)
{
var extensions = new List<SiteExtensionInfo>();
var key = string.Format("{0}:{1}", filter, feedUrl);
PackageCacheInfo info;
if (PackageCaches.TryGetValue(key, out info) && DateTime.UtcNow < info.ExpiredUtc)
{
return info.Extensions;
}
if (string.IsNullOrEmpty(feedUrl))
{
feedUrl = FeedExtensionsV2.GetFeedUrl(filter);
}
using (var client = new HttpClient { Timeout = HttpClientTimeout })
{
var response = await client.GetAsync(feedUrl);
var content = await response.Content.ReadAsStringAsync();
using (var reader = XmlReader.Create(new System.IO.StringReader(content)))
{
reader.ReadStartElement("feed");
while (reader.Read())
{
if (reader.Name == "entry" && reader.IsStartElement())
{
reader.ReadToDescendant("m:properties");
extensions.Add(new SiteExtensionInfo((XElement)XNode.ReadFrom(reader)));
}
}
}
}
info = new PackageCacheInfo
{
ExpiredUtc = DateTime.UtcNow.AddMinutes(10),
Extensions = extensions
};
PackageCaches.AddOrUpdate(key, info, (k, i) => info);
if (PackageCaches.Count > 10)
{
var toRemove = PackageCaches.OrderBy(p => p.Value.ExpiredUtc).FirstOrDefault();
if (!string.IsNullOrWhiteSpace(toRemove.Key))
{
PackageCaches.TryRemove(toRemove.Key, out _);
}
}
return info.Extensions;
}
}
}
}
| 47.526652 | 197 | 0.500224 | [
"Apache-2.0"
] | Teja-Nagoori/kudu | Kudu.Core/SiteExtensions/FeedExtensionsV2.cs | 22,292 | C# |
// <auto-generated>
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Azure.Management.SecurityInsights.Models
{
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// Query based alert rule template base property bag.
/// </summary>
public partial class QueryBasedAlertRuleTemplateProperties
{
/// <summary>
/// Initializes a new instance of the
/// QueryBasedAlertRuleTemplateProperties class.
/// </summary>
public QueryBasedAlertRuleTemplateProperties()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the
/// QueryBasedAlertRuleTemplateProperties class.
/// </summary>
/// <param name="query">The query that creates alerts for this
/// rule.</param>
/// <param name="severity">The severity for alerts created by this
/// alert rule. Possible values include: 'High', 'Medium', 'Low',
/// 'Informational'</param>
/// <param name="tactics">The tactics of the alert rule</param>
/// <param name="version">The version of this template - in format
/// <a.b.c>, where all are numbers. For example
/// <1.0.2>.</param>
/// <param name="customDetails">Dictionary of string key-value pairs of
/// columns to be attached to the alert</param>
/// <param name="entityMappings">Array of the entity mappings of the
/// alert rule</param>
/// <param name="alertDetailsOverride">The alert details override
/// settings</param>
public QueryBasedAlertRuleTemplateProperties(string query = default(string), string severity = default(string), IList<string> tactics = default(IList<string>), string version = default(string), IDictionary<string, string> customDetails = default(IDictionary<string, string>), IList<EntityMapping> entityMappings = default(IList<EntityMapping>), AlertDetailsOverride alertDetailsOverride = default(AlertDetailsOverride))
{
Query = query;
Severity = severity;
Tactics = tactics;
Version = version;
CustomDetails = customDetails;
EntityMappings = entityMappings;
AlertDetailsOverride = alertDetailsOverride;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// Gets or sets the query that creates alerts for this rule.
/// </summary>
[JsonProperty(PropertyName = "query")]
public string Query { get; set; }
/// <summary>
/// Gets or sets the severity for alerts created by this alert rule.
/// Possible values include: 'High', 'Medium', 'Low', 'Informational'
/// </summary>
[JsonProperty(PropertyName = "severity")]
public string Severity { get; set; }
/// <summary>
/// Gets or sets the tactics of the alert rule
/// </summary>
[JsonProperty(PropertyName = "tactics")]
public IList<string> Tactics { get; set; }
/// <summary>
/// Gets or sets the version of this template - in format
/// &lt;a.b.c&gt;, where all are numbers. For example
/// &lt;1.0.2&gt;.
/// </summary>
[JsonProperty(PropertyName = "version")]
public string Version { get; set; }
/// <summary>
/// Gets or sets dictionary of string key-value pairs of columns to be
/// attached to the alert
/// </summary>
[JsonProperty(PropertyName = "customDetails")]
public IDictionary<string, string> CustomDetails { get; set; }
/// <summary>
/// Gets or sets array of the entity mappings of the alert rule
/// </summary>
[JsonProperty(PropertyName = "entityMappings")]
public IList<EntityMapping> EntityMappings { get; set; }
/// <summary>
/// Gets or sets the alert details override settings
/// </summary>
[JsonProperty(PropertyName = "alertDetailsOverride")]
public AlertDetailsOverride AlertDetailsOverride { get; set; }
}
}
| 40.25 | 427 | 0.619405 | [
"MIT"
] | 93mishra/azure-sdk-for-net | sdk/securityinsights/Microsoft.Azure.Management.SecurityInsights/src/Generated/Models/QueryBasedAlertRuleTemplateProperties.cs | 4,669 | C# |
#region License
// Copyright (c) 2016-2018 Cisco Systems, Inc.
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace WebexSDK
{
#pragma warning disable S101 // Types should be named in camel case
internal class JWTAccessToken
#pragma warning restore S101 // Types should be named in camel case
{
public readonly string token;
public int tokenExpirationSinceNow;
public readonly DateTime tokenExpiration;
public readonly DateTime tokenCreationDate;
public JWTAccessToken(string token, int tokenExpirationSinceNow)
{
this.token = token;
this.tokenExpirationSinceNow = tokenExpirationSinceNow;
tokenCreationDate = DateTime.Now;
this.tokenExpiration = tokenCreationDate.AddSeconds(tokenExpirationSinceNow);
}
}
#pragma warning disable S101 // Types should be named in camel case
internal class JWTAuthClient
#pragma warning restore S101 // Types should be named in camel case
{
public void FetchTokenFromJWTAsync(string jwt, IAuthenticator authenticator,Action<WebexApiEventArgs<JWTAccessTokenInfo>> completionHandler)
{
var request = new ServiceRequest(authenticator)
{
Method = HttpMethod.POST,
Resource = "jwt/login"
};
request.AddHeaders("Authorization", jwt);
request.ExecuteAuth<JWTAccessTokenInfo>((response) =>
{
completionHandler(response);
});
}
}
}
| 37.943662 | 148 | 0.708241 | [
"MIT"
] | alexpacket/webex-windows-sdk | sdk/WebexWinSDK/Source/Auth/JWTAuthClient.cs | 2,696 | C# |
/*
* Copyright 2018 JDCLOUD.COM
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http:#www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ES Index LifeCycle API
* 支持针对索引模板每天、每周或每月定时创建索引;支持定期删除索引。
*
* OpenAPI spec version: v1
* Contact:
*
* NOTE: This class is auto generated by the jdcloud code generator program.
*/
using System;
using System.Collections.Generic;
using System.Text;
using JDCloudSDK.Core.Service;
namespace JDCloudSDK.Es.Apis
{
/// <summary>
/// 针对某个索引模板,创建定时任务
/// </summary>
public class CreateIndexTemplateCronTaskResult : JdcloudResult
{
///<summary>
/// 定时任务ID
///</summary>
public string TaskId{ get; set; }
}
} | 25.888889 | 76 | 0.694421 | [
"Apache-2.0"
] | jdcloud-api/jdcloud-sdk-net | sdk/src/Service/Es/Apis/CreateIndexTemplateCronTaskResult.cs | 1,267 | C# |
// ------------------------------------------------------------------------------
// 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.IO;
using System.Net.Http;
using System.Threading;
/// <summary>
/// The type WorkbookRangeOffsetRangeRequest.
/// </summary>
public partial class WorkbookRangeOffsetRangeRequest : BaseRequest, IWorkbookRangeOffsetRangeRequest
{
/// <summary>
/// Constructs a new WorkbookRangeOffsetRangeRequest.
/// </summary>
public WorkbookRangeOffsetRangeRequest(
string requestUrl,
IBaseClient client,
IEnumerable<Option> options)
: base(requestUrl, client, options)
{
}
/// <summary>
/// Issues the GET request.
/// </summary>
public System.Threading.Tasks.Task<WorkbookRange> GetAsync()
{
return this.GetAsync(CancellationToken.None);
}
/// <summary>
/// Issues the GET request.
/// </summary>
/// <param name=""cancellationToken"">The <see cref=""CancellationToken""/> for the request.</param>
/// <returns>The task to await for async call.</returns>
public System.Threading.Tasks.Task<WorkbookRange> GetAsync(
CancellationToken cancellationToken)
{
this.Method = "GET";
return this.SendAsync<WorkbookRange>(null, cancellationToken);
}
/// <summary>
/// Issues the PATCH request.
/// </summary>
/// <param name=workbookrange>The WorkbookRange object set with the properties to update.</param>
/// <returns>The task to await for async call.</returns>
public System.Threading.Tasks.Task<WorkbookRange> PatchAsync(WorkbookRange workbookrange)
{
return this.PatchAsync(workbookrange, CancellationToken.None);
}
/// <summary>
/// Issues the PATCH request.
/// </summary>
/// <param name=workbookrange>The WorkbookRange object set with the properties to update.</param>
/// <param name=""cancellationToken"">The <see cref=""CancellationToken""/> for the request.</param>
/// <returns>The task to await for async call.</returns>
public System.Threading.Tasks.Task<WorkbookRange> PatchAsync(WorkbookRange workbookrange,
CancellationToken cancellationToken)
{
this.Method = "PATCH";
return this.SendAsync<WorkbookRange>(workbookrange, cancellationToken);
}
/// <summary>
/// Issues the PUT request.
/// </summary>
/// <param name=workbookrange>The WorkbookRange object to update.</param>
/// <returns>The task to await for async call.</returns>
public System.Threading.Tasks.Task<WorkbookRange> PutAsync(WorkbookRange workbookrange)
{
return this.PutAsync(workbookrange, CancellationToken.None);
}
/// <summary>
/// Issues the PUT request.
/// </summary>
/// <param name=workbookrange>The WorkbookRange object to update.</param>
/// <param name=""cancellationToken"">The <see cref=""CancellationToken""/> for the request.</param>
/// <returns>The task to await for async call.</returns>
public System.Threading.Tasks.Task<WorkbookRange> PutAsync(WorkbookRange workbookrange,
CancellationToken cancellationToken)
{
this.Method = "PUT";
return this.SendAsync<WorkbookRange>(workbookrange, cancellationToken);
}
/// <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 IWorkbookRangeOffsetRangeRequest Expand(string value)
{
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 IWorkbookRangeOffsetRangeRequest Select(string value)
{
this.QueryOptions.Add(new QueryOption("$select", value));
return this;
}
}
}
| 39.319672 | 153 | 0.592662 | [
"MIT"
] | twsouthwick/msgraph-sdk-dotnet | src/Microsoft.Graph/Requests/Generated/WorkbookRangeOffsetRangeRequest.cs | 4,797 | C# |
using HotChocolate;
using Microsoft.Extensions.DependencyInjection;
using Snowflake.Services;
using Snowflake.Support.GraphQL.Server;
using Snowflake.Support.GraphQLFrameworkQueries.Containers;
using System;
using System.IO;
using Xunit;
namespace Snowflake.Remoting.GraphQL.Tests
{
public class ServerIntegrationTests
{
[Fact]
public void FrameworkSchemaCreation_Tests()
{
var appDataDirectory = new DirectoryInfo(System.IO.Path.GetTempPath())
.CreateSubdirectory(Guid.NewGuid().ToString());
var container = new ServiceContainer(appDataDirectory.FullName, "http://localhost:9797");
var schema = new GraphQLSchemaRegistrationProvider(container.Get<ILogProvider>().GetLogger("graphql"));
var schemaBuilder = new HotChocolateSchemaBuilder(schema, container.GetServiceContainerAsServiceProvider());
schemaBuilder.Create(true)
.Create()
.MakeExecutable();
//schemaBuilder.AddSnowflakeQueryRequestInterceptor(collection);
//schemaBuilder.AddStoneIdTypeConverters(collection);
}
[Fact]
public void FrameworkQueryCreation_Tests()
{
var appDataDirectory = new DirectoryInfo(System.IO.Path.GetTempPath())
.CreateSubdirectory(Guid.NewGuid().ToString());
var container = new ServiceContainer(appDataDirectory.FullName, "http://localhost:9797");
var schema = new GraphQLSchemaRegistrationProvider(container.Get<ILogProvider>().GetLogger("graphql"));
var schemaBuilder = new HotChocolateSchemaBuilder(schema, container.GetServiceContainerAsServiceProvider());
new QueryContainer().ConfigureHotChocolate(schema);
schemaBuilder.Create(false)
.Create()
.MakeExecutable();
}
}
}
| 42.977273 | 120 | 0.682179 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | hafixo/snowflake-1 | src/Snowflake.Framework.Tests/GraphQL/ServerIntegrationTests.cs | 1,891 | C# |
using System;
using System.Linq;
using MathNet.Numerics.Random;
using Xunit;
using PopOptBox.Base.Variables;
namespace PopOptBox.Optimisers.EvolutionaryComputation.Test
{
public class RandomNumberManagerTests
{
private readonly RandomNumberManager rngManager;
private readonly DecisionVector testDv;
public RandomNumberManagerTests()
{
testDv = DecisionVector.CreateFromArray(
DecisionSpace.CreateForUniformIntArray(8, 0, 7),
new int[8] {7, 6, 5, 4, 3, 2, 1, 0});
rngManager = new RandomNumberManager(new MersenneTwister(123456789));
}
[Fact]
public void GetLocations_InvalidNumberOfLocations_Throws()
{
Assert.Throws<ArgumentOutOfRangeException>(() =>
rngManager.GetLocations(testDv.Count,
maximumNumberOfLocations: testDv.Count + 1,
selectionWithReplacement: false));
Assert.Throws<ArgumentOutOfRangeException>(() =>
rngManager.GetLocations(testDv.Count,
maximumNumberOfLocations: 0,
selectionWithReplacement: false));
}
[Fact]
public void GetLocations_InvalidProbabilityOfSelection_Throws()
{
Assert.Throws<ArgumentOutOfRangeException>(() =>
rngManager.GetLocations(testDv.Count,
lambda: -0.01));
Assert.Throws<ArgumentOutOfRangeException>(() =>
rngManager.GetLocations(testDv.Count,
lambda: 1.01));
}
[Fact]
public void GetLocations_OneLocationRequested_ZeroProbability_ReturnsEmptyList()
{
var locations = rngManager.GetLocations(testDv.Count,
maximumNumberOfLocations: 1,
lambda: 0);
Assert.True(!locations.Any());
}
[Fact]
public void GetLocations_OneLocationRequested_CertainProbability_ReturnsOneValidLocation()
{
for (var i = 0; i < 10; i++)
{
// Try this a few times to try to cause a mistake.
var locations = rngManager.GetLocations(testDv.Count,
maximumNumberOfLocations: 1,
selectionWithReplacement: false,
lambda: 1);
Assert.True(locations.Count() == 1);
Assert.True(locations.ElementAt(0) >= 0 && locations.ElementAt(0) < testDv.Count);
}
}
[Fact]
public void GetLocations_FiveLocationsRequestedWithReplacement_CertainProbability_ReturnsFiveValidLocations()
{
for (var i = 0; i < 10; i++)
{
// Try this a few times to try to cause a mistake.
var locations = rngManager.GetLocations(testDv.Count,
maximumNumberOfLocations: 5,
selectionWithReplacement: true,
lambda: 1);
Assert.True(locations.Count() == 5);
Assert.True(locations.All(l => l >= 0 && l < testDv.Count));
}
}
[Fact]
public void GetLocations_SameNumberAsLength_NoReplacement_ReturnsAllUniqueValidLocations()
{
for (var i = 0; i < 10; i++)
{
// Try this a few times to try to cause a mistake.
var locations = rngManager.GetLocations(testDv.Count,
maximumNumberOfLocations: testDv.Count,
selectionWithReplacement: false,
lambda: 1);
Assert.True(locations.Count() == testDv.Count);
Assert.True(locations.Distinct().Count() == testDv.Count);
Assert.True(locations.All(l => l >= 0 && l < testDv.Count));
}
}
}
} | 36.743119 | 117 | 0.545318 | [
"MIT"
] | Clymsw/PopOptBox | PopOptBox.Optimisers.EvolutionaryComputation.Test/RandomNumberManagerTests.cs | 4,005 | C# |
// Python Tools for Visual Studio
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABILITY 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.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.PythonTools.Editor;
using Microsoft.PythonTools.Infrastructure;
using Microsoft.PythonTools.Intellisense;
using Microsoft.PythonTools.Interpreter;
using Microsoft.PythonTools.Options;
using Microsoft.PythonTools.Parsing;
using Microsoft.PythonTools.Project;
using Microsoft.VisualStudio.InteractiveWindow;
using Microsoft.VisualStudio.InteractiveWindow.Commands;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor.OptionsExtensionMethods;
using Microsoft.VisualStudio.Utilities;
using Microsoft.VisualStudioTools;
using Task = System.Threading.Tasks.Task;
namespace Microsoft.PythonTools.Repl {
[InteractiveWindowRole("Execution")]
[InteractiveWindowRole("Reset")]
[ContentType(PythonCoreConstants.ContentType)]
[ContentType(PredefinedInteractiveCommandsContentTypes.InteractiveCommandContentTypeName)]
internal abstract class PythonCommonInteractiveEvaluator :
IInteractiveEvaluator,
IPythonInteractiveEvaluator,
IMultipleScopeEvaluator,
IPythonInteractiveIntellisense,
IDisposable {
protected readonly IServiceProvider _serviceProvider;
private readonly StringBuilder _deferredOutput;
private PythonProjectNode _projectWithHookedEvents;
private IPythonWorkspaceContext _workspaceWithHookedEvents;
protected IInteractiveWindowCommands _commands;
private IInteractiveWindow _window;
private PythonInteractiveOptions _options;
protected VsProjectAnalyzer _analyzer;
private Uri _documentUri;
private int _nextDocumentIndex;
private bool _enableMultipleScopes;
private IReadOnlyList<string> _availableScopes;
private bool _isDisposed;
internal const string DoNotResetConfigurationLaunchOption = "DoNotResetConfiguration";
public PythonCommonInteractiveEvaluator(IServiceProvider serviceProvider) {
_serviceProvider = serviceProvider ?? throw new ArgumentNullException(nameof(serviceProvider));
_deferredOutput = new StringBuilder();
_documentUri = new Uri($"repl://{Guid.NewGuid()}/repl.py");
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2213:DisposableFieldsShouldBeDisposed", MessageId = "_analyzer")]
protected virtual void Dispose(bool disposing) {
if (_isDisposed) {
return;
}
_isDisposed = true;
if (_projectWithHookedEvents != null) {
_projectWithHookedEvents.ActiveInterpreterChanged -= Project_ConfigurationChanged;
_projectWithHookedEvents._searchPaths.Changed -= Project_ConfigurationChanged;
_projectWithHookedEvents = null;
}
if (_workspaceWithHookedEvents != null) {
_workspaceWithHookedEvents.ActiveInterpreterChanged -= Workspace_ConfigurationChanged;
_workspaceWithHookedEvents.SearchPathsSettingChanged -= Workspace_ConfigurationChanged;
_workspaceWithHookedEvents = null;
}
if (disposing) {
_analyzer?.Dispose();
}
}
public void Dispose() {
Dispose(true);
GC.SuppressFinalize(this);
}
~PythonCommonInteractiveEvaluator() {
Dispose(false);
}
public string DisplayName { get; set; }
public string ProjectMoniker { get; set; }
public string WorkspaceMoniker { get; set; }
public LaunchConfiguration Configuration { get; set; }
public string ScriptsPath { get; set; }
public PythonLanguageVersion LanguageVersion {
get {
return Configuration?.Interpreter?.Version.ToLanguageVersion() ?? PythonLanguageVersion.None;
}
}
public bool UseSmartHistoryKeys { get; set; }
public bool LiveCompletionsOnly { get; set; }
public string BackendName { get; set; }
internal bool AssociatedProjectHasChanged { get; set; }
internal bool AssociatedWorkspaceHasChanged { get; set; }
private PythonProjectNode GetAssociatedPythonProject(InterpreterConfiguration interpreter = null) {
_serviceProvider.GetUIThread().MustBeCalledFromUIThread();
var moniker = ProjectMoniker;
if (interpreter == null) {
interpreter = Configuration?.Interpreter;
}
if (string.IsNullOrEmpty(moniker) && interpreter != null) {
var interpreterService = _serviceProvider.GetComponentModel().GetService<IInterpreterRegistryService>();
moniker = interpreterService.GetProperty(interpreter.Id, "ProjectMoniker") as string;
}
if (string.IsNullOrEmpty(moniker)) {
return null;
}
return _serviceProvider.GetProjectFromFile(moniker);
}
private IPythonWorkspaceContext GetAssociatedPythonWorkspace(InterpreterConfiguration interpreter = null) {
_serviceProvider.GetUIThread().MustBeCalledFromUIThread();
if (string.IsNullOrEmpty(WorkspaceMoniker)) {
return null;
}
return _serviceProvider.GetWorkspace();
}
public virtual VsProjectAnalyzer Analyzer => _analyzer;
public virtual async Task<VsProjectAnalyzer> GetAnalyzerAsync() {
if (_analyzer != null) {
return _analyzer;
}
var config = Configuration;
IPythonInterpreterFactory factory = null;
if (config?.Interpreter != null) {
var interpreterService = _serviceProvider.GetComponentModel().GetService<IInterpreterRegistryService>();
factory = interpreterService.FindInterpreter(config.Interpreter.Id);
}
return await _serviceProvider.GetUIThread().InvokeTask(async () => {
var a = _analyzer;
if (a != null) {
return a;
}
if (factory == null) {
a = await _serviceProvider.GetPythonToolsService().GetSharedAnalyzerAsync();
} else {
a = await VsProjectAnalyzer.CreateForInteractiveAsync(
_serviceProvider.GetComponentModel().GetService<PythonEditorServices>(),
factory,
DisplayName.IfNullOrEmpty("Unnamed")
);
IEnumerable<string> sp;
var workspace = GetAssociatedPythonWorkspace(config.Interpreter);
var pyProject = GetAssociatedPythonProject(config.Interpreter);
if (workspace != null) {
sp = workspace.GetAbsoluteSearchPaths().ToArray();
} else if (pyProject != null) {
sp = pyProject.GetSearchPaths();
} else {
var sln = _serviceProvider.GetService(typeof(SVsSolution)) as IVsSolution;
sp = sln?.EnumerateLoadedPythonProjects().SelectMany(p => p.GetSearchPaths()).ToArray();
}
await a.SetSearchPathsAsync(sp.MaybeEnumerate());
}
if (_analyzer != null) {
a.Dispose();
} else {
_analyzer = a;
}
return _analyzer;
});
}
public virtual Uri DocumentUri { get => _documentUri; protected set => _documentUri = value; }
public virtual Uri NextDocumentUri() {
var d = DocumentUri;
if (d != null) {
return new Uri(d, $"#{++_nextDocumentIndex}");
}
return null;
}
internal void WriteOutput(string text, bool addNewline = true) {
var wnd = CurrentWindow;
if (wnd == null) {
lock (_deferredOutput) {
_deferredOutput.Append(text);
}
} else {
AppendTextWithEscapes(wnd, text, addNewline, isError: false);
}
}
internal void WriteError(string text, bool addNewline = true) {
var wnd = CurrentWindow;
if (wnd == null) {
lock (_deferredOutput) {
_deferredOutput.Append(text);
}
} else {
AppendTextWithEscapes(wnd, text, addNewline, isError: true);
}
}
public abstract bool IsDisconnected { get; }
public abstract bool IsExecuting { get; }
public abstract string CurrentScopeName { get; }
public abstract string CurrentScopePath { get; }
public abstract string CurrentWorkingDirectory { get; }
public IInteractiveWindow CurrentWindow {
get {
return _window;
}
set {
_commands = null;
if (value != null) {
lock (_deferredOutput) {
AppendTextWithEscapes(value, _deferredOutput.ToString(), false, false);
_deferredOutput.Clear();
}
_options = _serviceProvider.GetPythonToolsService().InteractiveOptions;
_options.Changed += InteractiveOptions_Changed;
UseSmartHistoryKeys = _options.UseSmartHistory;
LiveCompletionsOnly = _options.LiveCompletionsOnly;
} else {
if (_options != null) {
_options.Changed -= InteractiveOptions_Changed;
_options = null;
}
}
_window = value;
}
}
private async void InteractiveOptions_Changed(object sender, EventArgs e) {
if (!ReferenceEquals(sender, _options)) {
return;
}
UseSmartHistoryKeys = _options.UseSmartHistory;
LiveCompletionsOnly = _options.LiveCompletionsOnly;
var window = CurrentWindow;
if (window == null) {
return;
}
await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();
window.TextView.Options.SetOptionValue(InteractiveWindowOptions.SmartUpDown, UseSmartHistoryKeys);
}
public bool EnableMultipleScopes {
get { return _enableMultipleScopes; }
set {
if (_enableMultipleScopes != value) {
_enableMultipleScopes = value;
MultipleScopeSupportChanged?.Invoke(this, EventArgs.Empty);
}
}
}
public event EventHandler<EventArgs> AvailableScopesChanged;
public event EventHandler<EventArgs> MultipleScopeSupportChanged;
public abstract Task<bool> GetSupportsMultipleStatementsAsync();
protected void SetAvailableScopes(string[] scopes) {
_availableScopes = scopes;
AvailableScopesChanged?.Invoke(this, EventArgs.Empty);
}
public abstract IEnumerable<KeyValuePair<string, string>> GetAvailableScopesAndPaths();
public abstract CompletionResult[] GetMemberNames(string text);
public abstract OverloadDoc[] GetSignatureDocumentation(string text);
public abstract void AbortExecution();
public bool CanExecuteCode(string text) {
return CanExecuteCode(text, out _);
}
protected bool CanExecuteCode(string text, out ParseResult pr) {
pr = ParseResult.Complete;
if (string.IsNullOrEmpty(text)) {
return true;
}
if (string.IsNullOrWhiteSpace(text) && text.EndsWithOrdinal("\n")) {
pr = ParseResult.Empty;
return true;
}
var config = Configuration;
var parser = Parser.CreateParser(new StringReader(text), LanguageVersion);
parser.ParseInteractiveCode(out pr);
if (pr == ParseResult.IncompleteStatement || pr == ParseResult.Empty) {
return text.EndsWithOrdinal("\n");
}
if (pr == ParseResult.IncompleteToken) {
return false;
}
return true;
}
protected abstract Task ExecuteStartupScripts(string scriptsPath);
internal Task<ExecutionResult> UpdatePropertiesFromProjectMonikerAsync() {
return _serviceProvider.GetUIThread().InvokeAsync(UpdatePropertiesFromProjectMoniker);
}
internal Task<ExecutionResult> UpdatePropertiesFromWorkspaceMonikerAsync() {
return _serviceProvider.GetUIThread().InvokeAsync(UpdatePropertiesFromWorkspaceMoniker);
}
internal ExecutionResult UpdatePropertiesFromProjectMoniker() {
try {
if (_projectWithHookedEvents != null) {
_projectWithHookedEvents.ActiveInterpreterChanged -= Project_ConfigurationChanged;
_projectWithHookedEvents._searchPaths.Changed -= Project_ConfigurationChanged;
_projectWithHookedEvents = null;
}
AssociatedProjectHasChanged = false;
var pyProj = GetAssociatedPythonProject();
if (pyProj == null) {
return ExecutionResult.Success;
}
if (Configuration?.GetLaunchOption(DoNotResetConfigurationLaunchOption) == null) {
Configuration = pyProj.GetLaunchConfigurationOrThrow();
if (Configuration?.Interpreter != null) {
try {
ScriptsPath = GetScriptsPath(_serviceProvider, Configuration.Interpreter.Description, Configuration.Interpreter);
} catch (Exception ex) when (!ex.IsCriticalException()) {
ScriptsPath = null;
}
}
}
_projectWithHookedEvents = pyProj;
pyProj.ActiveInterpreterChanged += Project_ConfigurationChanged;
pyProj._searchPaths.Changed += Project_ConfigurationChanged;
return ExecutionResult.Success;
} catch (NoInterpretersException) {
WriteError(Strings.NoInterpretersAvailable);
} catch (MissingInterpreterException ex) {
WriteError(ex.ToString());
} catch (IOException ex) {
WriteError(ex.ToString());
} catch (Exception ex) when (!ex.IsCriticalException()) {
WriteError(ex.ToUnhandledExceptionMessage(GetType()));
}
return ExecutionResult.Failure;
}
internal ExecutionResult UpdatePropertiesFromWorkspaceMoniker() {
try {
if (_workspaceWithHookedEvents != null) {
_workspaceWithHookedEvents.ActiveInterpreterChanged -= Workspace_ConfigurationChanged;
_workspaceWithHookedEvents.SearchPathsSettingChanged -= Workspace_ConfigurationChanged;
_workspaceWithHookedEvents = null;
}
AssociatedWorkspaceHasChanged = false;
var workspace = GetAssociatedPythonWorkspace();
if (workspace == null) {
return ExecutionResult.Success;
}
if (Configuration?.GetLaunchOption(DoNotResetConfigurationLaunchOption) == null) {
Configuration = GetWorkspaceLaunchConfigurationOrThrow(workspace);
if (Configuration?.Interpreter != null) {
try {
ScriptsPath = GetScriptsPath(_serviceProvider, Configuration.Interpreter.Description, Configuration.Interpreter);
} catch (Exception ex) when (!ex.IsCriticalException()) {
ScriptsPath = null;
}
}
}
_workspaceWithHookedEvents = workspace;
workspace.ActiveInterpreterChanged += Workspace_ConfigurationChanged;
workspace.SearchPathsSettingChanged += Workspace_ConfigurationChanged;
return ExecutionResult.Success;
} catch (NoInterpretersException) {
WriteError(Strings.NoInterpretersAvailable);
} catch (MissingInterpreterException ex) {
WriteError(ex.ToString());
} catch (IOException ex) {
WriteError(ex.ToString());
} catch (Exception ex) when (!ex.IsCriticalException()) {
WriteError(ex.ToUnhandledExceptionMessage(GetType()));
}
return ExecutionResult.Failure;
}
internal static LaunchConfiguration GetWorkspaceLaunchConfigurationOrThrow(IPythonWorkspaceContext workspace) {
var fact = GetWorkspaceInterpreterFactoryOrThrow(workspace);
var config = new LaunchConfiguration(fact.Configuration) {
WorkingDirectory = workspace.Location,
SearchPaths = workspace.GetAbsoluteSearchPaths().ToList()
};
return config;
}
private static IPythonInterpreterFactory GetWorkspaceInterpreterFactoryOrThrow(IPythonWorkspaceContext workspace) {
var fact = workspace.CurrentFactory;
if (fact == null) {
throw new NoInterpretersException();
}
if (!fact.Configuration.IsAvailable()) {
throw new MissingInterpreterException(
Strings.MissingEnvironment.FormatUI(fact.Configuration.Description, fact.Configuration.Version)
);
}
return fact;
}
private void Project_ConfigurationChanged(object sender, EventArgs e) {
var pyProj = _projectWithHookedEvents;
_projectWithHookedEvents = null;
if (pyProj != null) {
Debug.Assert(pyProj == sender || pyProj._searchPaths == sender, "Unexpected project raised the event");
// Only warn once
pyProj.ActiveInterpreterChanged -= Project_ConfigurationChanged;
pyProj._searchPaths.Changed -= Project_ConfigurationChanged;
WriteError(Strings.ReplProjectConfigurationChanged.FormatUI(pyProj.Caption));
AssociatedProjectHasChanged = true;
}
}
private void Workspace_ConfigurationChanged(object sender, EventArgs e) {
var workspace = _workspaceWithHookedEvents;
_workspaceWithHookedEvents = null;
if (workspace != null) {
Debug.Assert(workspace == sender, "Unexpected workspace raised the event");
// Only warn once
workspace.ActiveInterpreterChanged -= Workspace_ConfigurationChanged;
workspace.SearchPathsSettingChanged -= Workspace_ConfigurationChanged;
WriteError(Strings.ReplWorkspaceConfigurationChanged.FormatUI(workspace.WorkspaceName));
AssociatedWorkspaceHasChanged = true;
}
}
internal static string GetScriptsPath(
IServiceProvider provider,
string displayName,
InterpreterConfiguration config,
bool onlyIfExists = true
) {
provider.MustBeCalledFromUIThread();
var root = provider.GetPythonToolsService().InteractiveOptions.Scripts;
if (Path.GetInvalidPathChars().Any(c => root.Contains(c))) {
throw new DirectoryNotFoundException(root);
}
if (string.IsNullOrEmpty(root)) {
try {
if (!provider.TryGetShellProperty((__VSSPROPID)__VSSPROPID2.VSSPROPID_VisualStudioDir, out root)) {
root = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
root = PathUtils.GetAbsoluteDirectoryPath(root, "Visual Studio {0}".FormatInvariant(AssemblyVersionInfo.VSName));
}
root = PathUtils.GetAbsoluteDirectoryPath(root, "Python Scripts");
} catch (ArgumentException argEx) {
throw new DirectoryNotFoundException(root, argEx);
}
}
string candidate;
if (!string.IsNullOrEmpty(displayName)) {
foreach (var c in Path.GetInvalidFileNameChars()) {
displayName = displayName.Replace(c, '_');
}
try {
candidate = PathUtils.GetAbsoluteDirectoryPath(root, displayName);
} catch (ArgumentException argEx) {
throw new DirectoryNotFoundException(root, argEx);
}
if (!onlyIfExists || Directory.Exists(candidate)) {
return candidate;
}
}
var version = config?.Version?.ToString();
if (!string.IsNullOrEmpty(version)) {
try {
candidate = PathUtils.GetAbsoluteDirectoryPath(root, version);
} catch (ArgumentException argEx) {
throw new DirectoryNotFoundException(root, argEx);
}
if (!onlyIfExists || Directory.Exists(candidate)) {
return candidate;
}
}
return null;
}
public abstract Task<ExecutionResult> ExecuteCodeAsync(string text);
public abstract Task<bool> ExecuteFileAsync(string filename, string extraArgs);
public abstract Task<bool> ExecuteModuleAsync(string name, string extraArgs);
public abstract Task<bool> ExecuteProcessAsync(string filename, string extraArgs);
const string _splitRegexPattern = @"(?x)\s*,\s*(?=(?:[^""]*""[^""]*"")*[^""]*$)"; // http://regexhero.net/library/52/
private static Regex _splitLineRegex = new Regex(_splitRegexPattern);
public string FormatClipboard() {
return FormatClipboard(_serviceProvider, CurrentWindow);
}
internal static string FormatClipboard(IServiceProvider serviceProvider, IInteractiveWindow interactiveWindow) {
// WPF and Windows Forms Clipboard behavior differs when it comes
// to DataFormats.CommaSeparatedValue.
// WPF will always return the data as a string, no matter how it
// was set, but Windows Forms may return a Stream or a string.
// Use WPF Clipboard fully qualified name to ensure we don't
// accidentally end up using the wrong clipboard implementation
// if this code is moved.
if (System.Windows.Clipboard.ContainsData(System.Windows.DataFormats.CommaSeparatedValue)) {
string data = System.Windows.Clipboard.GetData(System.Windows.DataFormats.CommaSeparatedValue) as string;
if (data != null) {
string[] lines = data.Split(new[] { "\n", "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
StringBuilder res = new StringBuilder();
res.AppendLine("[");
foreach (var line in lines) {
string[] items = _splitLineRegex.Split(line);
res.Append(" [");
for (int i = 0; i < items.Length; i++) {
res.Append(FormatItem(items[i]));
if (i != items.Length - 1) {
res.Append(", ");
}
}
res.AppendLine("],");
}
res.AppendLine("]");
return res.ToString();
}
}
var txt = System.Windows.Clipboard.GetText();
if (!serviceProvider.GetPythonToolsService().AdvancedOptions.PasteRemovesReplPrompts) {
return txt;
}
return ReplPromptHelpers.RemovePrompts(txt, interactiveWindow.TextView.Options.GetNewLineCharacter());
}
private static string FormatItem(string item) {
if (String.IsNullOrWhiteSpace(item)) {
return "None";
}
double doubleVal;
int intVal;
if (Double.TryParse(item, out doubleVal) ||
Int32.TryParse(item, out intVal)) {
return item;
}
if (item[0] == '"' && item[item.Length - 1] == '"' && item.IndexOf(',') != -1) {
// remove outer quotes, remove "" escaping
item = item.Substring(1, item.Length - 2).Replace("\"\"", "\"");
}
// put in single quotes and escape single quotes and backslashes
return "'" + item.Replace("\\", "\\\\").Replace("'", "\\'") + "'";
}
public IEnumerable<string> GetAvailableScopes() {
return _availableScopes ?? Enumerable.Empty<string>();
}
public abstract void SetScope(string scopeName);
public string GetPrompt() {
if ((_window?.CurrentLanguageBuffer.CurrentSnapshot.LineCount ?? 1) > 1) {
return SecondaryPrompt;
} else {
return PrimaryPrompt;
}
}
internal abstract string PrimaryPrompt { get; }
internal abstract string SecondaryPrompt { get; }
public virtual async Task<ExecutionResult> InitializeAsync() {
if (_commands != null) {
// Already initialized
return ExecutionResult.Success;
}
var msg = Strings.ReplInitializationMessage.FormatUI(
DisplayName,
AssemblyVersionInfo.Version,
AssemblyVersionInfo.VSVersion
).Replace("", "\x1b");
WriteOutput(msg, addNewline: true);
var langBuffer = _window.CurrentLanguageBuffer;
if (langBuffer != null) {
// Reinitializing, and our new language buffer does not automatically
// get connected to the Intellisense controller. Let's fix that.
var controller = IntellisenseControllerProvider.GetController(_window.TextView);
controller?.ConnectSubjectBuffer(langBuffer);
}
_window.TextView.Options.SetOptionValue(InteractiveWindowOptions.SmartUpDown, UseSmartHistoryKeys);
_commands = GetInteractiveCommands(_serviceProvider, _window, this);
return ExecutionResult.Success;
}
public async Task<ExecutionResult> ResetAsync(bool initialize = true) {
await UpdatePropertiesFromProjectMonikerAsync();
await UpdatePropertiesFromWorkspaceMonikerAsync();
return await ResetWorkerAsync(initialize, false);
}
public async Task<ExecutionResult> ResetAsync(bool initialize, bool quiet) {
await UpdatePropertiesFromProjectMonikerAsync();
await UpdatePropertiesFromWorkspaceMonikerAsync();
return await ResetWorkerAsync(initialize, quiet);
}
protected abstract Task<ExecutionResult> ResetWorkerAsync(bool initialize, bool quiet);
internal Task InvokeAsync(Action action) {
return _window.TextView.VisualElement.Dispatcher.InvokeAsync(action).Task;
}
internal void WriteFrameworkElement(System.Windows.UIElement control, System.Windows.Size desiredSize) {
if (_window == null) {
return;
}
_window.Write("");
_window.FlushOutput();
var caretPos = _window.TextView.Caret.Position.BufferPosition;
var manager = InlineReplAdornmentProvider.GetManager(_window.TextView);
manager.AddAdornment(new ZoomableInlineAdornment(control, _window.TextView, desiredSize), caretPos);
}
internal static IInteractiveWindowCommands GetInteractiveCommands(
IServiceProvider serviceProvider,
IInteractiveWindow window,
IInteractiveEvaluator eval
) {
var model = serviceProvider.GetComponentModel();
var cmdFactory = model.GetService<IInteractiveWindowCommandsFactory>();
var cmds = model.GetExtensions<IInteractiveWindowCommand>();
var roles = eval.GetType()
.GetCustomAttributes(typeof(InteractiveWindowRoleAttribute), true)
.Select(r => ((InteractiveWindowRoleAttribute)r).Name)
.ToArray();
var contentTypeRegistry = model.GetService<IContentTypeRegistryService>();
var contentTypes = eval.GetType()
.GetCustomAttributes(typeof(ContentTypeAttribute), true)
.Select(r => contentTypeRegistry.GetContentType(((ContentTypeAttribute)r).ContentTypes))
.ToArray();
return cmdFactory.CreateInteractiveCommands(
window,
"$",
cmds.Where(x => IsCommandApplicable(x, roles, contentTypes))
);
}
private static bool IsCommandApplicable(
IInteractiveWindowCommand command,
string[] supportedRoles,
IContentType[] supportedContentTypes
) {
var commandRoles = command.GetType().GetCustomAttributes(typeof(InteractiveWindowRoleAttribute), true).Select(r => ((InteractiveWindowRoleAttribute)r).Name).ToArray();
// Commands with no roles are always applicable.
// If a command specifies roles and none apply, exclude it
if (commandRoles.Any() && !commandRoles.Intersect(supportedRoles).Any()) {
return false;
}
var commandContentTypes = command.GetType()
.GetCustomAttributes(typeof(ContentTypeAttribute), true)
.Select(a => ((ContentTypeAttribute)a).ContentTypes)
.ToArray();
// Commands with no content type are always applicable
// If a commands specifies content types and none apply, exclude it
if (commandContentTypes.Any() && !commandContentTypes.Any(cct => supportedContentTypes.Any(sct => sct.IsOfType(cct)))) {
return false;
}
return true;
}
#region Append Text helpers
private static void AppendTextWithEscapes(
IInteractiveWindow window,
string text,
bool addNewLine,
bool isError
) {
int start = 0, escape = text.IndexOfOrdinal("\x1b[");
var colors = window.OutputBuffer.Properties.GetOrCreateSingletonProperty(
ReplOutputClassifier.ColorKey,
() => new List<ColoredSpan>()
);
ConsoleColor? color = null;
Span span;
var write = isError ? (Func<string, Span>)window.WriteError : window.Write;
int lastEscape = -1;
while (escape > lastEscape) {
lastEscape = escape;
span = write(text.Substring(start, escape - start));
if (span.Length > 0) {
colors.Add(new ColoredSpan(span, color));
}
start = escape + 2;
color = GetColorFromEscape(text, ref start);
Debug.Assert(start >= escape + 2);
escape = text.IndexOfOrdinal("\x1b[", start);
Debug.Assert(escape < 0 || escape > lastEscape);
}
var rest = text.Substring(start);
if (addNewLine) {
rest += Environment.NewLine;
}
span = write(rest);
if (span.Length > 0) {
colors.Add(new ColoredSpan(span, color));
}
}
private static ConsoleColor Change(ConsoleColor? from, ConsoleColor to) {
return ((from ?? ConsoleColor.Black) & ConsoleColor.DarkGray) | to;
}
private static ConsoleColor? GetColorFromEscape(string text, ref int start) {
// http://en.wikipedia.org/wiki/ANSI_escape_code
// process any ansi color sequences...
ConsoleColor? color = null;
List<int> codes = new List<int>();
int? value = 0;
while (start < text.Length) {
if (text[start] >= '0' && text[start] <= '9') {
// continue parsing the integer...
if (value == null) {
value = 0;
}
value = 10 * value.Value + (text[start] - '0');
} else if (text[start] == ';') {
if (value != null) {
codes.Add(value.Value);
value = null;
} else {
// CSI ; - invalid or CSI ### ;;, both invalid
break;
}
} else if (text[start] == 'm') {
start += 1;
if (value != null) {
codes.Add(value.Value);
}
// parsed a valid code
if (codes.Count == 0) {
// reset
color = null;
} else {
for (int j = 0; j < codes.Count; j++) {
switch (codes[j]) {
case 0: color = ConsoleColor.White; break;
case 1: // bright/bold
color |= ConsoleColor.DarkGray;
break;
case 2: // faint
case 3: // italic
case 4: // single underline
break;
case 5: // blink slow
case 6: // blink fast
break;
case 7: // negative
case 8: // conceal
case 9: // crossed out
case 10: // primary font
case 11: // 11-19, n-th alternate font
break;
case 21: // bright/bold off
color &= ~ConsoleColor.DarkGray;
break;
case 22: // normal intensity
case 24: // underline off
break;
case 25: // blink off
break;
case 27: // image - postive
case 28: // reveal
case 29: // not crossed out
case 30: color = Change(color, ConsoleColor.Black); break;
case 31: color = Change(color, ConsoleColor.DarkRed); break;
case 32: color = Change(color, ConsoleColor.DarkGreen); break;
case 33: color = Change(color, ConsoleColor.DarkYellow); break;
case 34: color = Change(color, ConsoleColor.DarkBlue); break;
case 35: color = Change(color, ConsoleColor.DarkMagenta); break;
case 36: color = Change(color, ConsoleColor.DarkCyan); break;
case 37: color = Change(color, ConsoleColor.Gray); break;
case 38: // xterm 286 background color
case 39: // default text color
color = null;
break;
case 40: // background colors
case 41:
case 42:
case 43:
case 44:
case 45:
case 46:
case 47: break;
case 90: color = ConsoleColor.DarkGray; break;
case 91: color = ConsoleColor.Red; break;
case 92: color = ConsoleColor.Green; break;
case 93: color = ConsoleColor.Yellow; break;
case 94: color = ConsoleColor.Blue; break;
case 95: color = ConsoleColor.Magenta; break;
case 96: color = ConsoleColor.Cyan; break;
case 97: color = ConsoleColor.White; break;
}
}
}
break;
} else {
// unknown char, invalid escape
break;
}
start += 1;
}
return color;
}
#endregion
}
internal static class PythonCommonInteractiveEvaluatorExtensions {
public static PythonCommonInteractiveEvaluator GetPythonEvaluator(this IInteractiveWindow window) {
var pie = window?.Evaluator as PythonCommonInteractiveEvaluator;
if (pie != null) {
return pie;
}
pie = (window?.Evaluator as SelectableReplEvaluator)?.Evaluator as PythonCommonInteractiveEvaluator;
return pie;
}
public static async Task<bool> GetSupportsMultipleStatements(this IInteractiveWindow window) {
var pie = window.GetPythonEvaluator();
if (pie == null) {
return false;
}
return await pie.GetSupportsMultipleStatementsAsync();
}
}
}
| 41.993624 | 179 | 0.559141 | [
"Apache-2.0"
] | Bhaskers-Blu-Org2/PTVS | Python/Product/PythonTools/PythonTools/Repl/PythonCommonInteractiveEvaluator.cs | 39,518 | C# |
using FFMpegCore.Exceptions;
using Instances;
namespace FFMpegCore.Helpers
{
public class FFProbeHelper
{
private static bool _ffprobeVerified;
public static int Gcd(int first, int second)
{
while (first != 0 && second != 0)
{
if (first > second)
first -= second;
else second -= first;
}
return first == 0 ? second : first;
}
public static void RootExceptionCheck()
{
if (GlobalFFOptions.Current.BinaryFolder == null)
throw new FFOptionsException("FFProbe root is not configured in app config. Missing key 'BinaryFolder'.");
}
public static void VerifyFFProbeExists(FFOptions ffMpegOptions)
{
if (_ffprobeVerified) return;
var (exitCode, _) = Instance.Finish(GlobalFFOptions.GetFFProbeBinaryPath(ffMpegOptions), "-version");
_ffprobeVerified = exitCode == 0;
if (!_ffprobeVerified)
throw new FFProbeException("ffprobe was not found on your system");
}
}
}
| 31.189189 | 122 | 0.567591 | [
"MIT"
] | AreebaAroosh/FFMpegCore | FFMpegCore/Helpers/FFProbeHelper.cs | 1,156 | C# |
using System;
using System.Diagnostics;
using Loupe.Extensibility.Data;
namespace Gibraltar.Monitor
{
/// <summary>
/// A single display-ready metric value.
/// </summary>
/// <remarks>
/// This is the complementary object to a Metric Sample. A Sample is a raw value that may require multiple
/// samples to determine a display ready value.
/// </remarks>
[DebuggerDisplay("{Sequence}: {Timestamp} Value={Value}")]
public class MetricValue : IMetricValue
{
private readonly long m_Sequence;
private readonly MetricValueCollection m_MetricValueCollection;
private readonly double m_Value;
private readonly DateTimeOffset m_TimeStamp;
/// <summary>Create a new metric value for the specified metric value set.</summary>
/// <remarks>The new metric value is automatically added to the provided metric value set.</remarks>
/// <param name="metricValueCollection">The metric value set this value is part of.</param>
/// <param name="timeStamp">The unique date and time of this value sample.</param>
/// <param name="value">The calculated value.</param>
public MetricValue(MetricValueCollection metricValueCollection, DateTimeOffset timeStamp, double value)
{
m_MetricValueCollection = metricValueCollection;
m_TimeStamp = timeStamp;
m_Value = value;
//get the unique sequence number from the metric
m_Sequence = metricValueCollection.GetSampleSequence();
//and add ourself to the metric value set
m_MetricValueCollection.Add(this);
}
#region Public Properties and Methods
/// <summary>
/// The metric value set this value is part of.
/// </summary>
public IMetricValueCollection ValueCollection { get { return m_MetricValueCollection; } }
/// <summary>
/// The exact date and time the metric was captured.
/// </summary>
public virtual DateTimeOffset Timestamp
{
get
{
return m_TimeStamp;
}
}
/// <summary>
/// The date and time the metric was captured in the effective time zone.
/// </summary>
public DateTime LocalTimestamp
{
get { return Timestamp.DateTime; }
}
/// <summary>
/// The value of the metric.
/// </summary>
public double Value { get { return m_Value; } }
/// <summary>
/// The value of the metric multiplied by 100 to handle raw percentage display
/// </summary>
/// <remarks>This value is scaled by 100 even if the underlying metric is not a percentage</remarks>
public double PercentageValue { get { return m_Value * 100; } }
/// <summary>
/// The increasing sequence number of all sample packets for this metric to be used as an absolute order sort.
/// </summary>
public long Sequence { get { return m_Sequence; } }
/// <summary>
/// Compare this metric value to another for the purpose of sorting them in time.
/// </summary>
/// <remarks>MetricValue instances are sorted by their Sequence number property.</remarks>
/// <param name="other">The MetricValue object to compare this object to.</param>
/// <returns>An int which is less than zero, equal to zero, or greater than zero to reflect whether
/// this MetricValue should sort as being less-than, equal to, or greater-than the other
/// MetricValue, respectively.</returns>
public int CompareTo(IMetricValue other)
{
//we are all about the sequence number baby!
return m_Sequence.CompareTo(other.Sequence);
}
/// <summary>
/// Determines if the provided MetricValue object is identical to this object.
/// </summary>
/// <param name="other">The MetricValue object to compare this object to.</param>
/// <returns>True if the Metric Value objects represent the same data.</returns>
public bool Equals(IMetricValue other)
{
// Careful, it could be null; check it without recursion
if (object.ReferenceEquals(other, null))
{
return false; // Since we're a live object we can't be equal to a null instance.
}
//they are equal if they have the same sequence and value
return ((Value == other.Value) && (Sequence == other.Sequence));
}
/// <summary>
/// Determines if the provided object is identical to this object.
/// </summary>
/// <param name="obj">The object to compare this object to</param>
/// <returns>True if the other object is also a MetricValue and represents the same data.</returns>
public override bool Equals(object obj)
{
MetricValue otherMetricValue = obj as MetricValue;
return Equals(otherMetricValue); // Just have type-specific Equals do the check (it even handles null)
}
/// <summary>
/// Provides a representative hash code for objects of this type to spread out distribution
/// in hash tables.
/// </summary>
/// <remarks>Objects which consider themselves to be Equal (a.Equals(b) returns true) are
/// expected to have the same hash code. Objects which are not Equal may have the same
/// hash code, but minimizing such overlaps helps with efficient operation of hash tables.
/// </remarks>
/// <returns>
/// An int representing the hash code calculated for the contents of this object.
/// </returns>
public override int GetHashCode()
{
int myHash = (int) (m_Sequence >> 32) ^ (int) m_Sequence; // Fold long Sequence number down to an int
myHash ^= m_Value.GetHashCode(); // Fold in hash code for double field Value
return myHash;
}
#endregion
#region Static Public Methods and Operators
/// <summary>
/// Compares two MetricValue instances for equality.
/// </summary>
/// <param name="left">The MetricValue to the left of the operator</param>
/// <param name="right">The MetricValue to the right of the operator</param>
/// <returns>True if the two MetricValues are equal.</returns>
public static bool operator ==(MetricValue left, MetricValue right)
{
// We have to check if left is null (right can be checked by Equals itself)
if (object.ReferenceEquals(left, null))
{
// If right is also null, we're equal; otherwise, we're unequal!
return object.ReferenceEquals(right, null);
}
return left.Equals(right);
}
/// <summary>
/// Compares two MetricValue instances for inequality.
/// </summary>
/// <param name="left">The MetricValue to the left of the operator</param>
/// <param name="right">The MetricValue to the right of the operator</param>
/// <returns>True if the two MetricValues are not equal.</returns>
public static bool operator !=(MetricValue left, MetricValue right)
{
// We have to check if left is null (right can be checked by Equals itself)
if (object.ReferenceEquals(left, null))
{
// If right is also null, we're equal; otherwise, we're unequal!
return ! object.ReferenceEquals(right, null);
}
return ! left.Equals(right);
}
/// <summary>
/// Compares if one MetricValue instance should sort less than another.
/// </summary>
/// <param name="left">The MetricValue to the left of the operator</param>
/// <param name="right">The MetricValue to the right of the operator</param>
/// <returns>True if the MetricValue to the left should sort less than the MetricValue to the right.</returns>
public static bool operator <(MetricValue left, MetricValue right)
{
return (left.CompareTo(right) < 0);
}
/// <summary>
/// Compares if one MetricValue instance should sort greater than another.
/// </summary>
/// <param name="left">The MetricValue to the left of the operator</param>
/// <param name="right">The MetricValue to the right of the operator</param>
/// <returns>True if the MetricValue to the left should sort greater than the MetricValue to the right.</returns>
public static bool operator >(MetricValue left, MetricValue right)
{
return (left.CompareTo(right) > 0);
}
#endregion
}
}
| 42.721154 | 121 | 0.610849 | [
"MIT"
] | GibraltarSoftware/Loupe.Agent.Core | src/Core/Monitor/MetricValue.cs | 8,888 | C# |
namespace SpecFlow.TestProjectGenerator.Inputs
{
public class CodeFileInput : FileInputWithContent
{
public CodeFileInput(string fileName, string folder, string content) : base(fileName, content, folder)
{
}
}
} | 27.555556 | 110 | 0.685484 | [
"Apache-2.0",
"MIT"
] | ImanMesgaran/SpecFlow | SpecFlow.TestGenerator/SpecFlow.TestProjectGenerator/Inputs/CodeFileInput.cs | 250 | C# |
// Copyright 2010 Chris Patterson
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
namespace Stact
{
public delegate TOutput MessageConverter<TInput, TOutput>(TInput message);
} | 44.4375 | 84 | 0.731364 | [
"Apache-2.0"
] | Nangal/Stact | src/Stact/Channels/MessageConverter.cs | 713 | C# |
// Copyright 2019 Florian Gather <florian.gather@tngtech.com>
// Copyright 2019 Paula Ruiz <paularuiz22@gmail.com>
// Copyright 2019 Fritz Brandhuber <fritz.brandhuber@tngtech.com>
//
// SPDX-License-Identifier: Apache-2.0
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using ArchUnitNET.Domain;
using ArchUnitNET.Domain.Extensions;
using Mono.Cecil;
using static System.IO.SearchOption;
using Assembly = System.Reflection.Assembly;
namespace ArchUnitNET.Loader
{
public class ArchLoader
{
private readonly ArchBuilder _archBuilder = new ArchBuilder();
private DotNetCoreAssemblyResolver _assemblyResolver = new DotNetCoreAssemblyResolver();
public Architecture Build()
{
var architecture = _archBuilder.Build();
_assemblyResolver.Dispose();
_assemblyResolver = new DotNetCoreAssemblyResolver();
return architecture;
}
public ArchLoader LoadAssemblies(params Assembly[] assemblies)
{
var assemblySet = new HashSet<Assembly>(assemblies);
assemblySet.ForEach(assembly => LoadAssembly(assembly));
return this;
}
public ArchLoader LoadAssembliesIncludingDependencies(params Assembly[] assemblies)
{
var assemblySet = new HashSet<Assembly>(assemblies);
assemblySet.ForEach(assembly => LoadAssemblyIncludingDependencies(assembly));
return this;
}
public ArchLoader LoadFilteredDirectory(string directory, string filter,
SearchOption searchOption = TopDirectoryOnly)
{
var path = Path.GetFullPath(directory);
_assemblyResolver.AssemblyPath = path;
var assemblies = Directory.GetFiles(path, filter, searchOption);
var result = this;
return assemblies.Aggregate(result,
(current, assembly) => current.LoadAssembly(assembly, false));
}
public ArchLoader LoadFilteredDirectoryIncludingDependencies(string directory, string filter,
SearchOption searchOption = TopDirectoryOnly)
{
var path = Path.GetFullPath(directory);
_assemblyResolver.AssemblyPath = path;
var assemblies = Directory.GetFiles(path, filter, searchOption);
var result = this;
return assemblies.Aggregate(result,
(current, assembly) => current.LoadAssembly(assembly, true));
}
public ArchLoader LoadNamespacesWithinAssembly(Assembly assembly, params string[] namespc)
{
var nameSpaces = new HashSet<string>(namespc);
nameSpaces.ForEach(nameSpace => { LoadModule(assembly.Location, nameSpace, false); });
return this;
}
public ArchLoader LoadAssembly(Assembly assembly)
{
return LoadAssembly(assembly.Location, false);
}
public ArchLoader LoadAssemblyIncludingDependencies(Assembly assembly)
{
return LoadAssembly(assembly.Location, true);
}
private ArchLoader LoadAssembly(string fileName, bool includeDependencies)
{
LoadModule(fileName, null, includeDependencies);
return this;
}
private void LoadModule(string fileName, string nameSpace, bool includeDependencies)
{
try
{
var module = ModuleDefinition.ReadModule(fileName,
new ReaderParameters {AssemblyResolver = _assemblyResolver});
_assemblyResolver.AddLib(module.Assembly);
_archBuilder.AddAssembly(module.Assembly, false);
foreach (var assemblyReference in module.AssemblyReferences)
{
try
{
_assemblyResolver.AddLib(assemblyReference);
if (includeDependencies)
{
_archBuilder.AddAssembly(
_assemblyResolver.Resolve(assemblyReference) ??
throw new AssemblyResolutionException(assemblyReference), false);
}
}
catch (AssemblyResolutionException)
{
//Failed to resolve assembly, skip it
}
}
_archBuilder.LoadTypesForModule(module, nameSpace);
if (includeDependencies)
{
foreach (var moduleDefinition in module.AssemblyReferences.SelectMany(reference =>
_assemblyResolver.Resolve(reference)?.Modules))
{
_archBuilder.LoadTypesForModule(moduleDefinition, null);
}
}
}
catch (BadImageFormatException)
{
// invalid file format of DLL or executable, therefore ignored
}
}
}
} | 37.189781 | 102 | 0.595289 | [
"Apache-2.0"
] | DialLuesebrink/ArchUnitNET | ArchUnitNET/Loader/ArchLoader.cs | 5,097 | C# |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the ec2-2016-11-15.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using System.Net;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.EC2.Model
{
/// <summary>
/// This is the response object from the RevokeClientVpnIngress operation.
/// </summary>
public partial class RevokeClientVpnIngressResponse : AmazonWebServiceResponse
{
private ClientVpnAuthorizationRuleStatus _status;
/// <summary>
/// Gets and sets the property Status.
/// <para>
/// The current state of the authorization rule.
/// </para>
/// </summary>
public ClientVpnAuthorizationRuleStatus Status
{
get { return this._status; }
set { this._status = value; }
}
// Check to see if Status property is set
internal bool IsSetStatus()
{
return this._status != null;
}
}
} | 29.350877 | 101 | 0.665272 | [
"Apache-2.0"
] | ChristopherButtars/aws-sdk-net | sdk/src/Services/EC2/Generated/Model/RevokeClientVpnIngressResponse.cs | 1,673 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConnectFour.InputOutput
{
public class Output : IOutputSender
{
/// <summary>
/// Returns what is sent, adds a new line to msg
/// </summary>
public string Send(string msg, bool newline)
{
if (newline)
{
Console.WriteLine(msg);
}
else
{
Console.Write(msg);
}
return msg;
}
}
}
| 20.75 | 56 | 0.509466 | [
"MIT"
] | PurplePenguin4102/ConnectFour | ConnectFour/ConnectFour/InputOutput/Output.cs | 583 | C# |
using Castle.DynamicProxy;
using Ninject;
using Ninject.Activation;
using Ninject.Extensions.Interception.Request;
using Ninject.Extensions.Interception.Wrapper;
namespace ServiceBridge.Ninject.Interception
{
/// <summary>
/// Defines an interception wrapper that can convert a Castle DynamicProxy2 <see cref="IInvocation" />
/// into a Ninject <see cref="IRequest" /> for interception.
/// </summary>
internal class DynamicProxyWrapper : StandardWrapper, IInterceptor
{
/// <summary>
/// Initializes a new instance of the <see cref="DynamicProxyWrapper" /> class.
/// </summary>
/// <param name="kernel">The kernel associated with the wrapper.</param>
/// <param name="context">The context in which the instance was activated.</param>
/// <param name="instance">The wrapped instance.</param>
public DynamicProxyWrapper(IKernel kernel, IContext context, object instance)
: base(kernel, context, instance)
{
}
/// <summary>
/// Intercepts the specified invocation.
/// </summary>
/// <param name="castleInvocation">The invocation.</param>
/// <returns>The return value of the invocation, once it is completed.</returns>
public void Intercept(IInvocation castleInvocation)
{
var request = CreateRequest(castleInvocation);
var invocation = CreateInvocation(request);
invocation.Proceed();
castleInvocation.ReturnValue = invocation.ReturnValue;
}
private IProxyRequest CreateRequest(IInvocation castleInvocation)
{
var requestFactory = Context.Kernel.Components.Get<IProxyRequestFactory>();
return requestFactory.Create(
Context,
castleInvocation.Proxy,
Instance,
castleInvocation.GetConcreteMethod(),
castleInvocation.Arguments,
castleInvocation.GenericArguments);
}
}
}
| 39.092593 | 111 | 0.617717 | [
"MIT"
] | edwardmeng/ServiceBridge | src/Ninject/ServiceBridge.Ninject.Interception/DynamicProxyWrapper.cs | 2,113 | C# |
using System;
using System.Globalization;
using NUnit.Framework;
namespace SimpleJSON.Test
{
[TestFixture]
public class TestToString
{
[Test]
public void ToString_SimpleObject_NullSuccess()
{
// arrange
const string expected = @"
{
""value"": null
}";
var node = JSON.Parse(expected);
// act
var actual = node.ToString();
// assert
Assert.IsTrue(String.Compare(expected, actual, CultureInfo.CurrentCulture, CompareOptions.IgnoreSymbols) ==
0);
}
[Test]
public void ToString_SimpleObject_IntegerSuccess()
{
// arrange
const string expected = @"
{
""value"": 1
}";
var node = JSON.Parse(expected);
// act
var actual = node.ToString();
// assert
Assert.IsTrue(String.Compare(expected, actual, CultureInfo.CurrentCulture, CompareOptions.IgnoreSymbols) ==
0);
}
[Test]
public void ToString_SimpleObject_DoubleSuccess()
{
// arrange
const string expected = @"
{
""value"": 1.5
}";
var node = JSON.Parse(expected);
// act
var actual = node.ToString();
// assert
Assert.IsTrue(String.Compare(expected, actual, CultureInfo.CurrentCulture, CompareOptions.IgnoreSymbols) ==
0);
}
[Test]
public void ToString_SimpleObject_StringSuccess()
{
// arrange
const string expected = @"
{
""value"": ""String""
}";
var node = JSON.Parse(expected);
// act
var actual = node.ToString();
// assert
Assert.IsTrue(String.Compare(expected, actual, CultureInfo.CurrentCulture, CompareOptions.IgnoreSymbols) ==
0);
}
[Test]
public void ToString_SimpleObject_LongSuccess()
{
// arrange
const string expected = @"
{
""value"": 12345678900000,
""value2"": 12345678900001
}";
var node = JSON.Parse(expected);
// act
var actual = node.ToString();
// assert
Assert.IsTrue(String.Compare(expected, actual, CultureInfo.CurrentCulture, CompareOptions.IgnoreSymbols) ==
0);
}
[Test]
public void ToString_SimpleObject_BoolSuccess()
{
// arrange
const string expected = @"
{
""value"": true,
""value2"": false
}";
var node = JSON.Parse(expected);
// act
var actual = node.ToString();
// assert
Assert.IsTrue(String.Compare(expected, actual, CultureInfo.CurrentCulture, CompareOptions.IgnoreSymbols) ==
0);
}
[Test]
public void ToString_SimpleObject_ObjectSuccess()
{
// arrange
const string expected = @"
{
""value"": {},
""value2"": {
""array"": [],
""integer"": 1,
""float"": 1.5,
""string "": ""string"",
""boolean"": false
}
}";
var node = JSON.Parse(expected);
// act
var actual = node.ToString();
// assert
Assert.IsTrue(String.Compare(expected, actual, CultureInfo.CurrentCulture, CompareOptions.IgnoreSymbols) ==
0);
}
[Test]
public void ToString_SimpleObject_ArraySuccess()
{
// arrange
const string expected = @"
{
""value"": [],
""value2"": [1, 1.5, ""string"", false, null, {}]
}";
var node = JSON.Parse(expected);
// act
var actual = node.ToString();
// assert
Assert.IsTrue(String.Compare(expected, actual, CultureInfo.CurrentCulture, CompareOptions.IgnoreSymbols) ==
0);
}
[Test]
public void ToStringFormatted_SimpleObject_NullSuccess()
{
// arrange
const string expected = @"
{
""value"": null
}";
var node = JSON.Parse(expected);
// act
var actual = node.ToString("");
// assert
Assert.IsTrue(String.Compare(expected, actual, CultureInfo.CurrentCulture, CompareOptions.IgnoreSymbols) ==
0);
}
[Test]
public void ToStringFormatted_SimpleObject_IntegerSuccess()
{
// arrange
const string expected = @"
{
""value"": 1
}";
var node = JSON.Parse(expected);
// act
var actual = node.ToString("");
// assert
Assert.IsTrue(String.Compare(expected, actual, CultureInfo.CurrentCulture, CompareOptions.IgnoreSymbols) ==
0);
}
[Test]
public void ToStringFormatted_SimpleObject_DoubleSuccess()
{
// arrange
const string expected = @"
{
""value"": 1.5
}";
var node = JSON.Parse(expected);
// act
var actual = node.ToString("");
// assert
Assert.IsTrue(String.Compare(expected, actual, CultureInfo.CurrentCulture, CompareOptions.IgnoreSymbols) ==
0);
}
[Test]
public void ToStringFormatted_SimpleObject_StringSuccess()
{
// arrange
const string expected = @"
{
""value"": ""String""
}";
var node = JSON.Parse(expected);
// act
var actual = node.ToString("");
// assert
Assert.IsTrue(String.Compare(expected, actual, CultureInfo.CurrentCulture, CompareOptions.IgnoreSymbols) ==
0);
}
[Test]
public void ToStringFormatted_SimpleObject_LongSuccess()
{
// arrange
const string expected = @"
{
""value"": 12345678900000,
""value2"": 12345678900001
}";
var node = JSON.Parse(expected);
// act
var actual = node.ToString("");
// assert
Assert.IsTrue(String.Compare(expected, actual, CultureInfo.CurrentCulture, CompareOptions.IgnoreSymbols) ==
0);
}
[Test]
public void ToStringFormatted_SimpleObject_BoolSuccess()
{
// arrange
const string expected = @"
{
""value"": true,
""value2"": false
}";
var node = JSON.Parse(expected);
// act
var actual = node.ToString("");
// assert
Assert.IsTrue(String.Compare(expected, actual, CultureInfo.CurrentCulture, CompareOptions.IgnoreSymbols) ==
0);
}
[Test]
public void ToStringToStringFormatted_SimpleObject_ObjectSuccess()
{
// arrange
const string expected = @"
{
""value"": {},
""value2"": {
""array"": [],
""integer"": 1,
""float"": 1.5,
""string "": ""string"",
""boolean"": false
}
}";
var node = JSON.Parse(expected);
// act
var actual = node.ToString("");
// assert
Assert.IsTrue(String.Compare(expected, actual, CultureInfo.CurrentCulture, CompareOptions.IgnoreSymbols) ==
0);
}
[Test]
public void ToStringFormatted_SimpleObject_ArraySuccess()
{
// arrange
const string expected = @"
{
""value"": [],
""value2"": [1, 1.5, ""string"", false, null, {}]
}";
var node = JSON.Parse(expected);
// act
var actual = node.ToString("");
// assert
Assert.IsTrue(String.Compare(expected, actual, CultureInfo.CurrentCulture, CompareOptions.IgnoreSymbols) ==
0);
}
}
} | 28.286164 | 119 | 0.45214 | [
"MIT"
] | DragonSpawn/SimpleJSON | Editor/TestToString.cs | 8,997 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Windows.Forms;
using System.Drawing;
namespace IA_File_Change_v1._0
{
public class WorkCodes
{
#region Dosya İşlemi 1
public void DosyaBilgiAl(int Deger1, int Deger2, FileInfo[] FI1, string Path, ComboBox CB1,Label Lbl1,Boolean Durum)
{
for (; Deger1 < FI1.Length; Deger1++)
{
if (Durum == false)
{
FileMove(Deger1, Deger2, FI1, Path, CB1, Durum);
Deger2++;
}
else if (Durum == true)
{
FileMove(Deger1, Deger2, FI1, Path, CB1, Durum);
Deger2++;
}
}
Lbl1.Text = "İşlem Tamamlandı";
}
public void FileMove(int Deger1, int Deger2, FileInfo[] FI1, string Path,ComboBox CB1,bool Durum)
{
try
{
if (Durum==false)
{
Directory.Move(FI1[Deger1].FullName, Path + "\\" + Deger2 + "." + CB1.Text);
}
else
{
string[] z = FI1[Deger1].Name.Split('.');
Directory.Move(FI1[Deger1].FullName, Path + "\\" + Deger2 + " " + z[0] + "." + CB1.Text);
}
}
catch (Exception)
{
Deger2++;
FileMove(Deger1, Deger2, FI1, Path, CB1,Durum);
}
}
#endregion
#region Renk
public void PicHover(PictureBox Pic1)
{
Pic1.BackColor = Color.White;
}
public void PicLeave(PictureBox Pic2)
{
Pic2.BackColor = Color.Transparent;
}
public void PicClick(PictureBox Pic3)
{
Pic3.BackColor = Color.RoyalBlue;
}
#endregion
}
}
| 25.13253 | 124 | 0.438159 | [
"Apache-2.0"
] | MuratBilginerSoft/IA-File-Change-v.1.0 | IA File Change v1.0/WorkCodes.cs | 2,093 | C# |
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
using Xunit;
namespace Microsoft.Alm.Cli.Test
{
public class OperationArgumentsTests
{
[Fact]
public void Typical()
{
const string input = "protocol=https\n"
+ "host=example.visualstudio.com\n"
+ "path=path\n"
+ "username=userName\n"
+ "password=incorrect\n";
OperationArguments cut;
using (var memory = new MemoryStream())
using (var writer = new StreamWriter(memory))
{
writer.Write(input);
writer.Flush();
memory.Seek(0, SeekOrigin.Begin);
cut = new OperationArguments.Impl(memory);
}
Assert.Equal("https", cut.QueryProtocol);
Assert.Equal("example.visualstudio.com", cut.QueryHost);
Assert.Equal("https://example.visualstudio.com/", cut.TargetUri.ToString());
Assert.Equal("path", cut.QueryPath);
Assert.Equal("userName", cut.CredUsername);
Assert.Equal("incorrect", cut.CredPassword);
var expected = ReadLines(input);
var actual = ReadLines(cut.ToString());
Assert.Equal(expected, actual);
}
[Fact]
public void SpecialCharacters()
{
const string input = "protocol=https\n"
+ "host=example.visualstudio.com\n"
+ "path=path\n"
+ "username=userNamể\n"
+ "password=ḭncorrect\n";
OperationArguments cut;
using (var memory = new MemoryStream())
using (var writer = new StreamWriter(memory))
{
writer.Write(input);
writer.Flush();
memory.Seek(0, SeekOrigin.Begin);
cut = new OperationArguments.Impl(memory);
}
Assert.Equal("https", cut.QueryProtocol);
Assert.Equal("example.visualstudio.com", cut.QueryHost);
Assert.Equal("https://example.visualstudio.com/", cut.TargetUri.ToString());
Assert.Equal("path", cut.QueryPath);
Assert.Equal("userNamể", cut.CredUsername);
Assert.Equal("ḭncorrect", cut.CredPassword);
var expected = ReadLines(input);
var actual = ReadLines(cut.ToString());
Assert.Equal(expected, actual);
}
[Fact]
public void CreateTargetUriGitHubSimple()
{
var input = new InputArg()
{
Protocol = "https",
Host = "github.com",
};
CreateTargetUriTestDefault(input);
CreateTargetUriTestSansPath(input);
CreateTargetUriTestWithPath(input);
}
[Fact]
public void CreateTargetUri_VstsSimple()
{
var input = new InputArg()
{
Protocol = "https",
Host = "team.visualstudio.com",
};
CreateTargetUriTestDefault(input);
CreateTargetUriTestSansPath(input);
CreateTargetUriTestWithPath(input);
}
[Fact]
public void CreateTargetUriGitHubComplex()
{
var input = new InputArg()
{
Protocol = "https",
Host = "github.com",
Path = "Microsoft/Git-Credential-Manager-for-Windows.git"
};
CreateTargetUriTestDefault(input);
CreateTargetUriTestSansPath(input);
CreateTargetUriTestWithPath(input);
}
[Fact]
public void CreateTargetUriWithPortNumber()
{
var input = new InputArg()
{
Protocol = "https",
Host = "onpremis:8080",
};
CreateTargetUriTestDefault(input);
CreateTargetUriTestSansPath(input);
CreateTargetUriTestWithPath(input);
}
[Fact]
public void CreateTargetUriComplexAndMessy()
{
var input = new InputArg()
{
Protocol = "https",
Host = "foo.bar.com:8181",
Path = "this-is/a/path%20with%20spaces",
};
CreateTargetUriTestDefault(input);
CreateTargetUriTestSansPath(input);
CreateTargetUriTestWithPath(input);
}
[Fact]
public void CreateTargetUriWithCredentials()
{
var input = new InputArg()
{
Protocol = "http",
Host = "insecure.com",
Username = "naive",
Password = "password",
};
CreateTargetUriTestDefault(input);
CreateTargetUriTestSansPath(input);
CreateTargetUriTestWithPath(input);
}
[Fact]
public void CreateTargetUriUnc()
{
var input = new InputArg()
{
Protocol = "file",
Host = "unc",
Path = "server/path",
};
CreateTargetUriTestDefault(input);
CreateTargetUriTestSansPath(input);
CreateTargetUriTestWithPath(input);
}
[Fact]
public void CreateTargetUriUncColloquial()
{
var input = new InputArg()
{
Host = @"\\windows\has\weird\paths",
};
CreateTargetUriTestDefault(input);
CreateTargetUriTestSansPath(input);
CreateTargetUriTestWithPath(input);
}
private void CreateTargetUriTestDefault(InputArg input)
{
using (var memory = new MemoryStream())
using (var writer = new StreamWriter(memory))
{
writer.Write(input.ToString());
writer.Flush();
memory.Seek(0, SeekOrigin.Begin);
var oparg = new OperationArguments.Impl(memory);
Assert.NotNull(oparg);
Assert.Equal(input.Protocol ?? string.Empty, oparg.QueryProtocol);
Assert.Equal(input.Host ?? string.Empty, oparg.QueryHost);
Assert.Equal(input.Path, oparg.QueryPath);
Assert.Equal(input.Username, oparg.CredUsername);
Assert.Equal(input.Password, oparg.CredPassword);
// file or unc paths are treated specially
if (oparg.QueryUri.Scheme != System.Uri.UriSchemeFile)
{
Assert.Equal("/", oparg.QueryUri.AbsolutePath);
}
}
}
private void CreateTargetUriTestSansPath(InputArg input)
{
using (var memory = new MemoryStream())
using (var writer = new StreamWriter(memory))
{
writer.Write(input.ToString());
writer.Flush();
memory.Seek(0, SeekOrigin.Begin);
var oparg = new OperationArguments.Impl(memory);
oparg.UseHttpPath = false;
Assert.NotNull(oparg);
Assert.Equal(input.Protocol ?? string.Empty, oparg.QueryProtocol);
Assert.Equal(input.Host ?? string.Empty, oparg.QueryHost);
Assert.Equal(input.Path, oparg.QueryPath);
Assert.Equal(input.Username, oparg.CredUsername);
Assert.Equal(input.Password, oparg.CredPassword);
// file or unc paths are treated specially
if (oparg.QueryUri.Scheme != System.Uri.UriSchemeFile)
{
Assert.Equal("/", oparg.QueryUri.AbsolutePath);
}
}
}
private void CreateTargetUriTestWithPath(InputArg input)
{
using (var memory = new MemoryStream())
using (var writer = new StreamWriter(memory))
{
writer.Write(input.ToString());
writer.Flush();
memory.Seek(0, SeekOrigin.Begin);
var oparg = new OperationArguments.Impl(memory);
oparg.UseHttpPath = true;
Assert.NotNull(oparg);
Assert.Equal(input.Protocol ?? string.Empty, oparg.QueryProtocol);
Assert.Equal(input.Host ?? string.Empty, oparg.QueryHost);
Assert.Equal(input.Path, oparg.QueryPath);
Assert.Equal(input.Username, oparg.CredUsername);
Assert.Equal(input.Password, oparg.CredPassword);
// file or unc paths are treated specially
if (oparg.QueryUri.Scheme != System.Uri.UriSchemeFile)
{
Assert.Equal("/" + input.Path, oparg.QueryUri.AbsolutePath);
}
}
}
private static ICollection ReadLines(string input)
{
var result = new List<string>();
using (var sr = new StringReader(input))
{
string line;
while ((line = sr.ReadLine()) != null)
{
result.Add(line);
}
}
return result;
}
private struct InputArg
{
public string Protocol;
public string Host;
public string Path;
public string Username;
public string Password;
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.Append("protocol=").Append(Protocol).Append("\n");
sb.Append("host=").Append(Host).Append("\n");
if (Path != null)
{
sb.Append("path=").Append(Path).Append("\n");
}
if (Username != null)
{
sb.Append("username=").Append(Username).Append("\n");
}
if (Password != null)
{
sb.Append("password=").Append(Password).Append("\n");
}
sb.Append("\n");
return sb.ToString();
}
}
}
}
| 32.104294 | 88 | 0.499522 | [
"MIT"
] | Haacked/Git-Credential-Manager-for-Windows | Cli-CredentialHelper.Test/OperationArgumentsTests.cs | 10,476 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using DSC.Core;
namespace GGJ2020
{
public class Event_Skill : MonoBehaviour
{
#region Variable
#region Variable - Inspector
#pragma warning disable 0649
#pragma warning restore 0649
#endregion
#region Variable - Property
#endregion
#endregion
#region Base - Mono
#endregion
#region Events
public void ResetSkill()
{
Global_GameplayManager.playerSkill = 0;
}
#endregion
#region Helper
#endregion
}
} | 15.512195 | 51 | 0.602201 | [
"MIT"
] | DeStiCap/Dim-Mind | Global Game Jam 2020/Assets/MainAsset/Scripts/Events/Event_Skill.cs | 638 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
public class Inventory : MonoBehaviour
{
#region Singleton
public static Inventory instance;
void Awake(){
if(instance != null){
Debug.LogWarning("More than one instance of Inventory found");
return;
}
instance = this;
}
#endregion
public delegate void OnItemChange();
public OnItemChange onItemChangeCallBack;
[SerializeField]
int space = 8;
public List<Item> items = new List<Item>();
public InventoryUI inventoryUI;
InputController input;
public bool Add(Item item){
bool isAdded = inventoryUI.AddItemUI(item);
if(isAdded){
items.Add(item);
return true;
}
return false;
}
public void Remove(Item item){
items.Remove(item);
}
public bool ContainsItem(Item item){
foreach( Item i in items){
if (i==item){
return true;
}
}
return false;
}
public int CountItem(Item item){
int count = 0;
for(int i=0; i<inventoryUI.slots.Length; i++){
if(inventoryUI.slots[i].item == item){
count += inventoryUI.slots[i].stackNum;
}
}
return count;
}
}
| 19.581081 | 74 | 0.545204 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | ChaoTheChild/Mogwai | Assets/Scripts/Inventory/Inventory.cs | 1,451 | C# |
using LocalParks.Models;
using System.Threading.Tasks;
namespace LocalParks.Services
{
public interface IHomeService
{
Task<HomeViewModel> GetHomeModelAsync(string latitude, string longitude);
bool PostFeedBackAsync(ContactViewModel model);
}
} | 24.909091 | 81 | 0.748175 | [
"BSD-3-Clause"
] | OwenSteele/LocalParks | LocalParks/Services/IHomeService.cs | 276 | C# |
using Bueller.DA.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Bueller.DAL.Models
{
public class SubjectDto : BaseEntity
{
[ScaffoldColumn(false)]
public int SubjectId { get; set; }
[Required]
[DataType(DataType.Text)]
[StringLength(100, ErrorMessage = "Name cannot be longer than {1} characters")]
public string Name { get; set; }
[Required]
[DataType(DataType.Text)]
[StringLength(100, ErrorMessage = "Department cannot be longer than {1} characters")]
public string Department { get; set; }
//credits is part of class model
[Column(TypeName = "datetime2")]
public DateTime Created { get; set; }
[Column(TypeName = "datetime2")]
public DateTime Modified { get; set; }
}
}
| 28.485714 | 93 | 0.65998 | [
"MIT"
] | 1804-Apr-USFdotnet/Project-2-Bueller | Project2-Bueller/Bueller.DAL/Models/SubjectDto.cs | 999 | C# |
using System;
using System.Runtime.InteropServices;
namespace OpenTK.Graphics.OpenGL
{
// FIXME: Remove this when it's fixed
// This is here because there in the gl.xml
// one of the parameters for "glSampleMaskIndexedNV"
// is marked with a group named this, but this group is never referenced
// anywhere else in the file.
public enum SampleMaskNV
{ }
public static unsafe partial class GL
{
public static void ShaderSource(uint shader, string shaderText)
{
var shaderTextPtr = Marshal.StringToCoTaskMemAnsi(shaderText);
var length = shaderText.Length;
GL.ShaderSource(shader, 1, (byte**)&shaderTextPtr, length);
Marshal.FreeCoTaskMem(shaderTextPtr);
}
public static void GetShaderInfoLog(uint shader, out string info)
{
int length = default;
GL.GetShader(shader, ShaderParameterName.InfoLogLength, ref length);
if (length == 0)
{
info = string.Empty;
}
else
{
GL.GetShaderInfoLog(shader, length, ref length, out info);
}
}
/// <summary>
/// Create a stand-alone program from an array of null-terminated source code strings
/// </summary>
/// <param name="shaderType">Specifies the type of shader to create</param>
/// <param name="shaderText"></param>
/// <exception cref="ArgumentNullException"></exception>
public static void CreateShaderProgram(ShaderType shaderType, string shaderText)
{
var shaderTextPtr = Marshal.StringToCoTaskMemAnsi(shaderText);
GL.CreateShaderProgramv_(shaderType, 1, (byte**)&shaderTextPtr);
Marshal.FreeCoTaskMem(shaderTextPtr);
}
}
}
| 35.442308 | 93 | 0.614216 | [
"MIT"
] | asears/opentk | src/OpenTK.Graphics/OpenGL/GL.Manual.cs | 1,843 | C# |
using FlowScriptEngine;
using System;
using System.Globalization;
using System.Text.RegularExpressions;
namespace FlowScriptEngineSlimDX.TypeFormatters
{
public class Vector3Formatter : TypeFormatterBase
{
static Regex regex = new Regex("^X:(?<X>[0-9.-]+) +Y:(?<Y>[0-9.-]+) +Z:(?<Z>[0-9.-]+)$");
public override Type Type
{
get { return typeof(SharpDX.Vector3); }
}
public override bool Format(string str, out object value)
{
value = null;
var m = regex.Match(str);
if (m.Success)
{
if (float.TryParse(m.Groups["X"].Value, NumberStyles.Float, CultureInfo.InvariantCulture, out float x)
&& float.TryParse(m.Groups["Y"].Value, NumberStyles.Float, CultureInfo.InvariantCulture, out float y)
&& float.TryParse(m.Groups["Z"].Value, NumberStyles.Float, CultureInfo.InvariantCulture, out float z))
{
value = new SharpDX.Vector3(x, y, z);
return true;
}
}
return false;
}
public override string CorrentFormat
{
get { return "X:2.5 Y:2.2 Z:1.0"; }
}
}
}
| 30.902439 | 122 | 0.539858 | [
"Apache-2.0"
] | KHCmaster/PPD | Win/FlowScriptEngineSlimDX/TypeFormatters/Vector3Formatter.cs | 1,269 | C# |
// Copyright 2021 Maintainers of NUKE.
// Distributed under the MIT License.
// https://github.com/nuke-build/nuke/blob/master/LICENSE
using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using JetBrains.Annotations;
using Nuke.Common.Utilities;
namespace Nuke.Common.CI.Jenkins
{
/// <summary>
/// Interface according to the <a href="https://wiki.jenkins.io/display/JENKINS/Building+a+software+project">official website</a>.
/// </summary>
[PublicAPI]
[CI]
[ExcludeFromCodeCoverage]
public class Jenkins : Host, IBuildServer
{
public new static Jenkins Instance => Host.Instance as Jenkins;
internal static bool IsRunningJenkins => !Environment.GetEnvironmentVariable("JENKINS_HOME").IsNullOrEmpty();
internal Jenkins()
{
}
string IBuildServer.Branch => GitBranch ?? BranchName;
string IBuildServer.Commit => GitCommit;
/// <summary>
/// Name of the branch for which this Pipeline is executing, for example <em>master</em>.
/// </summary>
public string BranchName => EnvironmentInfo.GetVariable<string>("BRANCH_NAME");
/// <summary>
/// The current build display name, such as "#14".
/// </summary>
public string BuilDisplayName => EnvironmentInfo.GetVariable<string>("BUILD_DISPLAY_NAME");
/// <summary>
/// The current build number, such as "14".
/// </summary>
public int BuildNumber => EnvironmentInfo.GetVariable<int>("BUILD_NUMBER");
/// <summary>
/// The current build tag, such as "jenkins-nuke-14".
/// </summary>
public string BuildTag => EnvironmentInfo.GetVariable<string>("BUILD_TAG");
/// <summary>
/// An identifier corresponding to some kind of change request, such as a pull request number.
/// </summary>
public string ChangeId => EnvironmentInfo.GetVariable<string>("CHANGE_ID");
/// <summary>
/// The number of the executor this build is running on, Equals '0' for first executor.
/// </summary>
public int ExecutorNumber => EnvironmentInfo.GetVariable<int>("EXECUTOR_NUMBER");
/// <summary>
/// For Git-based projects, this variable contains the Git branch that was checked out for the build (normally origin/master) (all the Git* properties require git plugin).
/// </summary>
public string GitBranch => EnvironmentInfo.GetVariable<string>("GIT_BRANCH");
/// <summary>
/// For Git-based projects, this variable contains the Git hash of the commit checked out for the build (like ce9a3c1404e8c91be604088670e93434c4253f03) (all the Git* properties require git plugin).
/// </summary>
[CanBeNull] public string GitCommit => EnvironmentInfo.GetVariable<string>("GIT_COMMIT");
/// <summary>
/// For Git-based projects, this variable contains the Git hash of the previous build commit (like ce9a3c1404e8c91be604088670e93434c4253f03) (all the Git* properties require git plugin).
/// </summary>
[CanBeNull] public string GitPreviousCommit => EnvironmentInfo.GetVariable<string>("GIT_PREVIOUS_COMMIT");
/// <summary>
/// For Git-based projects, this variable contains the Git hash of the last successful build (like ce9a3c1404e8c91be604088670e93434c4253f03) (all the Git* properties require git plugin).
/// </summary>
[CanBeNull] public string GitPreviousSuccessfulCommit => EnvironmentInfo.GetVariable<string>("GIT_PREVIOUS_SUCCESSFUL_COMMIT");
/// <summary>
/// For Git-based projects, this variable contains the Git url (like git@github.com:user/repo.git or [https://github.com/user/repo.git]) (all the Git* properties require git plugin).
/// </summary>
[CanBeNull] public string GitUrl => EnvironmentInfo.GetVariable<string>("GIT_URL");
/// <summary>
/// The path to the jenkins home directory.
/// </summary>
public string JenkinsHome => EnvironmentInfo.GetVariable<string>("JENKINS_HOME");
/// <summary>
/// The jenkins server cookie.
/// </summary>
public string JenkinsServerCookie => EnvironmentInfo.GetVariable<string>("JENKINS_SERVER_COOKIE");
/// <summary>
/// The base name of the current job, such as "Nuke".
/// </summary>
public string JobBaseName => EnvironmentInfo.GetVariable<string>("JOB_BASE_NAME");
/// <summary>
/// The url to the currents job overview.
/// </summary>
public string JobDisplayUrl => EnvironmentInfo.GetVariable<string>("JOB_DISPLAY_URL");
/// <summary>
/// The name of the current job, such as "Nuke".
/// </summary>
public string JobName => EnvironmentInfo.GetVariable<string>("JOB_NAME");
/// <summary>
/// The labels of the node this build is running on, such as "win64 msbuild".
/// </summary>
public string NodeLabels => EnvironmentInfo.GetVariable<string>("NODE_LABELS");
/// <summary>
/// The name of the node this build is running on, such as "master".
/// </summary>
public string NodeName => EnvironmentInfo.GetVariable<string>("NODE_NAME");
/// <summary>
/// The url to the currents run changes page.
/// </summary>
public string RunChangesDisplayUrl => EnvironmentInfo.GetVariable<string>("RUN_CHANGES_DISPLAY_URL");
/// <summary>
/// The url to the currents run overview page.
/// </summary>
public string RunDisplayUrl => EnvironmentInfo.GetVariable<string>("RUN_DISPLAY_URL");
/// <summary>
/// The path to the folder this job is running in.
/// </summary>
public string Workspace => EnvironmentInfo.GetVariable<string>("WORKSPACE");
}
}
| 42.985507 | 207 | 0.646999 | [
"MIT"
] | ChaseFlorell/nuke | source/Nuke.Common/CI/Jenkins/Jenkins.cs | 5,942 | C# |
using System.Collections.Generic;
using Essensoft.AspNetCore.Payment.Alipay.Response;
namespace Essensoft.AspNetCore.Payment.Alipay.Request
{
/// <summary>
/// koubei.catering.pos.order.upload
/// </summary>
public class KoubeiCateringPosOrderUploadRequest : IAlipayRequest<KoubeiCateringPosOrderUploadResponse>
{
/// <summary>
/// pos订单信息上传接口
/// </summary>
public string BizContent { get; set; }
#region IAlipayRequest Members
private bool needEncrypt = false;
private string apiVersion = "1.0";
private string terminalType;
private string terminalInfo;
private string prodCode;
private string notifyUrl;
private string returnUrl;
private AlipayObject bizModel;
public void SetNeedEncrypt(bool needEncrypt)
{
this.needEncrypt = needEncrypt;
}
public bool GetNeedEncrypt()
{
return needEncrypt;
}
public void SetNotifyUrl(string notifyUrl)
{
this.notifyUrl = notifyUrl;
}
public string GetNotifyUrl()
{
return notifyUrl;
}
public void SetReturnUrl(string returnUrl)
{
this.returnUrl = returnUrl;
}
public string GetReturnUrl()
{
return returnUrl;
}
public void SetTerminalType(string terminalType)
{
this.terminalType = terminalType;
}
public string GetTerminalType()
{
return terminalType;
}
public void SetTerminalInfo(string terminalInfo)
{
this.terminalInfo = terminalInfo;
}
public string GetTerminalInfo()
{
return terminalInfo;
}
public void SetProdCode(string prodCode)
{
this.prodCode = prodCode;
}
public string GetProdCode()
{
return prodCode;
}
public string GetApiName()
{
return "koubei.catering.pos.order.upload";
}
public void SetApiVersion(string apiVersion)
{
this.apiVersion = apiVersion;
}
public string GetApiVersion()
{
return apiVersion;
}
public IDictionary<string, string> GetParameters()
{
var parameters = new AlipayDictionary
{
{ "biz_content", BizContent }
};
return parameters;
}
public AlipayObject GetBizModel()
{
return bizModel;
}
public void SetBizModel(AlipayObject bizModel)
{
this.bizModel = bizModel;
}
#endregion
}
}
| 22.717742 | 107 | 0.548101 | [
"MIT"
] | lzw316/payment | src/Essensoft.AspNetCore.Payment.Alipay/Request/KoubeiCateringPosOrderUploadRequest.cs | 2,835 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Ors.Core.Caching;
using Ors.Core.Components;
using Ors.Core.Serialization;
using Ors.Core.Utilities;
namespace Ors.Core.Configurations
{
public class Configuration
{
private static Configuration _instance = new Configuration();
private Configuration()
{
}
public static Configuration Instance { get { return _instance; } }
public Configuration SetDefault<TService, TImplementer>(LifeStyle life = LifeStyle.Singleton)
where TService : class
where TImplementer : class, TService
{
ObjectContainer.Register<TService, TImplementer>(life);
return this;
}
public Configuration SetDefault<TService, TImplementer>(TImplementer instance)
where TService : class
where TImplementer : class, TService
{
ObjectContainer.RegisterInstance<TService, TImplementer>(instance);
return this;
}
public Configuration RegisterCommon()
{
this.SetDefault<IJsonSerializer, Json>();
this.SetDefault<ICache, MemoryCache>();
return this;
}
private readonly IList<Type> _assemblyInitializers = new List<Type>();
public Configuration RegisterBusinessComponents(params Assembly[] assemblies)
{
foreach (var assembly in assemblies)
{
try
{
foreach (var type in assembly.GetTypes().Where(TypeUtils.IsComponent))
{
ObjectContainer.RegisterType(type, LifeStyle.Singleton);
foreach (var interfaceType in type.GetInterfaces())
{
ObjectContainer.RegisterType(interfaceType, type);
}
if (TypeUtils.IsAssemblyInitializer(type))
{
_assemblyInitializers.Add(type);
}
}
}
catch { }
}
return this;
}
public Configuration InitializeAssemblies(params Assembly[] assemblies)
{
foreach (var initType in _assemblyInitializers)
{
var initializer = ObjectContainer.Resolve(initType) as IAssemblyInitializer;
if (initializer != null)
{
initializer.Initialize(assemblies);
}
}
return this;
}
}
}
| 32.352273 | 102 | 0.531788 | [
"Apache-2.0"
] | tianzhiyuan/Spellet | src/Ors.Core/Configurations/Configuration.cs | 2,849 | C# |
/*
* Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
* See https://github.com/openiddict/openiddict-core for more information concerning
* the license and the contributors participating to this project.
*/
using Microsoft.Extensions.DependencyInjection;
using Moq;
using Xunit;
using static OpenIddict.Server.OpenIddictServerEvents;
namespace OpenIddict.Server.IntegrationTests;
public abstract partial class OpenIddictServerIntegrationTests
{
[Theory]
[InlineData(nameof(HttpMethod.Delete))]
[InlineData(nameof(HttpMethod.Head))]
[InlineData(nameof(HttpMethod.Options))]
[InlineData(nameof(HttpMethod.Put))]
[InlineData(nameof(HttpMethod.Trace))]
public async Task ExtractLogoutRequest_UnexpectedMethodReturnsAnError(string method)
{
// Arrange
await using var server = await CreateServerAsync(options => options.EnableDegradedMode());
await using var client = await server.CreateClientAsync();
// Act
var response = await client.SendAsync(method, "/connect/logout", new OpenIddictRequest());
// Assert
Assert.Equal(Errors.InvalidRequest, response.Error);
Assert.Equal(SR.GetResourceString(SR.ID2084), response.ErrorDescription);
Assert.Equal(SR.FormatID8000(SR.ID2084), response.ErrorUri);
}
[Theory]
[InlineData("custom_error", null, null)]
[InlineData("custom_error", "custom_description", null)]
[InlineData("custom_error", "custom_description", "custom_uri")]
[InlineData(null, "custom_description", null)]
[InlineData(null, "custom_description", "custom_uri")]
[InlineData(null, null, "custom_uri")]
[InlineData(null, null, null)]
public async Task ExtractLogoutRequest_AllowsRejectingRequest(string error, string description, string uri)
{
// Arrange
await using var server = await CreateServerAsync(options =>
{
options.EnableDegradedMode();
options.AddEventHandler<ExtractLogoutRequestContext>(builder =>
builder.UseInlineHandler(context =>
{
context.Reject(error, description, uri);
return default;
}));
});
await using var client = await server.CreateClientAsync();
// Act
var response = await client.PostAsync("/connect/logout", new OpenIddictRequest());
// Assert
Assert.Equal(error ?? Errors.InvalidRequest, response.Error);
Assert.Equal(description, response.ErrorDescription);
Assert.Equal(uri, response.ErrorUri);
}
[Fact]
public async Task ExtractLogoutRequest_AllowsHandlingResponse()
{
// Arrange
await using var server = await CreateServerAsync(options =>
{
options.EnableDegradedMode();
options.AddEventHandler<ExtractLogoutRequestContext>(builder =>
builder.UseInlineHandler(context =>
{
context.Transaction.SetProperty("custom_response", new
{
name = "Bob le Bricoleur"
});
context.HandleRequest();
return default;
}));
});
await using var client = await server.CreateClientAsync();
// Act
var response = await client.GetAsync("/connect/logout");
// Assert
Assert.Equal("Bob le Bricoleur", (string?) response["name"]);
}
[Fact]
public async Task ExtractLogoutRequest_AllowsSkippingHandler()
{
// Arrange
await using var server = await CreateServerAsync(options =>
{
options.EnableDegradedMode();
options.AddEventHandler<ExtractLogoutRequestContext>(builder =>
builder.UseInlineHandler(context =>
{
context.SkipRequest();
return default;
}));
});
await using var client = await server.CreateClientAsync();
// Act
var response = await client.GetAsync("/connect/logout");
// Assert
Assert.Equal("Bob le Magnifique", (string?) response["name"]);
}
[Theory]
[InlineData("/path", SR.ID2030)]
[InlineData("/tmp/file.xml", SR.ID2030)]
[InlineData("C:\\tmp\\file.xml", SR.ID2030)]
[InlineData("http://www.fabrikam.com/path#param=value", SR.ID2031)]
public async Task ValidateLogoutRequest_InvalidRedirectUriCausesAnError(string address, string message)
{
// Arrange
await using var server = await CreateServerAsync();
await using var client = await server.CreateClientAsync();
// Act
var response = await client.PostAsync("/connect/logout", new OpenIddictRequest
{
PostLogoutRedirectUri = address
});
// Assert
Assert.Equal(Errors.InvalidRequest, response.Error);
Assert.Equal(string.Format(SR.GetResourceString(message), Parameters.PostLogoutRedirectUri), response.ErrorDescription);
Assert.Equal(SR.FormatID8000(message), response.ErrorUri);
}
[Fact]
public async Task ValidateLogoutRequest_RequestIsRejectedWhenNoMatchingApplicationIsFound()
{
// Arrange
var manager = CreateApplicationManager(mock =>
{
mock.Setup(manager => manager.FindByPostLogoutRedirectUriAsync("http://www.fabrikam.com/path", It.IsAny<CancellationToken>()))
.Returns(AsyncEnumerable.Empty<OpenIddictApplication>());
});
await using var server = await CreateServerAsync(options =>
{
options.Services.AddSingleton(manager);
});
await using var client = await server.CreateClientAsync();
// Act
var response = await client.PostAsync("/connect/logout", new OpenIddictRequest
{
PostLogoutRedirectUri = "http://www.fabrikam.com/path"
});
// Assert
Assert.Equal(Errors.InvalidRequest, response.Error);
Assert.Equal(SR.FormatID2052(Parameters.PostLogoutRedirectUri), response.ErrorDescription);
Assert.Equal(SR.FormatID8000(SR.ID2052), response.ErrorUri);
Mock.Get(manager).Verify(manager => manager.FindByPostLogoutRedirectUriAsync("http://www.fabrikam.com/path", It.IsAny<CancellationToken>()), Times.Once());
}
[Fact]
public async Task ValidateLogoutRequest_RequestIsRejectedWhenNoMatchingApplicationIsGrantedEndpointPermission()
{
// Arrange
var applications = new[]
{
new OpenIddictApplication(),
new OpenIddictApplication()
};
var manager = CreateApplicationManager(mock =>
{
mock.Setup(manager => manager.FindByPostLogoutRedirectUriAsync("http://www.fabrikam.com/path", It.IsAny<CancellationToken>()))
.Returns(applications.ToAsyncEnumerable());
mock.Setup(manager => manager.HasPermissionAsync(applications[0], Permissions.Endpoints.Logout, It.IsAny<CancellationToken>()))
.ReturnsAsync(false);
mock.Setup(manager => manager.HasPermissionAsync(applications[1], Permissions.Endpoints.Logout, It.IsAny<CancellationToken>()))
.ReturnsAsync(false);
});
await using var server = await CreateServerAsync(options =>
{
options.Services.AddSingleton(manager);
options.Configure(options => options.IgnoreEndpointPermissions = false);
});
await using var client = await server.CreateClientAsync();
// Act
var response = await client.PostAsync("/connect/logout", new OpenIddictRequest
{
PostLogoutRedirectUri = "http://www.fabrikam.com/path"
});
// Assert
Assert.Equal(Errors.InvalidRequest, response.Error);
Assert.Equal(SR.FormatID2052(Parameters.PostLogoutRedirectUri), response.ErrorDescription);
Assert.Equal(SR.FormatID8000(SR.ID2052), response.ErrorUri);
Mock.Get(manager).Verify(manager => manager.FindByPostLogoutRedirectUriAsync("http://www.fabrikam.com/path", It.IsAny<CancellationToken>()), Times.Once());
Mock.Get(manager).Verify(manager => manager.HasPermissionAsync(applications[0], Permissions.Endpoints.Logout, It.IsAny<CancellationToken>()), Times.Once());
Mock.Get(manager).Verify(manager => manager.HasPermissionAsync(applications[1], Permissions.Endpoints.Logout, It.IsAny<CancellationToken>()), Times.Once());
}
[Fact]
public async Task ValidateLogoutRequest_RequestIsValidatedWhenMatchingApplicationIsFound()
{
// Arrange
var applications = new[]
{
new OpenIddictApplication(),
new OpenIddictApplication(),
new OpenIddictApplication()
};
var manager = CreateApplicationManager(mock =>
{
mock.Setup(manager => manager.FindByPostLogoutRedirectUriAsync("http://www.fabrikam.com/path", It.IsAny<CancellationToken>()))
.Returns(applications.ToAsyncEnumerable());
mock.Setup(manager => manager.HasPermissionAsync(applications[0], Permissions.Endpoints.Logout, It.IsAny<CancellationToken>()))
.ReturnsAsync(false);
mock.Setup(manager => manager.HasPermissionAsync(applications[1], Permissions.Endpoints.Logout, It.IsAny<CancellationToken>()))
.ReturnsAsync(true);
mock.Setup(manager => manager.HasPermissionAsync(applications[2], Permissions.Endpoints.Logout, It.IsAny<CancellationToken>()))
.ReturnsAsync(false);
});
await using var server = await CreateServerAsync(options =>
{
options.Services.AddSingleton(manager);
options.SetLogoutEndpointUris("/signout");
options.Configure(options => options.IgnoreEndpointPermissions = false);
options.AddEventHandler<HandleLogoutRequestContext>(builder =>
builder.UseInlineHandler(context =>
{
context.SignOut();
return default;
}));
});
await using var client = await server.CreateClientAsync();
// Act
var response = await client.PostAsync("/signout", new OpenIddictRequest
{
PostLogoutRedirectUri = "http://www.fabrikam.com/path",
State = "af0ifjsldkj"
});
// Assert
Assert.Equal("af0ifjsldkj", response.State);
Mock.Get(manager).Verify(manager => manager.FindByPostLogoutRedirectUriAsync("http://www.fabrikam.com/path", It.IsAny<CancellationToken>()), Times.Once());
Mock.Get(manager).Verify(manager => manager.HasPermissionAsync(applications[0], Permissions.Endpoints.Logout, It.IsAny<CancellationToken>()), Times.Once());
Mock.Get(manager).Verify(manager => manager.HasPermissionAsync(applications[1], Permissions.Endpoints.Logout, It.IsAny<CancellationToken>()), Times.Once());
Mock.Get(manager).Verify(manager => manager.HasPermissionAsync(applications[2], Permissions.Endpoints.Logout, It.IsAny<CancellationToken>()), Times.Never());
}
[Theory]
[InlineData("custom_error", null, null)]
[InlineData("custom_error", "custom_description", null)]
[InlineData("custom_error", "custom_description", "custom_uri")]
[InlineData(null, "custom_description", null)]
[InlineData(null, "custom_description", "custom_uri")]
[InlineData(null, null, "custom_uri")]
[InlineData(null, null, null)]
public async Task ValidateLogoutRequest_AllowsRejectingRequest(string error, string description, string uri)
{
// Arrange
await using var server = await CreateServerAsync(options =>
{
options.EnableDegradedMode();
options.AddEventHandler<ValidateLogoutRequestContext>(builder =>
builder.UseInlineHandler(context =>
{
context.Reject(error, description, uri);
return default;
}));
});
await using var client = await server.CreateClientAsync();
// Act
var response = await client.PostAsync("/connect/logout", new OpenIddictRequest());
// Assert
Assert.Equal(error ?? Errors.InvalidRequest, response.Error);
Assert.Equal(description, response.ErrorDescription);
Assert.Equal(uri, response.ErrorUri);
}
[Fact]
public async Task ValidateLogoutRequest_AllowsHandlingResponse()
{
// Arrange
await using var server = await CreateServerAsync(options =>
{
options.EnableDegradedMode();
options.AddEventHandler<ValidateLogoutRequestContext>(builder =>
builder.UseInlineHandler(context =>
{
context.Transaction.SetProperty("custom_response", new
{
name = "Bob le Bricoleur"
});
context.HandleRequest();
return default;
}));
});
await using var client = await server.CreateClientAsync();
// Act
var response = await client.PostAsync("/connect/logout", new OpenIddictRequest());
// Assert
Assert.Equal("Bob le Bricoleur", (string?) response["name"]);
}
[Fact]
public async Task ValidateLogoutRequest_AllowsSkippingHandler()
{
// Arrange
await using var server = await CreateServerAsync(options =>
{
options.EnableDegradedMode();
options.AddEventHandler<ValidateLogoutRequestContext>(builder =>
builder.UseInlineHandler(context =>
{
context.SkipRequest();
return default;
}));
});
await using var client = await server.CreateClientAsync();
// Act
var response = await client.PostAsync("/connect/logout", new OpenIddictRequest());
// Assert
Assert.Equal("Bob le Magnifique", (string?) response["name"]);
}
[Theory]
[InlineData("custom_error", null, null)]
[InlineData("custom_error", "custom_description", null)]
[InlineData("custom_error", "custom_description", "custom_uri")]
[InlineData(null, "custom_description", null)]
[InlineData(null, "custom_description", "custom_uri")]
[InlineData(null, null, "custom_uri")]
[InlineData(null, null, null)]
public async Task HandleLogoutRequest_AllowsRejectingRequest(string error, string description, string uri)
{
// Arrange
await using var server = await CreateServerAsync(options =>
{
options.EnableDegradedMode();
options.AddEventHandler<HandleLogoutRequestContext>(builder =>
builder.UseInlineHandler(context =>
{
context.Reject(error, description, uri);
return default;
}));
});
await using var client = await server.CreateClientAsync();
// Act
var response = await client.PostAsync("/connect/logout", new OpenIddictRequest());
// Assert
Assert.Equal(error ?? Errors.InvalidRequest, response.Error);
Assert.Equal(description, response.ErrorDescription);
Assert.Equal(uri, response.ErrorUri);
}
[Fact]
public async Task HandleLogoutRequest_AllowsHandlingResponse()
{
// Arrange
await using var server = await CreateServerAsync(options =>
{
options.EnableDegradedMode();
options.AddEventHandler<HandleLogoutRequestContext>(builder =>
builder.UseInlineHandler(context =>
{
context.Transaction.SetProperty("custom_response", new
{
name = "Bob le Bricoleur"
});
context.HandleRequest();
return default;
}));
});
await using var client = await server.CreateClientAsync();
// Act
var response = await client.PostAsync("/connect/logout", new OpenIddictRequest());
// Assert
Assert.Equal("Bob le Bricoleur", (string?) response["name"]);
}
[Fact]
public async Task HandleLogoutRequest_AllowsSkippingHandler()
{
// Arrange
await using var server = await CreateServerAsync(options =>
{
options.EnableDegradedMode();
options.AddEventHandler<HandleLogoutRequestContext>(builder =>
builder.UseInlineHandler(context =>
{
context.SkipRequest();
return default;
}));
});
await using var client = await server.CreateClientAsync();
// Act
var response = await client.PostAsync("/connect/logout", new OpenIddictRequest());
// Assert
Assert.Equal("Bob le Magnifique", (string?) response["name"]);
}
[Fact]
public async Task HandleLogoutResponse_ResponseContainsCustomParameters()
{
// Arrange
await using var server = await CreateServerAsync(options =>
{
options.EnableDegradedMode();
options.AddEventHandler<HandleLogoutRequestContext>(builder =>
builder.UseInlineHandler(context =>
{
context.SignOut();
context.Parameters["custom_parameter"] = "custom_value";
context.Parameters["parameter_with_multiple_values"] = new[]
{
"custom_value_1",
"custom_value_2"
};
return default;
}));
});
await using var client = await server.CreateClientAsync();
// Act
var response = await client.PostAsync("/connect/logout", new OpenIddictRequest
{
PostLogoutRedirectUri = "http://www.fabrikam.com/path"
});
// Assert
Assert.Equal("custom_value", (string?) response["custom_parameter"]);
Assert.Equal(new[] { "custom_value_1", "custom_value_2" }, (string[]?) response["parameter_with_multiple_values"]);
}
[Fact]
public async Task ApplyLogoutResponse_AllowsHandlingResponse()
{
// Arrange
await using var server = await CreateServerAsync(options =>
{
options.EnableDegradedMode();
options.AddEventHandler<HandleLogoutRequestContext>(builder =>
builder.UseInlineHandler(context =>
{
context.SignOut();
return default;
}));
options.AddEventHandler<ApplyLogoutResponseContext>(builder =>
builder.UseInlineHandler(context =>
{
context.Transaction.SetProperty("custom_response", new
{
name = "Bob le Bricoleur"
});
context.HandleRequest();
return default;
}));
});
await using var client = await server.CreateClientAsync();
// Act
var response = await client.PostAsync("/connect/logout", new OpenIddictRequest());
// Assert
Assert.Equal("Bob le Bricoleur", (string?) response["name"]);
}
[Fact]
public async Task ApplyLogoutResponse_ResponseContainsCustomParameters()
{
// Arrange
await using var server = await CreateServerAsync(options =>
{
options.EnableDegradedMode();
options.AddEventHandler<HandleLogoutRequestContext>(builder =>
builder.UseInlineHandler(context =>
{
context.SignOut();
return default;
}));
options.AddEventHandler<ApplyLogoutResponseContext>(builder =>
builder.UseInlineHandler(context =>
{
context.Response["custom_parameter"] = "custom_value";
context.Response["parameter_with_multiple_values"] = new[]
{
"custom_value_1",
"custom_value_2"
};
return default;
}));
});
await using var client = await server.CreateClientAsync();
// Act
var response = await client.PostAsync("/connect/logout", new OpenIddictRequest
{
PostLogoutRedirectUri = "http://www.fabrikam.com/path"
});
// Assert
Assert.Equal("custom_value", (string?) response["custom_parameter"]);
Assert.Equal(new[] { "custom_value_1", "custom_value_2" }, (string[]?) response["parameter_with_multiple_values"]);
}
[Fact]
public async Task ApplyLogoutResponse_UsesPostLogoutRedirectUriWhenProvided()
{
// Arrange
await using var server = await CreateServerAsync(options =>
{
options.EnableDegradedMode();
options.AddEventHandler<HandleLogoutRequestContext>(builder =>
builder.UseInlineHandler(context =>
{
context.SignOut();
return default;
}));
options.AddEventHandler<ApplyLogoutResponseContext>(builder =>
builder.UseInlineHandler(context =>
{
context.Response["target_uri"] = context.PostLogoutRedirectUri;
return default;
}));
});
await using var client = await server.CreateClientAsync();
// Act
var response = await client.PostAsync("/connect/logout", new OpenIddictRequest
{
PostLogoutRedirectUri = "http://www.fabrikam.com/path"
});
// Assert
Assert.Equal("http://www.fabrikam.com/path", (string?) response["target_uri"]);
}
[Fact]
public async Task ApplyLogoutResponse_ReturnsEmptyResponseWhenNoPostLogoutRedirectUriIsProvided()
{
// Arrange
await using var server = await CreateServerAsync(options =>
{
options.EnableDegradedMode();
options.AddEventHandler<HandleLogoutRequestContext>(builder =>
builder.UseInlineHandler(context =>
{
context.SignOut();
return default;
}));
options.AddEventHandler<ApplyLogoutResponseContext>(builder =>
builder.UseInlineHandler(context =>
{
context.Response["target_uri"] = context.PostLogoutRedirectUri;
return default;
}));
});
await using var client = await server.CreateClientAsync();
// Act
var response = await client.PostAsync("/connect/logout", new OpenIddictRequest());
// Assert
Assert.Empty(response.GetParameters());
}
[Fact]
public async Task ApplyLogoutResponse_DoesNotSetStateWhenUserIsNotRedirected()
{
// Arrange
await using var server = await CreateServerAsync(options =>
{
options.EnableDegradedMode();
options.SetLogoutEndpointUris("/signout");
options.AddEventHandler<HandleLogoutRequestContext>(builder =>
builder.UseInlineHandler(context =>
{
context.SignOut();
return default;
}));
});
await using var client = await server.CreateClientAsync();
// Act
var response = await client.PostAsync("/signout", new OpenIddictRequest
{
State = "af0ifjsldkj"
});
// Assert
Assert.Null(response.State);
}
[Fact]
public async Task ApplyLogoutResponse_FlowsStateWhenRedirectUriIsUsed()
{
// Arrange
await using var server = await CreateServerAsync(options =>
{
options.EnableDegradedMode();
options.SetLogoutEndpointUris("/signout");
options.AddEventHandler<HandleLogoutRequestContext>(builder =>
builder.UseInlineHandler(context =>
{
context.SignOut();
return default;
}));
});
await using var client = await server.CreateClientAsync();
// Act
var response = await client.PostAsync("/signout", new OpenIddictRequest
{
PostLogoutRedirectUri = "http://www.fabrikam.com/path",
State = "af0ifjsldkj"
});
// Assert
Assert.Equal("af0ifjsldkj", response.State);
}
[Fact]
public async Task ApplyLogoutResponse_DoesNotOverrideStateSetByApplicationCode()
{
// Arrange
await using var server = await CreateServerAsync(options =>
{
options.EnableDegradedMode();
options.SetLogoutEndpointUris("/signout");
options.AddEventHandler<HandleLogoutRequestContext>(builder =>
builder.UseInlineHandler(context =>
{
context.SignOut();
return default;
}));
options.AddEventHandler<ApplyLogoutResponseContext>(builder =>
builder.UseInlineHandler(context =>
{
context.Response.State = "custom_state";
return default;
}));
});
await using var client = await server.CreateClientAsync();
// Act
var response = await client.PostAsync("/signout", new OpenIddictRequest
{
PostLogoutRedirectUri = "http://www.fabrikam.com/path",
State = "af0ifjsldkj"
});
// Assert
Assert.Equal("custom_state", response.State);
}
}
| 34.378272 | 165 | 0.595203 | [
"Apache-2.0"
] | Darthruneis/openiddict-core | test/OpenIddict.Server.IntegrationTests/OpenIddictServerIntegrationTests.Session.cs | 26,267 | C# |
using UnityEngine;
using System.Collections;
public class TriggerZoneScript : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
void OnTriggerEnter(Collider other)
{
Destroy (other.gameObject);
}
}
| 13.761905 | 48 | 0.695502 | [
"MIT"
] | ivopazdosreis/gauntlet_runner | Assets/_Scripts/TriggerZoneScript.cs | 291 | C# |
using System;
namespace Tel4Net.ExceptionNumbers.Regions
{
internal class CaymanIslands:IExceptionalCountryCode
{
public string[] InternationalPrefixes => new[] { "011" };
public string[] CountryCodes => new[] { "1" };
public string[] NationalPrefix => new[] { "1" };
public string[] NationalNumberPrefix => new[] { "345" };
public int[] NationalNumberLength => new[] { 7 };
public Func<string, bool> CustomValidation => null;
public Func<string, string> CustomNormalizer => null;
}
}
| 34.6875 | 65 | 0.628829 | [
"MIT"
] | deadmann/Tel4Net | Tel4Net/ExceptionNumbers/Regions/CaymanIslands.cs | 557 | C# |
using Paillave.Etl.Core;
using Paillave.Etl.Reactive.Operators;
using Paillave.Etl.ExcelFile.Core;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace Paillave.Etl.ExcelFile
{
public class ToExcelFileArgs<TIn>
{
public IStream<TIn> MainStream { get; set; }
public ExcelFileDefinition<TIn> Mapping { get; set; }
public string FileName { get; set; }
}
public class ToExcelFileStreamNode<TIn> : StreamNodeBase<IFileValue, IStream<IFileValue>, ToExcelFileArgs<TIn>>
{
public ToExcelFileStreamNode(string name, ToExcelFileArgs<TIn> args) : base(name, args)
{
}
public override ProcessImpact PerformanceImpact => ProcessImpact.Average;
public override ProcessImpact MemoryFootPrint => ProcessImpact.Average;
protected override IStream<IFileValue> CreateOutputStream(ToExcelFileArgs<TIn> args)
{
var obs = args.MainStream.Observable.ToList().Map(ProcessValueToOutput);
return CreateUnsortedStream(obs);
}
protected IFileValue ProcessValueToOutput(IList<TIn> value)
{
MemoryStream stream = new MemoryStream();
var excelReader = Args.Mapping.GetExcelReader();
value.WriteExcelListInStream(excelReader, stream);
return FileValue.Create(stream, this.Args.FileName, new ExcelFileValueMetadata
{
Map = excelReader.GetTextMapping()
});
}
}
public class ExcelFileValueMetadata : FileValueMetadataBase
{
public Dictionary<string, string> Map { get; set; }
}
public class ToExcelFileArgs<TIn, TStream>
where TStream : IStream<TIn>
{
public TStream MainStream { get; set; }
public ExcelFileDefinition<TIn> Mapping { get; set; }
public ISingleStream<Stream> TargetStream { get; set; }
}
public class ToExcelFileStreamNode<TIn, TStream> : StreamNodeBase<TIn, TStream, ToExcelFileArgs<TIn, TStream>>
where TStream : IStream<TIn>
{
public ToExcelFileStreamNode(string name, ToExcelFileArgs<TIn, TStream> args) : base(name, args)
{
}
public override ProcessImpact PerformanceImpact => ProcessImpact.Average;
public override ProcessImpact MemoryFootPrint => ProcessImpact.Average;
protected override TStream CreateOutputStream(ToExcelFileArgs<TIn, TStream> args)
{
var firstStreamWriter = args.TargetStream.Observable.First().DelayTillEndOfStream();
var obs = args.MainStream.Observable.ToList()
.CombineWithLatest(firstStreamWriter, (i, r) => { ProcessValueToOutput(r, i); return i; }, true)
.FlatMap((i, ct) => PushObservable.FromEnumerable(i, ct));
return CreateMatchingStream(obs, args.MainStream);
}
protected void ProcessValueToOutput(Stream streamWriter, IList<TIn> value)
{
value.WriteExcelListInStream(Args.Mapping, streamWriter);
}
}
}
| 39.701299 | 115 | 0.66634 | [
"MIT"
] | fundprocess/Etl.Net | src/Paillave.Etl.ExcelFile/ToExcelFileStreamNode.cs | 3,059 | C# |
using Microsoft.EntityFrameworkCore;
using System;
using System.ComponentModel.DataAnnotations;
namespace Core.Data.Models
{
[Index(nameof(Track))]
public class SpotifyTrack : BaseEntity
{
[MaxLength(255)]
public string Track { get; set; }
[Required]
[MaxLength(128)]
public string Url { get; set; }
public Guid ArtistId { get; set; }
public Artist Artist { get; set; }
}
}
| 21.428571 | 44 | 0.622222 | [
"MIT"
] | djohsson/Lastgram | src/Core/Data/Models/SpotifyTrack.cs | 452 | C# |
using System.Collections.Generic;
using Illumina.BaseSpace.SDK.Types;
using ServiceStack.Text;
namespace Illumina.BaseSpace.SDK.Deserialization
{
public static class MiscDeserializers
{
private static readonly JsonSerializer<Notification<Agreement>> agreementSerializer = new JsonSerializer<Notification<Agreement>>();
private static readonly JsonSerializer<Notification<ScheduledDowntime>> scheduledSerializer = new JsonSerializer<Notification<ScheduledDowntime>>();
public static INotification<object> NotificationDeserializer(string source)
{
//determine type, then use appropriate deserializer
var asValues = JsonSerializer.DeserializeFromString<Dictionary<string, string>>(source);
string type = asValues["Type"];
object o = null;
switch (type.ToLower())
{
case "agreement":
o = agreementSerializer.DeserializeFromString(source).Item;
break;
case "scheduleddowntime":
o = scheduledSerializer.DeserializeFromString(source).Item;
break;
}
return new Notification<object> { Item = o, Type = type };
}
}
}
| 35.416667 | 156 | 0.643137 | [
"Apache-2.0"
] | basespace/basespace-csharp-sdk | BaseSpace.SDK/Deserialization/MiscDeserializers.cs | 1,277 | C# |
// Remark: this file was auto-generated based on 'CircularSequence.puml'.
// Any changes will be overwritten the next time the file is generated.
namespace EtAlii.CryptoMagic
{
using System;
using System.Threading.Tasks;
using Stateless;
/// <summary>
/// This is the base class for the state machine as defined in 'CircularSequence.puml'.
/// Inherit the class and override the transition methods to define the necessary business behavior.
/// The transitions can then be triggered by calling the corresponding trigger methods.
/// </summary>
public abstract class CircularSequenceBase
{
protected global::Stateless.StateMachine<State, Trigger> StateMachine => _stateMachine;
private readonly global::Stateless.StateMachine<State, Trigger> _stateMachine;
protected CircularSequenceBase()
{
// Time to create a new state machine instance.
_stateMachine = new global::Stateless.StateMachine<State, Trigger>(State._Begin);
// Then we need to configure the state machine.
_stateMachine.Configure(State._Begin)
.OnEntry(On_BeginEntered)
.OnExit(On_BeginExited)
.Permit(Trigger.Start, State.LoadPreviousCycleFromDatabase);
_stateMachine.Configure(State._End)
.OnEntry(On_EndEntered)
.OnEntryFrom(Trigger.Continue, On_EndEnteredFromContinueTrigger)
.OnEntryFrom(Trigger.Continue, On_EndEnteredFromContinueTrigger)
.OnEntryFrom(Trigger.Continue, On_EndEnteredFromContinueTrigger)
.OnEntryFrom(Trigger.Continue, On_EndEnteredFromContinueTrigger)
.OnEntryFrom(Trigger.No, On_EndEnteredFromNoTrigger)
.OnEntryFrom(Trigger.No, On_EndEnteredFromNoTrigger)
.OnEntryFrom(Trigger.No, On_EndEnteredFromNoTrigger)
.OnEntryFrom(Trigger.No, On_EndEnteredFromNoTrigger)
.OnEntryFrom(Trigger.No, On_EndEnteredFromNoTrigger)
.OnEntryFrom(Trigger.No, On_EndEnteredFromNoTrigger)
.OnExit(On_EndExited);
_stateMachine.Configure(State.BuyAInInitialCycle)
.OnEntry(OnBuyAInInitialCycleEntered)
.OnEntryFrom(Trigger.Yes, OnBuyAInInitialCycleEnteredFromYesTrigger)
.OnExit(OnBuyAInInitialCycleExited)
.Permit(Trigger.Continue, State._End)
.SubstateOf(State.InitialPurchaseOfA);
_stateMachine.Configure(State.SellABuyBInInitialCycle)
.OnEntry(OnSellABuyBInInitialCycleEntered)
.OnEntryFrom(Trigger.Yes, OnSellABuyBInInitialCycleEnteredFromYesTrigger)
.OnExit(OnSellABuyBInInitialCycleExited)
.Permit(Trigger.Continue, State._End)
.SubstateOf(State.InitialPurchaseOfB);
_stateMachine.Configure(State.CheckIfSufficientA)
.OnEntry(OnCheckIfSufficientAEntered)
.OnEntryFrom(Trigger.Yes, OnCheckIfSufficientAEnteredFromYesTrigger)
.OnExit(OnCheckIfSufficientAExited)
.Permit(Trigger.Continue, State.HasSufficientA)
.SubstateOf(State.TransferFromAToB);
_stateMachine.Configure(State.CheckIfSufficientB)
.OnEntry(OnCheckIfSufficientBEntered)
.OnEntryFrom(Trigger.Yes, OnCheckIfSufficientBEnteredFromYesTrigger)
.OnExit(OnCheckIfSufficientBExited)
.Permit(Trigger.Continue, State.HasSufficientB)
.SubstateOf(State.TransferFromBToA);
_stateMachine.Configure(State.CheckIfSufficientReferenceInInitialPurchaseOfA)
.OnEntry(OnCheckIfSufficientReferenceInInitialPurchaseOfAEntered)
.OnEntryFrom(Trigger._BeginToCheckIfSufficientReferenceInInitialPurchaseOfA, OnCheckIfSufficientReferenceInInitialPurchaseOfAEnteredFrom_BeginToCheckIfSufficientReferenceInInitialPurchaseOfATrigger)
.OnExit(OnCheckIfSufficientReferenceInInitialPurchaseOfAExited)
.Permit(Trigger.Continue, State.HasSufficientReferenceInInitialPurchaseOfA)
.SubstateOf(State.InitialPurchaseOfA);
_stateMachine.Configure(State.CheckIfSufficientReferenceInInitialPurchaseOfB)
.OnEntry(OnCheckIfSufficientReferenceInInitialPurchaseOfBEntered)
.OnEntryFrom(Trigger._BeginToCheckIfSufficientReferenceInInitialPurchaseOfB, OnCheckIfSufficientReferenceInInitialPurchaseOfBEnteredFrom_BeginToCheckIfSufficientReferenceInInitialPurchaseOfBTrigger)
.OnExit(OnCheckIfSufficientReferenceInInitialPurchaseOfBExited)
.Permit(Trigger.Continue, State.HasSufficientReferenceInInitialPurchaseOfB)
.SubstateOf(State.InitialPurchaseOfB);
_stateMachine.Configure(State.CheckWhatCycle)
.OnEntry(() => OnCheckWhatCycleEntered(new CheckWhatCycleEventArgs(this)))
.OnEntryFrom(Trigger.Continue, () => OnCheckWhatCycleEnteredFromContinueTrigger(new CheckWhatCycleEventArgs(this)))
.OnExit(OnCheckWhatCycleExited)
.Permit(Trigger.IsInitialCycleToA, State.InitialPurchaseOfA)
.Permit(Trigger.IsInitialCycleToB, State.InitialPurchaseOfB)
.Permit(Trigger.IsNormalCycleFromAToB, State.TransferFromAToB)
.Permit(Trigger.IsNormalCycleFromBToA, State.TransferFromBToA);
_stateMachine.Configure(State.GetSituationInTransferFromAToB)
.OnEntry(OnGetSituationInTransferFromAToBEntered)
.OnEntryFrom(Trigger._BeginToGetSituationInTransferFromAToB, OnGetSituationInTransferFromAToBEnteredFrom_BeginToGetSituationInTransferFromAToBTrigger)
.OnExit(OnGetSituationInTransferFromAToBExited)
.Permit(Trigger.Continue, State.TransferFromAToBIsWorthIt)
.SubstateOf(State.TransferFromAToB);
_stateMachine.Configure(State.GetSituationInTransferFromBToA)
.OnEntry(OnGetSituationInTransferFromBToAEntered)
.OnEntryFrom(Trigger._BeginToGetSituationInTransferFromBToA, OnGetSituationInTransferFromBToAEnteredFrom_BeginToGetSituationInTransferFromBToATrigger)
.OnExit(OnGetSituationInTransferFromBToAExited)
.Permit(Trigger.Continue, State.TransferFromBToAIsWorthIt)
.SubstateOf(State.TransferFromBToA);
_stateMachine.Configure(State.HasSufficientA)
.OnEntry(() => OnHasSufficientAEntered(new HasSufficientAEventArgs(this)))
.OnEntryFrom(Trigger.Continue, () => OnHasSufficientAEnteredFromContinueTrigger(new HasSufficientAEventArgs(this)))
.OnExit(OnHasSufficientAExited)
.Permit(Trigger.No, State._End)
.Permit(Trigger.Yes, State.SellABuyB)
.SubstateOf(State.TransferFromAToB);
_stateMachine.Configure(State.HasSufficientB)
.OnEntry(() => OnHasSufficientBEntered(new HasSufficientBEventArgs(this)))
.OnEntryFrom(Trigger.Continue, () => OnHasSufficientBEnteredFromContinueTrigger(new HasSufficientBEventArgs(this)))
.OnExit(OnHasSufficientBExited)
.Permit(Trigger.No, State._End)
.Permit(Trigger.Yes, State.SellBBuyA)
.SubstateOf(State.TransferFromBToA);
_stateMachine.Configure(State.HasSufficientReferenceInInitialPurchaseOfA)
.OnEntry(() => OnHasSufficientReferenceInInitialPurchaseOfAEntered(new HasSufficientReferenceInInitialPurchaseOfAEventArgs(this)))
.OnEntryFrom(Trigger.Continue, () => OnHasSufficientReferenceInInitialPurchaseOfAEnteredFromContinueTrigger(new HasSufficientReferenceInInitialPurchaseOfAEventArgs(this)))
.OnExit(OnHasSufficientReferenceInInitialPurchaseOfAExited)
.Permit(Trigger.No, State._End)
.Permit(Trigger.Yes, State.BuyAInInitialCycle)
.SubstateOf(State.InitialPurchaseOfA);
_stateMachine.Configure(State.HasSufficientReferenceInInitialPurchaseOfB)
.OnEntry(() => OnHasSufficientReferenceInInitialPurchaseOfBEntered(new HasSufficientReferenceInInitialPurchaseOfBEventArgs(this)))
.OnEntryFrom(Trigger.Continue, () => OnHasSufficientReferenceInInitialPurchaseOfBEnteredFromContinueTrigger(new HasSufficientReferenceInInitialPurchaseOfBEventArgs(this)))
.OnExit(OnHasSufficientReferenceInInitialPurchaseOfBExited)
.Permit(Trigger.No, State._End)
.Permit(Trigger.Yes, State.SellABuyBInInitialCycle)
.SubstateOf(State.InitialPurchaseOfB);
_stateMachine.Configure(State.InitialPurchaseOfA)
.InitialTransition(State.CheckIfSufficientReferenceInInitialPurchaseOfA)
.OnEntry(OnInitialPurchaseOfAEntered)
.OnEntryFrom(Trigger.IsInitialCycleToA, OnInitialPurchaseOfAEnteredFromIsInitialCycleToATrigger)
.OnExit(OnInitialPurchaseOfAExited)
.Permit(Trigger.Continue, State.Wait);
_stateMachine.Configure(State.InitialPurchaseOfB)
.InitialTransition(State.CheckIfSufficientReferenceInInitialPurchaseOfB)
.OnEntry(OnInitialPurchaseOfBEntered)
.OnEntryFrom(Trigger.IsInitialCycleToB, OnInitialPurchaseOfBEnteredFromIsInitialCycleToBTrigger)
.OnExit(OnInitialPurchaseOfBExited)
.Permit(Trigger.Continue, State.Wait);
_stateMachine.Configure(State.LoadPreviousCycleFromDatabase)
.OnEntry(OnLoadPreviousCycleFromDatabaseEntered)
.OnEntryFrom(Trigger.Start, OnLoadPreviousCycleFromDatabaseEnteredFromStartTrigger)
.OnExit(OnLoadPreviousCycleFromDatabaseExited)
.Permit(Trigger.Continue, State.CheckWhatCycle);
_stateMachine.Configure(State.SellABuyB)
.OnEntry(OnSellABuyBEntered)
.OnEntryFrom(Trigger.Yes, OnSellABuyBEnteredFromYesTrigger)
.OnExit(OnSellABuyBExited)
.Permit(Trigger.Continue, State._End)
.SubstateOf(State.TransferFromAToB);
_stateMachine.Configure(State.SellBBuyA)
.OnEntry(OnSellBBuyAEntered)
.OnEntryFrom(Trigger.Yes, OnSellBBuyAEnteredFromYesTrigger)
.OnExit(OnSellBBuyAExited)
.Permit(Trigger.Continue, State._End)
.SubstateOf(State.TransferFromBToA);
_stateMachine.Configure(State.TransferFromAToB)
.InitialTransition(State.GetSituationInTransferFromAToB)
.OnEntry(OnTransferFromAToBEntered)
.OnEntryFrom(Trigger.IsNormalCycleFromAToB, OnTransferFromAToBEnteredFromIsNormalCycleFromAToBTrigger)
.OnExit(OnTransferFromAToBExited)
.Permit(Trigger.Continue, State.Wait);
_stateMachine.Configure(State.TransferFromAToBIsWorthIt)
.OnEntry(() => OnTransferFromAToBIsWorthItEntered(new TransferFromAToBIsWorthItEventArgs(this)))
.OnEntryFrom(Trigger.Continue, () => OnTransferFromAToBIsWorthItEnteredFromContinueTrigger(new TransferFromAToBIsWorthItEventArgs(this)))
.OnExit(OnTransferFromAToBIsWorthItExited)
.Permit(Trigger.No, State._End)
.Permit(Trigger.Yes, State.CheckIfSufficientA)
.SubstateOf(State.TransferFromAToB);
_stateMachine.Configure(State.TransferFromBToA)
.InitialTransition(State.GetSituationInTransferFromBToA)
.OnEntry(OnTransferFromBToAEntered)
.OnEntryFrom(Trigger.IsNormalCycleFromBToA, OnTransferFromBToAEnteredFromIsNormalCycleFromBToATrigger)
.OnExit(OnTransferFromBToAExited)
.Permit(Trigger.Continue, State.Wait);
_stateMachine.Configure(State.TransferFromBToAIsWorthIt)
.OnEntry(() => OnTransferFromBToAIsWorthItEntered(new TransferFromBToAIsWorthItEventArgs(this)))
.OnEntryFrom(Trigger.Continue, () => OnTransferFromBToAIsWorthItEnteredFromContinueTrigger(new TransferFromBToAIsWorthItEventArgs(this)))
.OnExit(OnTransferFromBToAIsWorthItExited)
.Permit(Trigger.No, State._End)
.Permit(Trigger.Yes, State.CheckIfSufficientB)
.SubstateOf(State.TransferFromBToA);
_stateMachine.Configure(State.Wait)
.OnEntry(OnWaitEntered)
.OnEntryFrom(Trigger.Continue, OnWaitEnteredFromContinueTrigger)
.OnEntryFrom(Trigger.Continue, OnWaitEnteredFromContinueTrigger)
.OnEntryFrom(Trigger.Continue, OnWaitEnteredFromContinueTrigger)
.OnEntryFrom(Trigger.Continue, OnWaitEnteredFromContinueTrigger)
.OnExit(OnWaitExited);
}
// The methods below can be each called to fire a specific trigger
// and cause the state machine to transition to another state.
/// <summary>
/// Depending on the current state, call this method to trigger one of the sync transitions below:<br/>
/// _Begin --> CheckIfSufficientReferenceInInitialPurchaseOfA : _BeginToCheckIfSufficientReferenceInInitialPurchaseOfA<br/>
/// </summary>
public void _BeginToCheckIfSufficientReferenceInInitialPurchaseOfA() => _stateMachine.Fire(Trigger._BeginToCheckIfSufficientReferenceInInitialPurchaseOfA);
/// <summary>
/// Depending on the current state, call this method to trigger one of the sync transitions below:<br/>
/// _Begin --> CheckIfSufficientReferenceInInitialPurchaseOfB : _BeginToCheckIfSufficientReferenceInInitialPurchaseOfB<br/>
/// </summary>
public void _BeginToCheckIfSufficientReferenceInInitialPurchaseOfB() => _stateMachine.Fire(Trigger._BeginToCheckIfSufficientReferenceInInitialPurchaseOfB);
/// <summary>
/// Depending on the current state, call this method to trigger one of the sync transitions below:<br/>
/// _Begin --> GetSituationInTransferFromAToB : _BeginToGetSituationInTransferFromAToB<br/>
/// </summary>
public void _BeginToGetSituationInTransferFromAToB() => _stateMachine.Fire(Trigger._BeginToGetSituationInTransferFromAToB);
/// <summary>
/// Depending on the current state, call this method to trigger one of the sync transitions below:<br/>
/// _Begin --> GetSituationInTransferFromBToA : _BeginToGetSituationInTransferFromBToA<br/>
/// </summary>
public void _BeginToGetSituationInTransferFromBToA() => _stateMachine.Fire(Trigger._BeginToGetSituationInTransferFromBToA);
/// <summary>
/// Depending on the current state, call this method to trigger one of the sync transitions below:<br/>
/// LoadPreviousCycleFromDatabase --> CheckWhatCycle : Continue<br/>
/// InitialPurchaseOfA --> Wait : Continue<br/>
/// InitialPurchaseOfB --> Wait : Continue<br/>
/// TransferFromAToB --> Wait : Continue<br/>
/// TransferFromBToA --> Wait : Continue<br/>
/// CheckIfSufficientReferenceInInitialPurchaseOfB --> HasSufficientReferenceInInitialPurchaseOfB : Continue<br/>
/// BuyBInInitialCycle --> _End : Continue<br/>
/// CheckIfSufficientReferenceInInitialPurchaseOfA --> HasSufficientReferenceInInitialPurchaseOfA : Continue<br/>
/// BuyAInInitialCycle --> _End : Continue<br/>
/// GetSituationInTransferFromAToB --> TransferFromAToBIsWorthIt : Continue<br/>
/// CheckIfSufficientA --> HasSufficientA : Continue<br/>
/// SellABuyB --> _End : Continue<br/>
/// GetSituationInTransferFromBToA --> TransferFromBToAIsWorthIt : Continue<br/>
/// CheckIfSufficientB --> HasSufficientB : Continue<br/>
/// SellBBuyA --> _End : Continue<br/>
/// </summary>
public void Continue() => _stateMachine.Fire(Trigger.Continue);
/// <summary>
/// Depending on the current state, call this method to trigger one of the sync transitions below:<br/>
/// CheckWhatCycle --> InitialPurchaseOfA : IsInitialCycleToA<br/>
/// </summary>
public void IsInitialCycleToA() => _stateMachine.Fire(Trigger.IsInitialCycleToA);
/// <summary>
/// Depending on the current state, call this method to trigger one of the sync transitions below:<br/>
/// CheckWhatCycle --> InitialPurchaseOfB : IsInitialCycleToB<br/>
/// </summary>
public void IsInitialCycleToB() => _stateMachine.Fire(Trigger.IsInitialCycleToB);
/// <summary>
/// Depending on the current state, call this method to trigger one of the sync transitions below:<br/>
/// CheckWhatCycle --> TransferFromAToB : IsNormalCycleFromAToB<br/>
/// </summary>
public void IsNormalCycleFromAToB() => _stateMachine.Fire(Trigger.IsNormalCycleFromAToB);
/// <summary>
/// Depending on the current state, call this method to trigger one of the sync transitions below:<br/>
/// CheckWhatCycle --> TransferFromBToA : IsNormalCycleFromBToA<br/>
/// </summary>
public void IsNormalCycleFromBToA() => _stateMachine.Fire(Trigger.IsNormalCycleFromBToA);
/// <summary>
/// Depending on the current state, call this method to trigger one of the sync transitions below:<br/>
/// HasSufficientReferenceInInitialPurchaseOfB --> _End : No<br/>
/// HasSufficientReferenceInInitialPurchaseOfA --> _End : No<br/>
/// TransferFromAToBIsWorthIt --> _End : No<br/>
/// HasSufficientA --> _End : No<br/>
/// TransferFromBToAIsWorthIt --> _End : No<br/>
/// HasSufficientB --> _End : No<br/>
/// </summary>
public void No() => _stateMachine.Fire(Trigger.No);
/// <summary>
/// Depending on the current state, call this method to trigger one of the sync transitions below:<br/>
/// _Begin --> LoadPreviousCycleFromDatabase : Start<br/>
/// </summary>
public void Start() => _stateMachine.Fire(Trigger.Start);
/// <summary>
/// Depending on the current state, call this method to trigger one of the sync transitions below:<br/>
/// HasSufficientReferenceInInitialPurchaseOfB --> BuyBInInitialCycle : Yes<br/>
/// HasSufficientReferenceInInitialPurchaseOfA --> BuyAInInitialCycle : Yes<br/>
/// TransferFromAToBIsWorthIt --> CheckIfSufficientA : Yes<br/>
/// HasSufficientA --> SellABuyB : Yes<br/>
/// TransferFromBToAIsWorthIt --> CheckIfSufficientB : Yes<br/>
/// HasSufficientB --> SellBBuyA : Yes<br/>
/// </summary>
public void Yes() => _stateMachine.Fire(Trigger.Yes);
// The classes below represent the EventArgs as used by some of the methods.
protected class CheckWhatCycleEventArgs
{
private readonly CircularSequenceBase _stateMachine;
public CheckWhatCycleEventArgs(CircularSequenceBase stateMachine)
{
_stateMachine = stateMachine;
}
/// <summary>
/// Depending on the current state, call this method to trigger one of the sync transitions below:<br/>
/// CheckWhatCycle --> InitialPurchaseOfA : IsInitialCycleToA<br/>
/// </summary>
public void IsInitialCycleToA() => _stateMachine.IsInitialCycleToA();
/// <summary>
/// Depending on the current state, call this method to trigger one of the sync transitions below:<br/>
/// CheckWhatCycle --> InitialPurchaseOfB : IsInitialCycleToB<br/>
/// </summary>
public void IsInitialCycleToB() => _stateMachine.IsInitialCycleToB();
/// <summary>
/// Depending on the current state, call this method to trigger one of the sync transitions below:<br/>
/// CheckWhatCycle --> TransferFromAToB : IsNormalCycleFromAToB<br/>
/// </summary>
public void IsNormalCycleFromAToB() => _stateMachine.IsNormalCycleFromAToB();
/// <summary>
/// Depending on the current state, call this method to trigger one of the sync transitions below:<br/>
/// CheckWhatCycle --> TransferFromBToA : IsNormalCycleFromBToA<br/>
/// </summary>
public void IsNormalCycleFromBToA() => _stateMachine.IsNormalCycleFromBToA();
}
protected class HasSufficientReferenceInInitialPurchaseOfBEventArgs
{
private readonly CircularSequenceBase _stateMachine;
public HasSufficientReferenceInInitialPurchaseOfBEventArgs(CircularSequenceBase stateMachine)
{
_stateMachine = stateMachine;
}
/// <summary>
/// Depending on the current state, call this method to trigger one of the sync transitions below:<br/>
/// HasSufficientReferenceInInitialPurchaseOfB --> BuyBInInitialCycle : Yes<br/>
/// </summary>
public void Yes() => _stateMachine.Yes();
/// <summary>
/// Depending on the current state, call this method to trigger one of the sync transitions below:<br/>
/// HasSufficientReferenceInInitialPurchaseOfB --> _End : No<br/>
/// </summary>
public void No() => _stateMachine.No();
}
protected class HasSufficientReferenceInInitialPurchaseOfAEventArgs
{
private readonly CircularSequenceBase _stateMachine;
public HasSufficientReferenceInInitialPurchaseOfAEventArgs(CircularSequenceBase stateMachine)
{
_stateMachine = stateMachine;
}
/// <summary>
/// Depending on the current state, call this method to trigger one of the sync transitions below:<br/>
/// HasSufficientReferenceInInitialPurchaseOfA --> BuyAInInitialCycle : Yes<br/>
/// </summary>
public void Yes() => _stateMachine.Yes();
/// <summary>
/// Depending on the current state, call this method to trigger one of the sync transitions below:<br/>
/// HasSufficientReferenceInInitialPurchaseOfA --> _End : No<br/>
/// </summary>
public void No() => _stateMachine.No();
}
protected class TransferFromAToBIsWorthItEventArgs
{
private readonly CircularSequenceBase _stateMachine;
public TransferFromAToBIsWorthItEventArgs(CircularSequenceBase stateMachine)
{
_stateMachine = stateMachine;
}
/// <summary>
/// Depending on the current state, call this method to trigger one of the sync transitions below:<br/>
/// TransferFromAToBIsWorthIt --> CheckIfSufficientA : Yes<br/>
/// </summary>
public void Yes() => _stateMachine.Yes();
/// <summary>
/// Depending on the current state, call this method to trigger one of the sync transitions below:<br/>
/// TransferFromAToBIsWorthIt --> _End : No<br/>
/// </summary>
public void No() => _stateMachine.No();
}
protected class HasSufficientAEventArgs
{
private readonly CircularSequenceBase _stateMachine;
public HasSufficientAEventArgs(CircularSequenceBase stateMachine)
{
_stateMachine = stateMachine;
}
/// <summary>
/// Depending on the current state, call this method to trigger one of the sync transitions below:<br/>
/// HasSufficientA --> _End : No<br/>
/// </summary>
public void No() => _stateMachine.No();
/// <summary>
/// Depending on the current state, call this method to trigger one of the sync transitions below:<br/>
/// HasSufficientA --> SellABuyB : Yes<br/>
/// </summary>
public void Yes() => _stateMachine.Yes();
}
protected class TransferFromBToAIsWorthItEventArgs
{
private readonly CircularSequenceBase _stateMachine;
public TransferFromBToAIsWorthItEventArgs(CircularSequenceBase stateMachine)
{
_stateMachine = stateMachine;
}
/// <summary>
/// Depending on the current state, call this method to trigger one of the sync transitions below:<br/>
/// TransferFromBToAIsWorthIt --> CheckIfSufficientB : Yes<br/>
/// </summary>
public void Yes() => _stateMachine.Yes();
/// <summary>
/// Depending on the current state, call this method to trigger one of the sync transitions below:<br/>
/// TransferFromBToAIsWorthIt --> _End : No<br/>
/// </summary>
public void No() => _stateMachine.No();
}
protected class HasSufficientBEventArgs
{
private readonly CircularSequenceBase _stateMachine;
public HasSufficientBEventArgs(CircularSequenceBase stateMachine)
{
_stateMachine = stateMachine;
}
/// <summary>
/// Depending on the current state, call this method to trigger one of the sync transitions below:<br/>
/// HasSufficientB --> _End : No<br/>
/// </summary>
public void No() => _stateMachine.No();
/// <summary>
/// Depending on the current state, call this method to trigger one of the sync transitions below:<br/>
/// HasSufficientB --> SellBBuyA : Yes<br/>
/// </summary>
public void Yes() => _stateMachine.Yes();
}
// Of course each state machine needs a set of states.
protected enum State
{
_Begin,
_End,
BuyAInInitialCycle,
SellABuyBInInitialCycle,
CheckIfSufficientA,
CheckIfSufficientB,
CheckIfSufficientReferenceInInitialPurchaseOfA,
CheckIfSufficientReferenceInInitialPurchaseOfB,
CheckWhatCycle,
GetSituationInTransferFromAToB,
GetSituationInTransferFromBToA,
HasSufficientA,
HasSufficientB,
HasSufficientReferenceInInitialPurchaseOfA,
HasSufficientReferenceInInitialPurchaseOfB,
InitialPurchaseOfA,
InitialPurchaseOfB,
LoadPreviousCycleFromDatabase,
SellABuyB,
SellBBuyA,
TransferFromAToB,
TransferFromAToBIsWorthIt,
TransferFromBToA,
TransferFromBToAIsWorthIt,
Wait,
}
// And all state machine need something that trigger them.
protected enum Trigger
{
_BeginToCheckIfSufficientReferenceInInitialPurchaseOfA,
_BeginToCheckIfSufficientReferenceInInitialPurchaseOfB,
_BeginToGetSituationInTransferFromAToB,
_BeginToGetSituationInTransferFromBToA,
Continue,
IsInitialCycleToA,
IsInitialCycleToB,
IsNormalCycleFromAToB,
IsNormalCycleFromBToA,
No,
Start,
Yes,
}
/// <summary>
/// Implement this method to handle the entry of the '_Begin' state.
/// </summary>
protected virtual void On_BeginEntered()
{
}
/// <summary>
/// Implement this method to handle the exit of the '_Begin' state.
/// </summary>
protected virtual void On_BeginExited()
{
}
/// <summary>
/// Implement this method to handle the entry of the '_End' state.
/// </summary>
protected virtual void On_EndEntered()
{
}
/// <summary>
/// Implement this method to handle the exit of the '_End' state.
/// </summary>
protected virtual void On_EndExited()
{
}
/// <summary>
/// Implement this method to handle the transition below:<br/>
/// HasSufficientReferenceInInitialPurchaseOfB --> _End : No<br/>
/// </summary>
protected virtual void On_EndEnteredFromNoTrigger()
{
}
/// <summary>
/// Implement this method to handle the transition below:<br/>
/// BuyBInInitialCycle --> _End : Continue<br/>
/// </summary>
protected virtual void On_EndEnteredFromContinueTrigger()
{
}
/// <summary>
/// Implement this method to handle the entry of the 'BuyAInInitialCycle' state.
/// </summary>
protected virtual void OnBuyAInInitialCycleEntered()
{
}
/// <summary>
/// Implement this method to handle the exit of the 'BuyAInInitialCycle' state.
/// </summary>
protected virtual void OnBuyAInInitialCycleExited()
{
}
/// <summary>
/// Implement this method to handle the transition below:<br/>
/// HasSufficientReferenceInInitialPurchaseOfA --> BuyAInInitialCycle : Yes<br/>
/// </summary>
protected virtual void OnBuyAInInitialCycleEnteredFromYesTrigger()
{
}
/// <summary>
/// Implement this method to handle the entry of the 'BuyBInInitialCycle' state.
/// </summary>
protected virtual void OnSellABuyBInInitialCycleEntered()
{
}
/// <summary>
/// Implement this method to handle the exit of the 'BuyBInInitialCycle' state.
/// </summary>
protected virtual void OnSellABuyBInInitialCycleExited()
{
}
/// <summary>
/// Implement this method to handle the transition below:<br/>
/// HasSufficientReferenceInInitialPurchaseOfB --> BuyBInInitialCycle : Yes<br/>
/// </summary>
protected virtual void OnSellABuyBInInitialCycleEnteredFromYesTrigger()
{
}
/// <summary>
/// Implement this method to handle the entry of the 'CheckIfSufficientA' state.
/// </summary>
protected virtual void OnCheckIfSufficientAEntered()
{
}
/// <summary>
/// Implement this method to handle the exit of the 'CheckIfSufficientA' state.
/// </summary>
protected virtual void OnCheckIfSufficientAExited()
{
}
/// <summary>
/// Implement this method to handle the transition below:<br/>
/// TransferFromAToBIsWorthIt --> CheckIfSufficientA : Yes<br/>
/// </summary>
protected virtual void OnCheckIfSufficientAEnteredFromYesTrigger()
{
}
/// <summary>
/// Implement this method to handle the entry of the 'CheckIfSufficientB' state.
/// </summary>
protected virtual void OnCheckIfSufficientBEntered()
{
}
/// <summary>
/// Implement this method to handle the exit of the 'CheckIfSufficientB' state.
/// </summary>
protected virtual void OnCheckIfSufficientBExited()
{
}
/// <summary>
/// Implement this method to handle the transition below:<br/>
/// TransferFromBToAIsWorthIt --> CheckIfSufficientB : Yes<br/>
/// </summary>
protected virtual void OnCheckIfSufficientBEnteredFromYesTrigger()
{
}
/// <summary>
/// Implement this method to handle the entry of the 'CheckIfSufficientReferenceInInitialPurchaseOfA' state.
/// </summary>
protected virtual void OnCheckIfSufficientReferenceInInitialPurchaseOfAEntered()
{
}
/// <summary>
/// Implement this method to handle the exit of the 'CheckIfSufficientReferenceInInitialPurchaseOfA' state.
/// </summary>
protected virtual void OnCheckIfSufficientReferenceInInitialPurchaseOfAExited()
{
}
/// <summary>
/// Implement this method to handle the transition below:<br/>
/// _Begin --> CheckIfSufficientReferenceInInitialPurchaseOfA : _BeginToCheckIfSufficientReferenceInInitialPurchaseOfA<br/>
/// </summary>
protected virtual void OnCheckIfSufficientReferenceInInitialPurchaseOfAEnteredFrom_BeginToCheckIfSufficientReferenceInInitialPurchaseOfATrigger()
{
}
/// <summary>
/// Implement this method to handle the entry of the 'CheckIfSufficientReferenceInInitialPurchaseOfB' state.
/// </summary>
protected virtual void OnCheckIfSufficientReferenceInInitialPurchaseOfBEntered()
{
}
/// <summary>
/// Implement this method to handle the exit of the 'CheckIfSufficientReferenceInInitialPurchaseOfB' state.
/// </summary>
protected virtual void OnCheckIfSufficientReferenceInInitialPurchaseOfBExited()
{
}
/// <summary>
/// Implement this method to handle the transition below:<br/>
/// _Begin --> CheckIfSufficientReferenceInInitialPurchaseOfB : _BeginToCheckIfSufficientReferenceInInitialPurchaseOfB<br/>
/// </summary>
protected virtual void OnCheckIfSufficientReferenceInInitialPurchaseOfBEnteredFrom_BeginToCheckIfSufficientReferenceInInitialPurchaseOfBTrigger()
{
}
/// <summary>
/// Implement this method to handle the entry of the 'CheckWhatCycle' state.
/// </summary>
protected virtual void OnCheckWhatCycleEntered(CheckWhatCycleEventArgs e)
{
}
/// <summary>
/// Implement this method to handle the exit of the 'CheckWhatCycle' state.
/// </summary>
protected virtual void OnCheckWhatCycleExited()
{
}
/// <summary>
/// Implement this method to handle the transition below:<br/>
/// LoadPreviousCycleFromDatabase --> CheckWhatCycle : Continue<br/>
/// </summary>
protected virtual void OnCheckWhatCycleEnteredFromContinueTrigger(CheckWhatCycleEventArgs e)
{
}
/// <summary>
/// Implement this method to handle the entry of the 'GetSituationInTransferFromAToB' state.
/// </summary>
protected virtual void OnGetSituationInTransferFromAToBEntered()
{
}
/// <summary>
/// Implement this method to handle the exit of the 'GetSituationInTransferFromAToB' state.
/// </summary>
protected virtual void OnGetSituationInTransferFromAToBExited()
{
}
/// <summary>
/// Implement this method to handle the transition below:<br/>
/// _Begin --> GetSituationInTransferFromAToB : _BeginToGetSituationInTransferFromAToB<br/>
/// </summary>
protected virtual void OnGetSituationInTransferFromAToBEnteredFrom_BeginToGetSituationInTransferFromAToBTrigger()
{
}
/// <summary>
/// Implement this method to handle the entry of the 'GetSituationInTransferFromBToA' state.
/// </summary>
protected virtual void OnGetSituationInTransferFromBToAEntered()
{
}
/// <summary>
/// Implement this method to handle the exit of the 'GetSituationInTransferFromBToA' state.
/// </summary>
protected virtual void OnGetSituationInTransferFromBToAExited()
{
}
/// <summary>
/// Implement this method to handle the transition below:<br/>
/// _Begin --> GetSituationInTransferFromBToA : _BeginToGetSituationInTransferFromBToA<br/>
/// </summary>
protected virtual void OnGetSituationInTransferFromBToAEnteredFrom_BeginToGetSituationInTransferFromBToATrigger()
{
}
/// <summary>
/// Implement this method to handle the entry of the 'HasSufficientA' state.
/// </summary>
protected virtual void OnHasSufficientAEntered(HasSufficientAEventArgs e)
{
}
/// <summary>
/// Implement this method to handle the exit of the 'HasSufficientA' state.
/// </summary>
protected virtual void OnHasSufficientAExited()
{
}
/// <summary>
/// Implement this method to handle the transition below:<br/>
/// CheckIfSufficientA --> HasSufficientA : Continue<br/>
/// </summary>
protected virtual void OnHasSufficientAEnteredFromContinueTrigger(HasSufficientAEventArgs e)
{
}
/// <summary>
/// Implement this method to handle the entry of the 'HasSufficientB' state.
/// </summary>
protected virtual void OnHasSufficientBEntered(HasSufficientBEventArgs e)
{
}
/// <summary>
/// Implement this method to handle the exit of the 'HasSufficientB' state.
/// </summary>
protected virtual void OnHasSufficientBExited()
{
}
/// <summary>
/// Implement this method to handle the transition below:<br/>
/// CheckIfSufficientB --> HasSufficientB : Continue<br/>
/// </summary>
protected virtual void OnHasSufficientBEnteredFromContinueTrigger(HasSufficientBEventArgs e)
{
}
/// <summary>
/// Implement this method to handle the entry of the 'HasSufficientReferenceInInitialPurchaseOfA' state.
/// </summary>
protected virtual void OnHasSufficientReferenceInInitialPurchaseOfAEntered(HasSufficientReferenceInInitialPurchaseOfAEventArgs e)
{
}
/// <summary>
/// Implement this method to handle the exit of the 'HasSufficientReferenceInInitialPurchaseOfA' state.
/// </summary>
protected virtual void OnHasSufficientReferenceInInitialPurchaseOfAExited()
{
}
/// <summary>
/// Implement this method to handle the transition below:<br/>
/// CheckIfSufficientReferenceInInitialPurchaseOfA --> HasSufficientReferenceInInitialPurchaseOfA : Continue<br/>
/// </summary>
protected virtual void OnHasSufficientReferenceInInitialPurchaseOfAEnteredFromContinueTrigger(HasSufficientReferenceInInitialPurchaseOfAEventArgs e)
{
}
/// <summary>
/// Implement this method to handle the entry of the 'HasSufficientReferenceInInitialPurchaseOfB' state.
/// </summary>
protected virtual void OnHasSufficientReferenceInInitialPurchaseOfBEntered(HasSufficientReferenceInInitialPurchaseOfBEventArgs e)
{
}
/// <summary>
/// Implement this method to handle the exit of the 'HasSufficientReferenceInInitialPurchaseOfB' state.
/// </summary>
protected virtual void OnHasSufficientReferenceInInitialPurchaseOfBExited()
{
}
/// <summary>
/// Implement this method to handle the transition below:<br/>
/// CheckIfSufficientReferenceInInitialPurchaseOfB --> HasSufficientReferenceInInitialPurchaseOfB : Continue<br/>
/// </summary>
protected virtual void OnHasSufficientReferenceInInitialPurchaseOfBEnteredFromContinueTrigger(HasSufficientReferenceInInitialPurchaseOfBEventArgs e)
{
}
/// <summary>
/// Implement this method to handle the entry of the 'InitialPurchaseOfA' state.
/// </summary>
protected virtual void OnInitialPurchaseOfAEntered()
{
}
/// <summary>
/// Implement this method to handle the exit of the 'InitialPurchaseOfA' state.
/// </summary>
protected virtual void OnInitialPurchaseOfAExited()
{
}
/// <summary>
/// Implement this method to handle the transition below:<br/>
/// CheckWhatCycle --> InitialPurchaseOfA : IsInitialCycleToA<br/>
/// </summary>
protected virtual void OnInitialPurchaseOfAEnteredFromIsInitialCycleToATrigger()
{
}
/// <summary>
/// Implement this method to handle the entry of the 'InitialPurchaseOfB' state.
/// </summary>
protected virtual void OnInitialPurchaseOfBEntered()
{
}
/// <summary>
/// Implement this method to handle the exit of the 'InitialPurchaseOfB' state.
/// </summary>
protected virtual void OnInitialPurchaseOfBExited()
{
}
/// <summary>
/// Implement this method to handle the transition below:<br/>
/// CheckWhatCycle --> InitialPurchaseOfB : IsInitialCycleToB<br/>
/// </summary>
protected virtual void OnInitialPurchaseOfBEnteredFromIsInitialCycleToBTrigger()
{
}
/// <summary>
/// Implement this method to handle the entry of the 'LoadPreviousCycleFromDatabase' state.
/// </summary>
protected virtual void OnLoadPreviousCycleFromDatabaseEntered()
{
}
/// <summary>
/// Implement this method to handle the exit of the 'LoadPreviousCycleFromDatabase' state.
/// </summary>
protected virtual void OnLoadPreviousCycleFromDatabaseExited()
{
}
/// <summary>
/// Implement this method to handle the transition below:<br/>
/// _Begin --> LoadPreviousCycleFromDatabase : Start<br/>
/// </summary>
protected virtual void OnLoadPreviousCycleFromDatabaseEnteredFromStartTrigger()
{
}
/// <summary>
/// Implement this method to handle the entry of the 'SellABuyB' state.
/// </summary>
protected virtual void OnSellABuyBEntered()
{
}
/// <summary>
/// Implement this method to handle the exit of the 'SellABuyB' state.
/// </summary>
protected virtual void OnSellABuyBExited()
{
}
/// <summary>
/// Implement this method to handle the transition below:<br/>
/// HasSufficientA --> SellABuyB : Yes<br/>
/// </summary>
protected virtual void OnSellABuyBEnteredFromYesTrigger()
{
}
/// <summary>
/// Implement this method to handle the entry of the 'SellBBuyA' state.
/// </summary>
protected virtual void OnSellBBuyAEntered()
{
}
/// <summary>
/// Implement this method to handle the exit of the 'SellBBuyA' state.
/// </summary>
protected virtual void OnSellBBuyAExited()
{
}
/// <summary>
/// Implement this method to handle the transition below:<br/>
/// HasSufficientB --> SellBBuyA : Yes<br/>
/// </summary>
protected virtual void OnSellBBuyAEnteredFromYesTrigger()
{
}
/// <summary>
/// Implement this method to handle the entry of the 'TransferFromAToB' state.
/// </summary>
protected virtual void OnTransferFromAToBEntered()
{
}
/// <summary>
/// Implement this method to handle the exit of the 'TransferFromAToB' state.
/// </summary>
protected virtual void OnTransferFromAToBExited()
{
}
/// <summary>
/// Implement this method to handle the transition below:<br/>
/// CheckWhatCycle --> TransferFromAToB : IsNormalCycleFromAToB<br/>
/// </summary>
protected virtual void OnTransferFromAToBEnteredFromIsNormalCycleFromAToBTrigger()
{
}
/// <summary>
/// Implement this method to handle the entry of the 'TransferFromAToBIsWorthIt' state.
/// </summary>
protected virtual void OnTransferFromAToBIsWorthItEntered(TransferFromAToBIsWorthItEventArgs e)
{
}
/// <summary>
/// Implement this method to handle the exit of the 'TransferFromAToBIsWorthIt' state.
/// </summary>
protected virtual void OnTransferFromAToBIsWorthItExited()
{
}
/// <summary>
/// Implement this method to handle the transition below:<br/>
/// GetSituationInTransferFromAToB --> TransferFromAToBIsWorthIt : Continue<br/>
/// </summary>
protected virtual void OnTransferFromAToBIsWorthItEnteredFromContinueTrigger(TransferFromAToBIsWorthItEventArgs e)
{
}
/// <summary>
/// Implement this method to handle the entry of the 'TransferFromBToA' state.
/// </summary>
protected virtual void OnTransferFromBToAEntered()
{
}
/// <summary>
/// Implement this method to handle the exit of the 'TransferFromBToA' state.
/// </summary>
protected virtual void OnTransferFromBToAExited()
{
}
/// <summary>
/// Implement this method to handle the transition below:<br/>
/// CheckWhatCycle --> TransferFromBToA : IsNormalCycleFromBToA<br/>
/// </summary>
protected virtual void OnTransferFromBToAEnteredFromIsNormalCycleFromBToATrigger()
{
}
/// <summary>
/// Implement this method to handle the entry of the 'TransferFromBToAIsWorthIt' state.
/// </summary>
protected virtual void OnTransferFromBToAIsWorthItEntered(TransferFromBToAIsWorthItEventArgs e)
{
}
/// <summary>
/// Implement this method to handle the exit of the 'TransferFromBToAIsWorthIt' state.
/// </summary>
protected virtual void OnTransferFromBToAIsWorthItExited()
{
}
/// <summary>
/// Implement this method to handle the transition below:<br/>
/// GetSituationInTransferFromBToA --> TransferFromBToAIsWorthIt : Continue<br/>
/// </summary>
protected virtual void OnTransferFromBToAIsWorthItEnteredFromContinueTrigger(TransferFromBToAIsWorthItEventArgs e)
{
}
/// <summary>
/// Implement this method to handle the entry of the 'Wait' state.
/// </summary>
protected virtual void OnWaitEntered()
{
}
/// <summary>
/// Implement this method to handle the exit of the 'Wait' state.
/// </summary>
protected virtual void OnWaitExited()
{
}
/// <summary>
/// Implement this method to handle the transition below:<br/>
/// InitialPurchaseOfA --> Wait : Continue<br/>
/// </summary>
protected virtual void OnWaitEnteredFromContinueTrigger()
{
}
}
}
| 44.281136 | 211 | 0.625458 | [
"MIT"
] | vrenken/EtAlii.CryptoMagic | EtAlii.CryptoMagic/Trading/Circular/Algorithm/CircularSequence.Generated.cs | 48,357 | C# |
namespace Jumoo.uSync.BackOffice.Helpers
{
using System;
using System.Linq;
using System.Xml.Linq;
using System.IO;
using Umbraco.Core;
using Umbraco.Core.Logging;
using Core.Extensions;
public class uSyncIOHelper
{
public static string SavePath(string root, string type, string filePath)
{
return Umbraco.Core.IO.IOHelper.MapPath(
Path.Combine(root, type, filePath + ".config"));
}
public static string SavePath(string root, string type, string path, string name)
{
return
Umbraco.Core.IO.IOHelper.MapPath(
Path.Combine(root, type, path, name + ".config")
);
}
public static void SaveNode(XElement node, string path)
{
try
{
if (File.Exists(path))
{
ArchiveFile(path);
// remove
// File.Delete(path);
}
string folder = Path.GetDirectoryName(path);
if (!Directory.Exists(folder))
Directory.CreateDirectory(folder);
LogHelper.Debug<uSyncIOHelper>("Saving XML to Disk: {0}", () => path);
uSyncEvents.fireSaving(new uSyncEventArgs { fileName = path });
node.Save(path);
uSyncEvents.fireSaved(new uSyncEventArgs { fileName = path });
}
catch(Exception ex)
{
LogHelper.Warn<uSyncEvents>("Failed to save node: ", () => ex.ToString());
}
}
public static void ArchiveFile(string path)
{
LogHelper.Debug<uSyncIOHelper>("Archive: {0}", () => path);
try
{
if (!uSyncBackOfficeContext.Instance.Configuration.Settings.ArchiveVersions)
{
DeleteFile(path);
return;
}
string fileName = Path.GetFileNameWithoutExtension(path);
string folder = Path.GetDirectoryName(path);
var root = uSyncBackOfficeContext.Instance.Configuration.Settings.MappedFolder();
var archiveRoot = uSyncBackOfficeContext.Instance.Configuration.Settings.ArchiveFolder;
string filePath = path.Substring(root.Length);
var archiveFile = string.Format("{0}\\{1}\\{2}_{3}.config",
Umbraco.Core.IO.IOHelper.MapPath(archiveRoot),
filePath, fileName.ToSafeFileName(),
DateTime.Now.ToString("ddMMyy_HHmmss"));
if (!Directory.Exists(Path.GetDirectoryName(archiveFile)))
Directory.CreateDirectory(Path.GetDirectoryName(archiveFile));
if (File.Exists(path))
{
if (File.Exists(archiveFile))
File.Delete(archiveFile);
File.Copy(path, archiveFile);
// archive does delete. because it is always called before a save,
// calling archive without a save is just like deleting (but saving)
DeleteFile(path);
}
}
catch(Exception ex)
{
LogHelper.Warn<uSyncEvents>("Failed to Archive the existing file (might be locked?) {0}", () => ex.ToString());
}
}
public static void ArchiveRelativeFile(string type, string path, string name)
{
string fullpath = Path.Combine(type, path, name);
ArchiveRelativeFile(fullpath);
}
public static void ArchiveRelativeFile(string path, string name)
{
string fullPath = Path.Combine(path, name);
ArchiveRelativeFile(fullPath);
}
public static void ArchiveRelativeFile(string fullPath)
{
var uSyncFolder = uSyncBackOfficeContext.Instance.Configuration.Settings.Folder;
var fullFolder = Path.Combine(uSyncFolder, fullPath + ".config");
ArchiveFile(Umbraco.Core.IO.IOHelper.MapPath(fullFolder));
}
internal static void DeleteFile(string file)
{
LogHelper.Debug<uSyncIOHelper>("Delete File: {0}", () => file);
uSyncEvents.fireDeleting(new uSyncEventArgs { fileName = file });
var blankOnDelete = uSyncBackOfficeContext.Instance.Configuration.Settings.PreserveAllFiles;
if (File.Exists(file))
{
if (!blankOnDelete)
{
LogHelper.Debug<uSyncIOHelper>("Delete: {0}", () => file);
File.Delete(file);
}
else
{
LogHelper.Debug<uSyncIOHelper>("Blank: {0}", () => file);
CreateBlank(file);
}
}
else
{
LogHelper.Debug<uSyncIOHelper>("Cannot find {0} to delete", ()=> file);
}
var dir = Path.GetDirectoryName(file);
if (Directory.Exists(dir))
{
if (!Directory.EnumerateFileSystemEntries(dir).Any())
Directory.Delete(dir);
}
uSyncEvents.fireDeleted(new uSyncEventArgs { fileName = file });
}
internal static void CreateBlank(string file)
{
var key = Guid.NewGuid();
var name = "default";
if (File.Exists(file))
{
try
{
var existing = XElement.Load(file);
if (existing != null && !existing.Name.LocalName.InvariantEquals("uSyncArchive"))
{
key = existing.KeyOrDefault();
name = existing.NameFromNode();
}
}
catch (Exception ex)
{
LogHelper.Debug<uSyncIOHelper>("Unable to load existing xml: {0}", ()=> ex);
}
}
XElement a = new XElement("uSyncArchive",
new XAttribute("Key", key.ToString()),
new XAttribute("Name", name));
a.Save(file);
}
private static void ClenseArchiveFolder(string folder)
{
if (Directory.Exists(folder))
{
int versions = uSyncBackOfficeContext.Instance.Configuration.Settings.MaxArchiveVersionCount;
DirectoryInfo dir = new DirectoryInfo(folder);
FileInfo[] fileList = dir.GetFiles("*.config");
var files = fileList.OrderByDescending(f => f.CreationTime);
foreach (var file in files.Skip(versions))
{
file.Delete();
}
}
}
public static string GetShortGuidPath(Guid guid)
{
string encoded = Convert.ToBase64String(guid.ToByteArray());
encoded = encoded
.Replace("/", "_")
.Replace("+", "-");
return encoded.Substring(0, 22);
}
}
}
| 33.706422 | 127 | 0.50313 | [
"MPL-2.0"
] | SimonHartfield/uSync | Jumoo.uSync.BackOffice/Helpers/uSyncIOHelper.cs | 7,350 | C# |
using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Graphics;
using System.Collections;
using Nez.Systems;
using Nez.Console;
using Nez.Tweens;
using Nez.Timers;
using Nez.BitmapFonts;
using Nez.Analysis;
using Nez.Textures;
namespace Nez
{
public class Core : Game
{
/// <summary>
/// core emitter. emits only Core level events.
/// </summary>
public static Emitter<CoreEvents> emitter;
/// <summary>
/// enables/disables if we should quit the app when escape is pressed
/// </summary>
public static bool exitOnEscapeKeypress = true;
/// <summary>
/// enables/disables pausing when focus is lost. No update or render methods will be called if true when not in focus.
/// </summary>
public static bool pauseOnFocusLost = true;
/// <summary>
/// enables/disables debug rendering
/// </summary>
public static bool debugRenderEnabled = false;
/// <summary>
/// global access to the graphicsDevice
/// </summary>
public static GraphicsDevice graphicsDevice;
/// <summary>
/// global content manager for loading any assets that should stick around between scenes
/// </summary>
public static NezContentManager content;
/// <summary>
/// default SamplerState used by Materials. Note that this must be set at launch! Changing it after that time will result in only
/// Materials created after it was set having the new SamplerState
/// </summary>
public static SamplerState defaultSamplerState = SamplerState.PointClamp;
/// <summary>
/// default wrapped SamplerState. Determined by the Filter of the defaultSamplerState.
/// </summary>
/// <value>The default state of the wraped sampler.</value>
public static SamplerState defaultWrappedSamplerState { get { return defaultSamplerState.Filter == TextureFilter.Point ? SamplerState.PointWrap : SamplerState.LinearWrap; } }
/// <summary>
/// default GameServiceContainer access
/// </summary>
/// <value>The services.</value>
public static GameServiceContainer services { get { return _instance.Services; } }
/// <summary>
/// provides access to the single Core/Game instance
/// </summary>
public static Core instance => _instance;
/// <summary>
/// facilitates easy access to the global Content instance for internal classes
/// </summary>
internal static Core _instance;
/// <summary>
/// internal flag used to determine if EntitySystems should be used or not
/// </summary>
internal static bool entitySystemsEnabled;
#if DEBUG
internal static long drawCalls;
TimeSpan _frameCounterElapsedTime = TimeSpan.Zero;
int _frameCounter = 0;
string _windowTitle;
#endif
Scene _scene;
Scene _nextScene;
internal SceneTransition _sceneTransition;
/// <summary>
/// used to coalesce GraphicsDeviceReset events
/// </summary>
ITimer _graphicsDeviceChangeTimer;
// globally accessible systems
FastList<IUpdatableManager> _globalManagers = new FastList<IUpdatableManager>();
CoroutineManager _coroutineManager = new CoroutineManager();
TimerManager _timerManager = new TimerManager();
/// <summary>
/// The currently active Scene. Note that if set, the Scene will not actually change until the end of the Update
/// </summary>
public static Scene scene
{
get { return _instance._scene; }
set { _instance._nextScene = value; }
}
public Core( int width = 1280, int height = 720, bool isFullScreen = false, bool enableEntitySystems = true, string windowTitle = "Nez", string contentDirectory = "Content" )
{
#if DEBUG
_windowTitle = windowTitle;
#endif
_instance = this;
emitter = new Emitter<CoreEvents>( new CoreEventsComparer() );
var graphicsManager = new GraphicsDeviceManager( this );
graphicsManager.PreferredBackBufferWidth = width;
graphicsManager.PreferredBackBufferHeight = height;
graphicsManager.IsFullScreen = isFullScreen;
graphicsManager.SynchronizeWithVerticalRetrace = true;
graphicsManager.DeviceReset += onGraphicsDeviceReset;
graphicsManager.PreferredDepthStencilFormat = DepthFormat.Depth24Stencil8;
Screen.initialize( graphicsManager );
Window.ClientSizeChanged += onGraphicsDeviceReset;
Window.OrientationChanged += onOrientationChanged;
Content.RootDirectory = contentDirectory;
content = new NezGlobalContentManager( Services, Content.RootDirectory );
IsMouseVisible = true;
IsFixedTimeStep = false;
entitySystemsEnabled = enableEntitySystems;
// setup systems
_globalManagers.add( _coroutineManager );
_globalManagers.add( new TweenManager() );
_globalManagers.add( _timerManager );
_globalManagers.add( new RenderTarget() );
}
void onOrientationChanged( object sender, EventArgs e )
{
emitter.emit( CoreEvents.OrientationChanged );
}
/// <summary>
/// this gets called whenever the screen size changes
/// </summary>
/// <param name="sender">Sender.</param>
/// <param name="e">E.</param>
protected void onGraphicsDeviceReset( object sender, EventArgs e )
{
// we coalese these to avoid spamming events
if( _graphicsDeviceChangeTimer != null )
{
_graphicsDeviceChangeTimer.reset();
}
else
{
_graphicsDeviceChangeTimer = schedule( 0.05f, false, this, t =>
{
( t.context as Core )._graphicsDeviceChangeTimer = null;
emitter.emit( CoreEvents.GraphicsDeviceReset );
} );
}
}
#region Passthroughs to Game
public static void exit()
{
_instance.Exit();
}
#endregion
#region Game overides
protected override void Initialize()
{
base.Initialize();
// prep the default Graphics system
graphicsDevice = GraphicsDevice;
var font = content.Load<BitmapFont>( "nez://Nez.Content.NezDefaultBMFont.xnb" );
Graphics.instance = new Graphics( font );
}
protected override void Update( GameTime gameTime )
{
if( pauseOnFocusLost && !IsActive )
{
SuppressDraw();
return;
}
#if DEBUG
TimeRuler.instance.startFrame();
TimeRuler.instance.beginMark( "update", Color.Green );
#endif
// update all our systems and global managers
Time.update( (float)gameTime.ElapsedGameTime.TotalSeconds );
Input.update();
for( var i = _globalManagers.length - 1; i >= 0; i-- )
_globalManagers.buffer[i].update();
if( exitOnEscapeKeypress && ( Input.isKeyDown( Keys.Escape ) || Input.gamePads[0].isButtonReleased( Buttons.Back ) ) )
{
Exit();
return;
}
if( _scene != null )
_scene.update();
if( _scene != _nextScene )
{
if( _scene != null )
_scene.end();
_scene = _nextScene;
onSceneChanged();
if( _scene != null )
_scene.begin();
}
#if DEBUG
TimeRuler.instance.endMark( "update" );
DebugConsole.instance.update();
drawCalls = 0;
#endif
#if FNA
// MonoGame only updates old-school XNA Components in Update which we dont care about. FNA's core FrameworkDispatcher needs
// Update called though so we do so here.
FrameworkDispatcher.Update();
#endif
}
protected override void Draw( GameTime gameTime )
{
if( pauseOnFocusLost && !IsActive )
return;
#if DEBUG
TimeRuler.instance.beginMark( "draw", Color.Gold );
// fps counter
_frameCounter++;
_frameCounterElapsedTime += gameTime.ElapsedGameTime;
if( _frameCounterElapsedTime >= TimeSpan.FromSeconds( 1 ) )
{
var totalMemory = ( GC.GetTotalMemory( false ) / 1048576f ).ToString( "F" );
Window.Title = string.Format( "{0} {1} fps - {2} MB", _windowTitle, _frameCounter, totalMemory );
_frameCounter = 0;
_frameCounterElapsedTime -= TimeSpan.FromSeconds( 1 );
}
#endif
if( _sceneTransition != null )
_sceneTransition.preRender( Graphics.instance );
if( _scene != null )
{
_scene.render();
#if DEBUG
if( debugRenderEnabled )
Debug.render();
#endif
// render as usual if we dont have an active SceneTransition
if( _sceneTransition == null )
_scene.postRender();
}
// special handling of SceneTransition if we have one
if( _sceneTransition != null )
{
if( _scene != null && _sceneTransition.wantsPreviousSceneRender && !_sceneTransition.hasPreviousSceneRender )
{
_scene.postRender( _sceneTransition.previousSceneRender );
if( _sceneTransition._loadsNewScene )
scene = null;
startCoroutine( _sceneTransition.onBeginTransition() );
}
else if( _scene != null )
{
_scene.postRender();
}
_sceneTransition.render( Graphics.instance );
}
#if DEBUG
TimeRuler.instance.endMark( "draw" );
DebugConsole.instance.render();
// the TimeRuler only needs to render when the DebugConsole is not open
if( !DebugConsole.instance.isOpen )
TimeRuler.instance.render();
#if !FNA
drawCalls = graphicsDevice.Metrics.DrawCount;
#endif
#endif
}
#endregion
/// <summary>
/// Called after a Scene ends, before the next Scene begins
/// </summary>
void onSceneChanged()
{
emitter.emit( CoreEvents.SceneChanged );
Time.sceneChanged();
GC.Collect();
}
/// <summary>
/// temporarily runs SceneTransition allowing one Scene to transition to another smoothly with custom effects.
/// </summary>
/// <param name="sceneTransition">Scene transition.</param>
public static T startSceneTransition<T>( T sceneTransition ) where T : SceneTransition
{
Assert.isNull( _instance._sceneTransition, "You cannot start a new SceneTransition until the previous one has completed" );
_instance._sceneTransition = sceneTransition;
return sceneTransition;
}
#region Global Managers
/// <summary>
/// adds a global manager object that will have its update method called each frame before Scene.update is called
/// </summary>
/// <returns>The global manager.</returns>
/// <param name="manager">Manager.</param>
public static void registerGlobalManager( IUpdatableManager manager )
{
_instance._globalManagers.add( manager );
}
/// <summary>
/// removes the global manager object
/// </summary>
/// <returns>The global manager.</returns>
/// <param name="manager">Manager.</param>
public static void unregisterGlobalManager( IUpdatableManager manager )
{
_instance._globalManagers.remove( manager );
}
/// <summary>
/// gets the global manager of type T
/// </summary>
/// <returns>The global manager.</returns>
/// <typeparam name="T">The 1st type parameter.</typeparam>
public static T getGlobalManager<T>() where T : class, IUpdatableManager
{
for( var i = 0; i < _instance._globalManagers.length; i++ )
{
if( _instance._globalManagers.buffer[i] is T )
return _instance._globalManagers.buffer[i] as T;
}
return null;
}
#endregion
#region Systems access
/// <summary>
/// starts a coroutine. Coroutines can yeild ints/floats to delay for seconds or yeild to other calls to startCoroutine.
/// Yielding null will make the coroutine get ticked the next frame.
/// </summary>
/// <returns>The coroutine.</returns>
/// <param name="enumerator">Enumerator.</param>
public static ICoroutine startCoroutine( IEnumerator enumerator )
{
return _instance._coroutineManager.startCoroutine( enumerator );
}
/// <summary>
/// schedules a one-time or repeating timer that will call the passed in Action
/// </summary>
/// <param name="timeInSeconds">Time in seconds.</param>
/// <param name="repeats">If set to <c>true</c> repeats.</param>
/// <param name="context">Context.</param>
/// <param name="onTime">On time.</param>
public static ITimer schedule( float timeInSeconds, bool repeats, object context, Action<ITimer> onTime )
{
return _instance._timerManager.schedule( timeInSeconds, repeats, context, onTime );
}
/// <summary>
/// schedules a one-time timer that will call the passed in Action after timeInSeconds
/// </summary>
/// <param name="timeInSeconds">Time in seconds.</param>
/// <param name="context">Context.</param>
/// <param name="onTime">On time.</param>
public static ITimer schedule( float timeInSeconds, object context, Action<ITimer> onTime )
{
return _instance._timerManager.schedule( timeInSeconds, false, context, onTime );
}
/// <summary>
/// schedules a one-time or repeating timer that will call the passed in Action
/// </summary>
/// <param name="timeInSeconds">Time in seconds.</param>
/// <param name="repeats">If set to <c>true</c> repeats.</param>
/// <param name="onTime">On time.</param>
public static ITimer schedule( float timeInSeconds, bool repeats, Action<ITimer> onTime )
{
return _instance._timerManager.schedule( timeInSeconds, repeats, null, onTime );
}
/// <summary>
/// schedules a one-time timer that will call the passed in Action after timeInSeconds
/// </summary>
/// <param name="timeInSeconds">Time in seconds.</param>
/// <param name="onTime">On time.</param>
public static ITimer schedule( float timeInSeconds, Action<ITimer> onTime )
{
return _instance._timerManager.schedule( timeInSeconds, false, null, onTime );
}
#endregion
}
}
| 28.6 | 176 | 0.697324 | [
"Apache-2.0",
"MIT"
] | tullrich/Nez | Nez.Portable/Core.cs | 13,158 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using BenchmarkDotNet.Columns;
using BenchmarkDotNet.Configs;
using BenchmarkDotNet.Diagnosers;
using BenchmarkDotNet.Engines;
using BenchmarkDotNet.Jobs;
using BenchmarkDotNet.Validators;
namespace Microsoft.AspNetCore.Server.Kestrel.Performance
{
public class CoreConfig : ManualConfig
{
public CoreConfig()
{
Add(JitOptimizationsValidator.FailOnError);
Add(MemoryDiagnoser.Default);
Add(StatisticColumn.OperationsPerSecond);
Add(Job.Default
.With(BenchmarkDotNet.Environments.Runtime.Core)
.WithRemoveOutliers(false)
.With(new GcMode() { Server = true })
.With(RunStrategy.Throughput)
.WithLaunchCount(3)
.WithWarmupCount(5)
.WithTargetCount(10));
}
}
}
| 32 | 111 | 0.654297 | [
"Apache-2.0"
] | PHeonix25/KestrelHttpServer | test/Microsoft.AspNetCore.Server.Kestrel.Performance/configs/CoreConfig.cs | 1,026 | C# |
/*******************************************************************************
* Copyright 2012-2019 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.
* *****************************************************************************
*
* AWS Tools for Windows (TM) PowerShell (TM)
*
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation;
using System.Text;
using Amazon.PowerShell.Common;
using Amazon.Runtime;
using Amazon.KeyManagementService;
using Amazon.KeyManagementService.Model;
namespace Amazon.PowerShell.Cmdlets.KMS
{
/// <summary>
/// Imports key material into an existing AWS KMS customer master key (CMK) that was created
/// without key material. You cannot perform this operation on a CMK in a different AWS
/// account. For more information about creating CMKs with no key material and then importing
/// key material, see <a href="https://docs.aws.amazon.com/kms/latest/developerguide/importing-keys.html">Importing
/// Key Material</a> in the <i>AWS Key Management Service Developer Guide</i>.
///
///
/// <para>
/// Before using this operation, call <a>GetParametersForImport</a>. Its response includes
/// a public key and an import token. Use the public key to encrypt the key material.
/// Then, submit the import token from the same <code>GetParametersForImport</code> response.
/// </para><para>
/// When calling this operation, you must specify the following values:
/// </para><ul><li><para>
/// The key ID or key ARN of a CMK with no key material. Its <code>Origin</code> must
/// be <code>EXTERNAL</code>.
/// </para><para>
/// To create a CMK with no key material, call <a>CreateKey</a> and set the value of its
/// <code>Origin</code> parameter to <code>EXTERNAL</code>. To get the <code>Origin</code>
/// of a CMK, call <a>DescribeKey</a>.)
/// </para></li><li><para>
/// The encrypted key material. To get the public key to encrypt the key material, call
/// <a>GetParametersForImport</a>.
/// </para></li><li><para>
/// The import token that <a>GetParametersForImport</a> returned. This token and the public
/// key used to encrypt the key material must have come from the same response.
/// </para></li><li><para>
/// Whether the key material expires and if so, when. If you set an expiration date, you
/// can change it only by reimporting the same key material and specifying a new expiration
/// date. If the key material expires, AWS KMS deletes the key material and the CMK becomes
/// unusable. To use the CMK again, you must reimport the same key material.
/// </para></li></ul><para>
/// When this operation is successful, the key state of the CMK changes from <code>PendingImport</code>
/// to <code>Enabled</code>, and you can use the CMK. After you successfully import key
/// material into a CMK, you can reimport the same key material into that CMK, but you
/// cannot import different key material.
/// </para><para>
/// The result of this operation varies with the key state of the CMK. For details, see
/// <a href="https://docs.aws.amazon.com/kms/latest/developerguide/key-state.html">How
/// Key State Affects Use of a Customer Master Key</a> in the <i>AWS Key Management Service
/// Developer Guide</i>.
/// </para>
/// </summary>
[Cmdlet("Import", "KMSKeyMaterial", SupportsShouldProcess = true, ConfirmImpact = ConfirmImpact.Medium)]
[OutputType("None")]
[AWSCmdlet("Calls the AWS Key Management Service ImportKeyMaterial API operation.", Operation = new[] {"ImportKeyMaterial"}, SelectReturnType = typeof(Amazon.KeyManagementService.Model.ImportKeyMaterialResponse))]
[AWSCmdletOutput("None or Amazon.KeyManagementService.Model.ImportKeyMaterialResponse",
"This cmdlet does not generate any output." +
"The service response (type Amazon.KeyManagementService.Model.ImportKeyMaterialResponse) can be referenced from properties attached to the cmdlet entry in the $AWSHistory stack."
)]
public partial class ImportKMSKeyMaterialCmdlet : AmazonKeyManagementServiceClientCmdlet, IExecutor
{
#region Parameter EncryptedKeyMaterial
/// <summary>
/// <para>
/// <para>The encrypted key material to import. It must be encrypted with the public key that
/// you received in the response to a previous <a>GetParametersForImport</a> request,
/// using the wrapping algorithm that you specified in that request.</para>
/// </para>
/// <para>The cmdlet will automatically convert the supplied parameter of type string, string[], System.IO.FileInfo or System.IO.Stream to byte[] before supplying it to the service.</para>
/// </summary>
#if !MODULAR
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
#else
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true, Mandatory = true)]
[System.Management.Automation.AllowNull]
#endif
[Amazon.PowerShell.Common.AWSRequiredParameter]
[Amazon.PowerShell.Common.MemoryStreamParameterConverter]
public byte[] EncryptedKeyMaterial { get; set; }
#endregion
#region Parameter ExpirationModel
/// <summary>
/// <para>
/// <para>Specifies whether the key material expires. The default is <code>KEY_MATERIAL_EXPIRES</code>,
/// in which case you must include the <code>ValidTo</code> parameter. When this parameter
/// is set to <code>KEY_MATERIAL_DOES_NOT_EXPIRE</code>, you must omit the <code>ValidTo</code>
/// parameter.</para>
/// </para>
/// </summary>
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
[AWSConstantClassSource("Amazon.KeyManagementService.ExpirationModelType")]
public Amazon.KeyManagementService.ExpirationModelType ExpirationModel { get; set; }
#endregion
#region Parameter ImportToken
/// <summary>
/// <para>
/// <para>The import token that you received in the response to a previous <a>GetParametersForImport</a>
/// request. It must be from the same response that contained the public key that you
/// used to encrypt the key material.</para>
/// </para>
/// <para>The cmdlet will automatically convert the supplied parameter of type string, string[], System.IO.FileInfo or System.IO.Stream to byte[] before supplying it to the service.</para>
/// </summary>
#if !MODULAR
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
#else
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true, Mandatory = true)]
[System.Management.Automation.AllowNull]
#endif
[Amazon.PowerShell.Common.AWSRequiredParameter]
[Amazon.PowerShell.Common.MemoryStreamParameterConverter]
public byte[] ImportToken { get; set; }
#endregion
#region Parameter KeyId
/// <summary>
/// <para>
/// <para>The identifier of the CMK to import the key material into. The CMK's <code>Origin</code>
/// must be <code>EXTERNAL</code>.</para><para>Specify the key ID or the Amazon Resource Name (ARN) of the CMK.</para><para>For example:</para><ul><li><para>Key ID: <code>1234abcd-12ab-34cd-56ef-1234567890ab</code></para></li><li><para>Key ARN: <code>arn:aws:kms:us-east-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab</code></para></li></ul><para>To get the key ID and key ARN for a CMK, use <a>ListKeys</a> or <a>DescribeKey</a>.</para>
/// </para>
/// </summary>
#if !MODULAR
[System.Management.Automation.Parameter(Position = 0, ValueFromPipelineByPropertyName = true, ValueFromPipeline = true)]
#else
[System.Management.Automation.Parameter(Position = 0, ValueFromPipelineByPropertyName = true, ValueFromPipeline = true, Mandatory = true)]
[System.Management.Automation.AllowEmptyString]
[System.Management.Automation.AllowNull]
#endif
[Amazon.PowerShell.Common.AWSRequiredParameter]
public System.String KeyId { get; set; }
#endregion
#region Parameter ValidTo
/// <summary>
/// <para>
/// <para>The time at which the imported key material expires. When the key material expires,
/// AWS KMS deletes the key material and the CMK becomes unusable. You must omit this
/// parameter when the <code>ExpirationModel</code> parameter is set to <code>KEY_MATERIAL_DOES_NOT_EXPIRE</code>.
/// Otherwise it is required.</para>
/// </para>
/// </summary>
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
public System.DateTime? ValidTo { get; set; }
#endregion
#region Parameter Select
/// <summary>
/// Use the -Select parameter to control the cmdlet output. The cmdlet doesn't have a return value by default.
/// Specifying -Select '*' will result in the cmdlet returning the whole service response (Amazon.KeyManagementService.Model.ImportKeyMaterialResponse).
/// Specifying -Select '^ParameterName' will result in the cmdlet returning the selected cmdlet parameter value.
/// </summary>
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
public string Select { get; set; } = "*";
#endregion
#region Parameter PassThru
/// <summary>
/// Changes the cmdlet behavior to return the value passed to the KeyId parameter.
/// The -PassThru parameter is deprecated, use -Select '^KeyId' instead. This parameter will be removed in a future version.
/// </summary>
[System.Obsolete("The -PassThru parameter is deprecated, use -Select '^KeyId' instead. This parameter will be removed in a future version.")]
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
public SwitchParameter PassThru { get; set; }
#endregion
#region Parameter Force
/// <summary>
/// This parameter overrides confirmation prompts to force
/// the cmdlet to continue its operation. This parameter should always
/// be used with caution.
/// </summary>
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
public SwitchParameter Force { get; set; }
#endregion
protected override void ProcessRecord()
{
base.ProcessRecord();
var resourceIdentifiersText = FormatParameterValuesForConfirmationMsg(nameof(this.KeyId), MyInvocation.BoundParameters);
if (!ConfirmShouldProceed(this.Force.IsPresent, resourceIdentifiersText, "Import-KMSKeyMaterial (ImportKeyMaterial)"))
{
return;
}
var context = new CmdletContext();
// allow for manipulation of parameters prior to loading into context
PreExecutionContextLoad(context);
#pragma warning disable CS0618, CS0612 //A class member was marked with the Obsolete attribute
if (ParameterWasBound(nameof(this.Select)))
{
context.Select = CreateSelectDelegate<Amazon.KeyManagementService.Model.ImportKeyMaterialResponse, ImportKMSKeyMaterialCmdlet>(Select) ??
throw new System.ArgumentException("Invalid value for -Select parameter.", nameof(this.Select));
if (this.PassThru.IsPresent)
{
throw new System.ArgumentException("-PassThru cannot be used when -Select is specified.", nameof(this.Select));
}
}
else if (this.PassThru.IsPresent)
{
context.Select = (response, cmdlet) => this.KeyId;
}
#pragma warning restore CS0618, CS0612 //A class member was marked with the Obsolete attribute
context.EncryptedKeyMaterial = this.EncryptedKeyMaterial;
#if MODULAR
if (this.EncryptedKeyMaterial == null && ParameterWasBound(nameof(this.EncryptedKeyMaterial)))
{
WriteWarning("You are passing $null as a value for parameter EncryptedKeyMaterial which is marked as required. In case you believe this parameter was incorrectly marked as required, report this by opening an issue at https://github.com/aws/aws-tools-for-powershell/issues.");
}
#endif
context.ExpirationModel = this.ExpirationModel;
context.ImportToken = this.ImportToken;
#if MODULAR
if (this.ImportToken == null && ParameterWasBound(nameof(this.ImportToken)))
{
WriteWarning("You are passing $null as a value for parameter ImportToken which is marked as required. In case you believe this parameter was incorrectly marked as required, report this by opening an issue at https://github.com/aws/aws-tools-for-powershell/issues.");
}
#endif
context.KeyId = this.KeyId;
#if MODULAR
if (this.KeyId == null && ParameterWasBound(nameof(this.KeyId)))
{
WriteWarning("You are passing $null as a value for parameter KeyId which is marked as required. In case you believe this parameter was incorrectly marked as required, report this by opening an issue at https://github.com/aws/aws-tools-for-powershell/issues.");
}
#endif
context.ValidTo = this.ValidTo;
// allow further manipulation of loaded context prior to processing
PostExecutionContextLoad(context);
var output = Execute(context) as CmdletOutput;
ProcessOutput(output);
}
#region IExecutor Members
public object Execute(ExecutorContext context)
{
System.IO.MemoryStream _EncryptedKeyMaterialStream = null;
System.IO.MemoryStream _ImportTokenStream = null;
try
{
var cmdletContext = context as CmdletContext;
// create request
var request = new Amazon.KeyManagementService.Model.ImportKeyMaterialRequest();
if (cmdletContext.EncryptedKeyMaterial != null)
{
_EncryptedKeyMaterialStream = new System.IO.MemoryStream(cmdletContext.EncryptedKeyMaterial);
request.EncryptedKeyMaterial = _EncryptedKeyMaterialStream;
}
if (cmdletContext.ExpirationModel != null)
{
request.ExpirationModel = cmdletContext.ExpirationModel;
}
if (cmdletContext.ImportToken != null)
{
_ImportTokenStream = new System.IO.MemoryStream(cmdletContext.ImportToken);
request.ImportToken = _ImportTokenStream;
}
if (cmdletContext.KeyId != null)
{
request.KeyId = cmdletContext.KeyId;
}
if (cmdletContext.ValidTo != null)
{
request.ValidTo = cmdletContext.ValidTo.Value;
}
CmdletOutput output;
// issue call
var client = Client ?? CreateClient(_CurrentCredentials, _RegionEndpoint);
try
{
var response = CallAWSServiceOperation(client, request);
object pipelineOutput = null;
pipelineOutput = cmdletContext.Select(response, this);
output = new CmdletOutput
{
PipelineOutput = pipelineOutput,
ServiceResponse = response
};
}
catch (Exception e)
{
output = new CmdletOutput { ErrorResponse = e };
}
return output;
}
finally
{
if( _EncryptedKeyMaterialStream != null)
{
_EncryptedKeyMaterialStream.Dispose();
}
if( _ImportTokenStream != null)
{
_ImportTokenStream.Dispose();
}
}
}
public ExecutorContext CreateContext()
{
return new CmdletContext();
}
#endregion
#region AWS Service Operation Call
private Amazon.KeyManagementService.Model.ImportKeyMaterialResponse CallAWSServiceOperation(IAmazonKeyManagementService client, Amazon.KeyManagementService.Model.ImportKeyMaterialRequest request)
{
Utils.Common.WriteVerboseEndpointMessage(this, client.Config, "AWS Key Management Service", "ImportKeyMaterial");
try
{
#if DESKTOP
return client.ImportKeyMaterial(request);
#elif CORECLR
return client.ImportKeyMaterialAsync(request).GetAwaiter().GetResult();
#else
#error "Unknown build edition"
#endif
}
catch (AmazonServiceException exc)
{
var webException = exc.InnerException as System.Net.WebException;
if (webException != null)
{
throw new Exception(Utils.Common.FormatNameResolutionFailureMessage(client.Config, webException.Message), webException);
}
throw;
}
}
#endregion
internal partial class CmdletContext : ExecutorContext
{
public byte[] EncryptedKeyMaterial { get; set; }
public Amazon.KeyManagementService.ExpirationModelType ExpirationModel { get; set; }
public byte[] ImportToken { get; set; }
public System.String KeyId { get; set; }
public System.DateTime? ValidTo { get; set; }
public System.Func<Amazon.KeyManagementService.Model.ImportKeyMaterialResponse, ImportKMSKeyMaterialCmdlet, object> Select { get; set; } =
(response, cmdlet) => null;
}
}
}
| 51.087071 | 454 | 0.621837 | [
"Apache-2.0"
] | 5u5hma/aws-tools-for-powershell | modules/AWSPowerShell/Cmdlets/KeyManagementService/Basic/Import-KMSKeyMaterial-Cmdlet.cs | 19,362 | C# |
using System;
using System.IO;
using System.Linq;
using UnityEditor;
using UnityEditor.Build.Reporting;
using UnityEngine;
namespace FlutterUnityPlugin.Editor
{
public class Build : UnityEditor.Editor
{
private static readonly string ProjectPath = Path.GetFullPath(Path.Combine(Application.dataPath, ".."));
private static readonly string IOSExportPath =
Path.GetFullPath(Path.Combine(ProjectPath, "../../ios/UnityProject"));
private static readonly string AndroidExportPath =
Path.GetFullPath(Path.Combine(ProjectPath, "../../android/unityExport"));
[MenuItem("Flutter/Export iOS", false, 1)]
public static void BuildIOSForRelease()
{
if (Directory.Exists(IOSExportPath))
{
Directory.Delete(IOSExportPath, true);
}
PlayerSettings.iOS.sdkVersion = iOSSdkVersion.DeviceSDK;
EditorUserBuildSettings.iOSBuildConfigType = iOSBuildType.Release;
var report = BuildPipeline.BuildPlayer(
GetEnabledScenes(), IOSExportPath, BuildTarget.iOS, BuildOptions.None);
if (report.summary.result != BuildResult.Succeeded)
{
throw new Exception(report.summary.result.ToString());
}
Debug.Log($"IOS Build Succeeded. output path: {report.summary.outputPath}¥n" +
$"Build time: {report.summary.totalTime.Seconds} seconds");
}
[MenuItem("Flutter/Export Android", false, 2)]
public static void BuildAndroid()
{
if (Directory.Exists(AndroidExportPath))
{
Directory.Delete(AndroidExportPath, true);
}
EditorUserBuildSettings.exportAsGoogleAndroidProject = true;
var report = BuildPipeline.BuildPlayer(
GetEnabledScenes(), AndroidExportPath, BuildTarget.Android, BuildOptions.None);
if (report.summary.result != BuildResult.Succeeded)
{
throw new Exception(report.summary.result.ToString());
}
Debug.Log($"Android Build Succeeded. output path: {report.summary.outputPath}¥n" +
$"Build time: {report.summary.totalTime.Seconds} seconds");
}
private static string[] GetEnabledScenes()
{
return EditorBuildSettings.scenes.Where(s => s.enabled).Select(s => s.path).ToArray();
}
}
} | 35.6 | 112 | 0.616372 | [
"BSD-3-Clause"
] | gatari/flutter-unity | example/unity/flutter_unity_example_unity/Packages/FlutterUnityPlugin/Editor/Build.cs | 2,496 | C# |
using Microsoft.EntityFrameworkCore.Migrations;
namespace RecordCollection.Migrations
{
public partial class DataSeeding : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.InsertData(
table: "Genres",
columns: new[] { "GenreId", "Name" },
values: new object[] { 1, "Rock" });
migrationBuilder.InsertData(
table: "Genres",
columns: new[] { "GenreId", "Name" },
values: new object[] { 2, "Country" });
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DeleteData(
table: "Genres",
keyColumn: "GenreId",
keyValue: 1);
migrationBuilder.DeleteData(
table: "Genres",
keyColumn: "GenreId",
keyValue: 2);
}
}
}
| 29.029412 | 71 | 0.51773 | [
"MIT"
] | Sudolphus/RecordCollection.Solution | RecordCollection/Migrations/20200806164940_DataSeeding.cs | 989 | C# |
#pragma checksum "..\..\..\App.xaml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "6188313EFFC09F9BF101E21C1A12ECC1037F3684"
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Diagnostics;
using System.Windows;
using System.Windows.Automation;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Controls.Ribbon;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Markup;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Effects;
using System.Windows.Media.Imaging;
using System.Windows.Media.Media3D;
using System.Windows.Media.TextFormatting;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Shell;
using YoutubeDownloader;
namespace YoutubeDownloader {
/// <summary>
/// App
/// </summary>
public partial class App : System.Windows.Application {
private bool _contentLoaded;
/// <summary>
/// InitializeComponent
/// </summary>
[System.Diagnostics.DebuggerNonUserCodeAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "5.0.4.0")]
public void InitializeComponent() {
if (_contentLoaded) {
return;
}
_contentLoaded = true;
#line 5 "..\..\..\App.xaml"
this.StartupUri = new System.Uri("MainWindow.xaml", System.UriKind.Relative);
#line default
#line hidden
System.Uri resourceLocater = new System.Uri("/YoutubeDownloader.Wpf.App;component/app.xaml", System.UriKind.Relative);
#line 1 "..\..\..\App.xaml"
System.Windows.Application.LoadComponent(this, resourceLocater);
#line default
#line hidden
}
/// <summary>
/// Application Entry Point.
/// </summary>
[System.STAThreadAttribute()]
[System.Diagnostics.DebuggerNonUserCodeAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "5.0.4.0")]
public static void Main() {
YoutubeDownloader.App app = new YoutubeDownloader.App();
app.InitializeComponent();
app.Run();
}
}
}
| 32.917647 | 130 | 0.605075 | [
"MIT"
] | sste9512/YoutubeDownloader | YoutubeDownloader.Wpf.App/obj/Debug/net5.0-windows/App.g.cs | 2,800 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations.Schema;
namespace RankDit.Models
{
[Table("Posts")]
public class Post
{
public string PostID { get; set; }
public string Titel { get; set; }
public string Description { get; set; }
public string Place { get; set; }
public string CountryID { get; set; }
public string VideoID { get; set; }
public bool IsActive { get; set; }
public int RoundID { get; set; }
public Post()
{
}
}
}
| 24.115385 | 51 | 0.606061 | [
"MIT"
] | amera7md/Rankdit | Models/Post.cs | 627 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.