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.Threading.Tasks;
using Red.Interfaces;
namespace Red.Extensions
{
/// <summary>
/// Extension to RedRequests, to parse body to object of specified type
/// </summary>
public static class BodyParserExtensions
{
/// <summary>
/// Returns the body deserialized or parsed to specified type, if possible, default if not
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public static async Task<T> ParseBodyAsync<T>(this Request request)
{
var bodyparser = request.ServerPlugins.Get<IBodyParser>();
return await bodyparser.Parse<T>(request);
}
}
} | 31.909091 | 102 | 0.612536 | [
"MIT"
] | firesharkstudios/Red | src/RedHttpServer/Extensions/BodyParserExtensions.cs | 702 | C# |
using System.Collections.Generic;
using System.Linq;
using OurUmbraco.Our.Extensions;
using OurUmbraco.Our.Services;
using Umbraco.Core;
namespace OurUmbraco.Project.uVersion
{
public class UVersion
{
public string Key { get; private set; }
public string Name { get; private set; }
public System.Version FullVersion { get; private set; }
public IEnumerable<UVersion> GetAllVersions()
{
var releasesService = new ReleasesService();
var releases = releasesService.GetReleasesCache()
.Where(x => x.FullVersion.Major > 6 && x.FullVersion.Build == 0)
.OrderByDescending(x => x.FullVersion).ToList();
var versions = new List<UVersion>();
foreach (var release in releases)
{
versions.Add(new UVersion
{
Name = release.FullVersion.VersionName(),
Key = release.FullVersion.VersionKey(),
FullVersion = release.FullVersion
});
}
return versions;
}
public IEnumerable<System.Version> GetAllAsVersions()
{
var versions = new UVersion();
var all = versions.GetAllVersions()
.Select(x => x.Name.Replace(".x", ""))
.Select(x =>
{
return System.Version.TryParse(x, out var version) ? version : null;
})
.WhereNotNull()
.OrderByDescending(x => x);
return all;
}
}
} | 32.27451 | 88 | 0.521871 | [
"MIT"
] | KevinJump/OurUmbraco | OurUmbraco/Project/uVersion/uVersion.cs | 1,648 | C# |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;
namespace EFCore_Ex.Pages
{
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
[IgnoreAntiforgeryToken]
public class ErrorModel : PageModel
{
public string RequestId { get; set; }
public bool ShowRequestId => !string.IsNullOrEmpty(RequestId);
private readonly ILogger<ErrorModel> _logger;
public ErrorModel(ILogger<ErrorModel> logger)
{
_logger = logger;
}
public void OnGet()
{
RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier;
}
}
}
| 26.393939 | 89 | 0.659013 | [
"MIT"
] | bpbpublications/Cross-Platform-Modern-Apps-with-VS-Code | Chapter 7 Code Samples/EFCore_Ex/EFCore_Ex/Pages/Error.cshtml.cs | 871 | C# |
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Text;
using System.Text;
namespace MyTemplate
{
internal static class SourceGeneratorContextExtension
{
public static void AddCode(this GeneratorExecutionContext context, string hint_name, string code)
{
context.AddSource(hint_name.Replace("<", "_").Replace(">", "_"), SourceText.From(code.NormalizeWhitespace(), Encoding.UTF8));
}
}
} | 32.642857 | 138 | 0.68709 | [
"MIT"
] | stefanloerwald/roslyn-templates | templates/SourceGenerator/MyTemplate/SourceGeneratorContextExtension.cs | 459 | C# |
using Microsoft.EntityFrameworkCore;
using Open.Nat;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using TournamentAssistantCore.Discord;
using TournamentAssistantCore.Discord.Helpers;
using TournamentAssistantCore.Discord.Services;
using TournamentAssistantShared;
using TournamentAssistantShared.Models;
using TournamentAssistantShared.Models.Packets;
using TournamentAssistantShared.Sockets;
using TournamentAssistantShared.Utilities;
using static TournamentAssistantShared.Models.GameplayModifiers;
using static TournamentAssistantShared.Models.Packets.Response;
using static TournamentAssistantShared.Models.PlayerSpecificSettings;
using static TournamentAssistantShared.Constants;
namespace TournamentAssistantCore
{
public class SystemServer : INotifyPropertyChanged
{
Server server;
WsServer wsServer;
public event Func<User, Task> UserConnected;
public event Func<User, Task> UserDisconnected;
public event Func<User, Task> UserInfoUpdated;
public event Func<Match, Task> MatchInfoUpdated;
public event Func<Match, Task> MatchCreated;
public event Func<Match, Task> MatchDeleted;
public event Func<SongFinished, Task> PlayerFinishedSong;
public event Func<Acknowledgement, Guid, Task> AckReceived;
public event PropertyChangedEventHandler PropertyChanged;
public void NotifyPropertyChanged(string propertyName) =>
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
//Tournament State can be modified by ANY client thread, so definitely needs thread-safe accessing
private State _state;
public State State
{
get { return _state; }
set
{
_state = value;
NotifyPropertyChanged(nameof(State));
}
}
public User Self { get; set; }
public QualifierBot QualifierBot { get; private set; }
public Discord.Database.QualifierDatabaseContext Database { get; private set; }
//Reference to self as a server, if we are eligible for the Master Lists
public CoreServer CoreServer { get; private set; }
//Server settings
private Config config;
private string address;
private int port;
private ServerSettings settings;
private string botToken;
//Update checker
private CancellationTokenSource updateCheckToken = new();
//Overlay settings
private int overlayPort;
public SystemServer(string botTokenArg = null)
{
config = new Config("serverConfig.json");
var portValue = config.GetString("port");
if (portValue == string.Empty)
{
portValue = "2052";
config.SaveString("port", portValue);
}
var nameValue = config.GetString("serverName");
if (nameValue == string.Empty)
{
nameValue = "Default Server Name";
config.SaveString("serverName", nameValue);
}
var passwordValue = config.GetString("password");
if (passwordValue == string.Empty || passwordValue == "[Password]")
{
passwordValue = string.Empty;
config.SaveString("password", "[Password]");
}
var addressValue = config.GetString("serverAddress");
if (addressValue == string.Empty || addressValue == "[serverAddress]")
{
addressValue = "[serverAddress]";
config.SaveString("serverAddress", addressValue);
}
var scoreUpdateFrequencyValue = config.GetString("scoreUpdateFrequency");
if (scoreUpdateFrequencyValue == string.Empty)
{
scoreUpdateFrequencyValue = "30";
config.SaveString("scoreUpdateFrequency", scoreUpdateFrequencyValue);
}
var overlayPortValue = config.GetString("overlayPort");
if (overlayPortValue == string.Empty || overlayPortValue == "[overlayPort]")
{
overlayPortValue = "2053";
config.SaveString("overlayPort", overlayPortValue);
}
var botTokenValue = config.GetString("botToken");
if (botTokenValue == string.Empty || botTokenValue == "[botToken]")
{
botTokenValue = botTokenArg;
config.SaveString("botToken", "[botToken]");
}
var bannedModsValue = config.GetBannedMods();
if (bannedModsValue.Length == 0)
{
bannedModsValue = new string[]
{"IntroSkip", "AutoPauseStealth", "NoteSliceVisualizer", "SongChartVisualizer", "Custom Notes"};
config.SaveBannedMods(bannedModsValue);
}
var enableTeamsValue = config.GetBoolean("enableTeams");
var teamsValue = config.GetTeams();
if (teamsValue.Length == 0)
{
//Default teams
teamsValue = new Team[]
{
new Team()
{
Id = Guid.NewGuid().ToString(),
Name = "Team Green"
},
new Team()
{
Id = Guid.NewGuid().ToString(),
Name = "Team Spicy"
}
};
config.SaveTeams(teamsValue);
}
settings = new ServerSettings
{
ServerName = nameValue,
Password = passwordValue,
EnableTeams = enableTeamsValue,
ScoreUpdateFrequency = Convert.ToInt32(scoreUpdateFrequencyValue),
};
settings.Teams.AddRange(teamsValue);
settings.BannedMods.AddRange(bannedModsValue);
address = addressValue;
port = int.Parse(portValue);
overlayPort = int.Parse(overlayPortValue);
botToken = botTokenValue;
}
//Blocks until socket server begins to start (note that this is not "until server is started")
public async void Start()
{
State = new State();
State.ServerSettings = settings;
State.KnownHosts.AddRange(config.GetHosts());
Logger.Info($"Running on {Update.osType}");
//Check for updates
Logger.Info("Checking for updates...");
var newVersion = await Update.GetLatestRelease();
if (System.Version.Parse(Constants.Version) < newVersion)
{
Logger.Error(
$"Update required! You are on \'{Constants.Version}\', new version is \'{newVersion}\'");
Logger.Info("Attempting AutoUpdate...");
bool UpdateSuccess = await Update.AttemptAutoUpdate();
if (!UpdateSuccess)
{
Logger.Error("AutoUpdate Failed. Please Update Manually. Shutting down");
//Moon's note / TODO: Can't do this from shared. Screw the threads
//SystemHost.MainThreadStop.Set(); //Release the main thread, so we don't leave behind threads
Environment.Exit(0);
}
else
{
Logger.Warning("Update was successful, exitting...");
//SystemHost.MainThreadStop.Set(); //Release the main thread, so we don't leave behind threads
Environment.Exit(0);
}
}
else Logger.Success($"You are on the most recent version! ({Constants.Version})");
if (overlayPort != 0)
{
OpenPort(overlayPort);
wsServer = new WsServer(overlayPort);
wsServer.PacketReceived += Server_PacketReceived;
wsServer.ClientConnected += Server_ClientConnected;
wsServer.ClientDisconnected += Server_ClientDisconnected;
#pragma warning disable CS4014
Task.Run(wsServer.Start);
#pragma warning restore CS4014
}
//If we have a token, start a qualifier bot
if (!string.IsNullOrEmpty(botToken) && botToken != "[botToken]")
{
//We need to await this so the DI framework has time to load the database service
QualifierBot = new QualifierBot(botToken: botToken, server: this);
await QualifierBot.Start();
}
//Set up the database
if (QualifierBot != null)
{
Database = QualifierBot.Database;
}
else
{
//If the bot's not running, we need to start the service manually
var service = new DatabaseService();
Database = service.DatabaseContext;
}
//Translate Event and Songs from database to model format
var events = Database.Events.Where(x => !x.Old);
Func<string, List<GameplayParameters>> getSongsForEvent = (string eventId) =>
{
return Database.Songs.Where(x => !x.Old && x.EventId == eventId).Select(x => new GameplayParameters
{
Beatmap = new Beatmap
{
LevelId = x.LevelId,
Characteristic = new Characteristic
{
SerializedName = x.Characteristic
},
Difficulty = x.BeatmapDifficulty,
Name = x.Name
},
GameplayModifiers = new GameplayModifiers
{
Options = (GameOptions)x.GameOptions
},
PlayerSettings = new PlayerSpecificSettings
{
Options = (PlayerOptions)x.PlayerOptions
}
}).ToList() ?? new List<GameplayParameters> { };
};
State.Events.AddRange(events
.Select(x => Database.ConvertDatabaseToModel(getSongsForEvent(x.EventId).ToArray(), x)).ToArray());
//Give our new server a sense of self :P
Self = new User()
{
Id = Guid.Empty.ToString(),
Name = "HOST"
};
async Task scrapeServersAndStart(CoreServer core)
{
CoreServer = core ?? new CoreServer
{
Address = "127.0.0.1",
Port = 0,
Name = "Unregistered Server"
};
//Scrape hosts. Unreachable hosts will be removed
Logger.Info("Reaching out to other hosts for updated Master Lists...");
//Commented out is the code that makes this act as a mesh network
//var hostStatePairs = await HostScraper.ScrapeHosts(State.KnownHosts, settings.ServerName, 0, core);
//The uncommented duplicate here makes this act as a hub and spoke network, since MasterServer is the domain of the master server
var hostStatePairs = await HostScraper.ScrapeHosts(
State.KnownHosts.Where(x => x.Address.Contains(MasterServer)).ToArray(),
settings.ServerName,
0,
core);
hostStatePairs = hostStatePairs.Where(x => x.Value != null).ToDictionary(x => x.Key, x => x.Value);
var newHostList = hostStatePairs.Values.Where(x => x.KnownHosts != null).SelectMany(x => x.KnownHosts).Union(hostStatePairs.Keys, new CoreServerEqualityComparer());
State.KnownHosts.Clear();
State.KnownHosts.AddRange(newHostList.ToArray());
//The current server will always remove itself from its list thanks to it not being up when
//it starts. Let's fix that. Also, add back the Master Server if it was removed.
//We accomplish this by triggering the default-on-empty function of GetHosts()
if (State.KnownHosts.Count == 0) State.KnownHosts.AddRange(config.GetHosts());
if (core != null)
{
State.KnownHosts.AddRange(State.KnownHosts.Union(new CoreServer[] { core }, new CoreServerEqualityComparer()).ToArray());
}
config.SaveHosts(State.KnownHosts.ToArray());
Logger.Info("Server list updated.");
OpenPort(port);
server = new Server(port);
server.PacketReceived += Server_PacketReceived;
server.ClientConnected += Server_ClientConnected;
server.ClientDisconnected += Server_ClientDisconnected;
server.Start();
//Start a regular check for updates
Update.PollForUpdates(() =>
{
server.Shutdown();
//SystemHost.MainThreadStop.Set(); //Release the main thread, so we don't leave behind threads
Environment.Exit(0);
}, updateCheckToken.Token);
}
//Verify that the provided address points to our server
if (IPAddress.TryParse(address, out _))
{
Logger.Warning(
$"\'{address}\' seems to be an IP address. You'll need a domain pointed to your server for it to be added to the Master Lists");
await scrapeServersAndStart(null);
}
else if (address != "[serverAddress]")
{
Logger.Info("Verifying that \'serverAddress\' points to this server...");
var connected = new AutoResetEvent(false);
var keyName = $"{address}:{port}";
bool verified = false;
var verificationServer = new Server(port);
verificationServer.PacketReceived += (_, packet) =>
{
if (packet.packetCase == Packet.packetOneofCase.Connect)
{
var connect = packet.Connect;
if (connect.Name == keyName)
{
verified = true;
connected.Set();
}
}
return Task.CompletedTask;
};
verificationServer.Start();
var client = new TemporaryClient(address, port, keyName, "0", User.ClientTypes.TemporaryConnection);
await client.Start();
connected.WaitOne(6000);
client.Shutdown();
verificationServer.Shutdown();
if (verified)
{
Logger.Success(
"Verified address! Server should be added to the Lists of all servers that were scraped for hosts");
await scrapeServersAndStart(new CoreServer
{
Address = address,
Port = port,
Name = State.ServerSettings.ServerName
});
}
else
{
Logger.Warning(
"Failed to verify address. Continuing server startup, but note that this server was not added to the Master Lists, if it wasn't already there");
await scrapeServersAndStart(null);
}
}
else
{
Logger.Warning(
"If you provide a value for \'serverAddress\' in the configuration file, your server can be added to the Master Lists");
await scrapeServersAndStart(null);
}
}
//Courtesy of andruzzzhka's Multiplayer
async void OpenPort(int port)
{
Logger.Info($"Trying to open port {port} using UPnP...");
try
{
NatDiscoverer discoverer = new NatDiscoverer();
CancellationTokenSource cts = new CancellationTokenSource(2500);
NatDevice device = await discoverer.DiscoverDeviceAsync(PortMapper.Upnp, cts);
await device.CreatePortMapAsync(new Mapping(Protocol.Tcp, port, port, ""));
Logger.Info($"Port {port} is open!");
}
catch (Exception)
{
Logger.Warning(
$"Can't open port {port} using UPnP! (This is only relevant for people behind NAT who don't port forward. If you're being hosted by an actual server, or you've set up port forwarding manually, you can safely ignore this message. As well as any other yellow messages... Yellow means \"warning\" folks.");
}
}
private async Task Server_ClientDisconnected(ConnectedUser client)
{
Logger.Debug("Client Disconnected!");
if (State.Users.Any(x => x.Id == client.id.ToString()))
{
var user = State.Users.First(x => x.Id == client.id.ToString());
await RemoveUser(user);
}
}
private Task Server_ClientConnected(ConnectedUser client)
{
return Task.CompletedTask;
}
static string LogPacket(Packet packet)
{
string secondaryInfo = string.Empty;
if (packet.packetCase == Packet.packetOneofCase.PlaySong)
{
var playSong = packet.PlaySong;
secondaryInfo = playSong.GameplayParameters.Beatmap.LevelId + " : " +
playSong.GameplayParameters.Beatmap.Difficulty;
}
if (packet.packetCase == Packet.packetOneofCase.LoadSong)
{
var loadSong = packet.LoadSong;
secondaryInfo = loadSong.LevelId;
}
if (packet.packetCase == Packet.packetOneofCase.Command)
{
var command = packet.Command;
secondaryInfo = command.CommandType.ToString();
}
if (packet.packetCase == Packet.packetOneofCase.Event)
{
var @event = packet.Event;
secondaryInfo = @event.ChangedObjectCase.ToString();
if (@event.ChangedObjectCase == Event.ChangedObjectOneofCase.user_updated_event)
{
var user = @event.user_updated_event.User;
secondaryInfo =
$"{secondaryInfo} from ({user.Name} : {user.DownloadState}) : ({user.PlayState} : {user.Score} : {user.StreamDelayMs})";
}
else if (@event.ChangedObjectCase == Event.ChangedObjectOneofCase.match_updated_event)
{
var match = @event.match_updated_event.Match;
secondaryInfo = $"{secondaryInfo} ({match.SelectedDifficulty})";
}
}
if (packet.packetCase == Packet.packetOneofCase.ForwardingPacket)
{
var forwardedpacketCase = packet.ForwardingPacket.Packet.packetCase;
secondaryInfo = $"{forwardedpacketCase}";
}
return $"({packet.packetCase}) ({secondaryInfo})";
}
public async Task Send(Guid id, Packet packet)
{
Logger.Debug($"Sending data: {LogPacket(packet)}");
packet.From = Self?.Id ?? Guid.Empty.ToString();
await server.Send(id, new PacketWrapper(packet));
await wsServer?.Send(id, packet);
}
public async Task Send(Guid[] ids, Packet packet)
{
Logger.Debug($"Sending data: {LogPacket(packet)}");
packet.From = Self?.Id ?? Guid.Empty.ToString();
await server.Send(ids, new PacketWrapper(packet));
await wsServer?.Send(ids, packet);
}
public async Task ForwardTo(Guid[] ids, Guid from, Packet packet)
{
packet.From = from.ToString();
Logger.Debug($"Sending data: {LogPacket(packet)}");
await server.Send(ids, new PacketWrapper(packet));
await wsServer?.Send(ids, packet);
}
private async Task BroadcastToAllClients(Packet packet, bool toOverlay = true)
{
packet.From = Self.Id;
Logger.Debug($"Sending data: {LogPacket(packet)}");
await server.Broadcast(new PacketWrapper(packet));
await wsServer?.Broadcast(packet);
}
#region EventManagement
public async Task AddUser(User user)
{
lock (State)
{
State.Users.Add(user);
}
NotifyPropertyChanged(nameof(State));
var @event = new Event
{
user_added_event = new Event.UserAddedEvent
{
User = user
}
};
await BroadcastToAllClients(new Packet
{
Event = @event
});
if (UserConnected != null) await UserConnected.Invoke(user);
}
public async Task UpdateUser(User user)
{
lock (State)
{
var userToReplace = State.Users.FirstOrDefault(x => x.UserEquals(user));
State.Users.Remove(userToReplace);
State.Users.Add(user);
}
NotifyPropertyChanged(nameof(State));
var @event = new Event
{
user_updated_event = new Event.UserUpdatedEvent
{
User = user
}
};
await BroadcastToAllClients(new Packet
{
Event = @event
});
if (UserInfoUpdated != null) await UserInfoUpdated.Invoke(user);
}
public async Task RemoveUser(User user)
{
lock (State)
{
var userToRemove = State.Users.FirstOrDefault(x => x.UserEquals(user));
State.Users.Remove(userToRemove);
}
NotifyPropertyChanged(nameof(State));
var @event = new Event
{
user_left_event = new Event.UserLeftEvent
{
User = user
}
};
await BroadcastToAllClients(new Packet
{
Event = @event
});
if (UserDisconnected != null) await UserDisconnected.Invoke(user);
}
public async Task CreateMatch(Match match)
{
lock (State)
{
State.Matches.Add(match);
}
NotifyPropertyChanged(nameof(State));
var @event = new Event
{
match_created_event = new Event.MatchCreatedEvent
{
Match = match
}
};
await BroadcastToAllClients(new Packet
{
Event = @event
});
if (MatchCreated != null) await MatchCreated.Invoke(match);
}
public async Task UpdateMatch(Match match)
{
lock (State)
{
var matchToReplace = State.Matches.FirstOrDefault(x => x.MatchEquals(match));
State.Matches.Remove(matchToReplace);
State.Matches.Add(match);
}
NotifyPropertyChanged(nameof(State));
var @event = new Event
{
match_updated_event = new Event.MatchUpdatedEvent
{
Match = match
}
};
var updatePacket = new Packet
{
Event = @event
};
await BroadcastToAllClients(updatePacket);
if (MatchInfoUpdated != null) await MatchInfoUpdated.Invoke(match);
}
public async Task DeleteMatch(Match match)
{
lock (State)
{
var matchToRemove = State.Matches.FirstOrDefault(x => x.MatchEquals(match));
State.Matches.Remove(matchToRemove);
}
NotifyPropertyChanged(nameof(State));
var @event = new Event
{
match_deleted_event = new Event.MatchDeletedEvent
{
Match = match
}
};
await BroadcastToAllClients(new Packet
{
Event = @event
});
if (MatchDeleted != null) await MatchDeleted.Invoke(match);
}
public async Task<Response> SendCreateQualifierEvent(CoreServer host, QualifierEvent qualifierEvent)
{
if (host.CoreServerEquals(CoreServer))
{
return await CreateQualifierEvent(qualifierEvent);
}
else
{
var result = await HostScraper.RequestResponse(host, new Packet
{
Event = new Event
{
qualifier_created_event = new Event.QualifierCreatedEvent
{
Event = qualifierEvent
}
}
}, Packet.packetOneofCase.Response, $"{CoreServer.Address}:{CoreServer.Port}", 0);
return result?.Response ?? new Response
{
Type = ResponseType.Fail,
Message =
"The request to the designated server timed out. The server is offline or otherwise unreachable"
};
}
}
public async Task<Response> SendUpdateQualifierEvent(CoreServer host, QualifierEvent qualifierEvent)
{
if (host.CoreServerEquals(CoreServer))
{
return await UpdateQualifierEvent(qualifierEvent);
}
else
{
var result = await HostScraper.RequestResponse(host, new Packet
{
Event = new Event
{
qualifier_updated_event = new Event.QualifierUpdatedEvent
{
Event = qualifierEvent
}
}
}, Packet.packetOneofCase.Response, $"{CoreServer.Address}:{CoreServer.Port}", 0);
return result?.Response ?? new Response
{
Type = ResponseType.Fail,
Message =
"The request to the designated server timed out. The server is offline or otherwise unreachable"
};
}
}
public async Task<Response> SendDeleteQualifierEvent(CoreServer host, QualifierEvent qualifierEvent)
{
if (host.CoreServerEquals(CoreServer))
{
return await DeleteQualifierEvent(qualifierEvent);
}
else
{
var result = await HostScraper.RequestResponse(host, new Packet
{
Event = new Event
{
qualifier_deleted_event = new Event.QualifierDeletedEvent
{
Event = qualifierEvent
}
}
}, Packet.packetOneofCase.Response,
$"{CoreServer.Address}:{CoreServer.Port}", 0);
return result?.Response ?? new Response
{
Type = ResponseType.Fail,
Message =
"The request to the designated server timed out. The server is offline or otherwise unreachable"
};
}
}
public async Task<Response> CreateQualifierEvent(QualifierEvent qualifierEvent)
{
if (Database.Events.Any(x => !x.Old && x.GuildId == (ulong)qualifierEvent.Guild.Id))
{
return new Response
{
Type = ResponseType.Fail,
Message = "There is already an event running for your guild"
};
}
var databaseEvent = Database.ConvertModelToEventDatabase(qualifierEvent);
Database.Events.Add(databaseEvent);
await Database.SaveChangesAsync();
lock (State)
{
State.Events.Add(qualifierEvent);
}
NotifyPropertyChanged(nameof(State));
var @event = new Event
{
qualifier_created_event = new Event.QualifierCreatedEvent
{
Event = qualifierEvent
}
};
await BroadcastToAllClients(new Packet
{
Event = @event
});
return new Response
{
Type = ResponseType.Success,
Message =
$"Successfully created event: {databaseEvent.Name} with settings: {(QualifierEvent.EventSettings)databaseEvent.Flags}"
};
}
public async Task<Response> UpdateQualifierEvent(QualifierEvent qualifierEvent)
{
if (!Database.Events.Any(x => !x.Old && x.GuildId == (ulong)qualifierEvent.Guild.Id))
{
return new Response
{
Type = ResponseType.Fail,
Message = "There is not an event running for your guild"
};
}
//Update Event entry
var newDatabaseEvent = Database.ConvertModelToEventDatabase(qualifierEvent);
Database.Entry(Database.Events.First(x => x.EventId == qualifierEvent.EventId.ToString())).CurrentValues
.SetValues(newDatabaseEvent);
//Check for removed songs
foreach (var song in Database.Songs.Where(x => x.EventId == qualifierEvent.EventId.ToString() && !x.Old))
{
if (!qualifierEvent.QualifierMaps.Any(x => song.LevelId == x.Beatmap.LevelId &&
song.Characteristic ==
x.Beatmap.Characteristic.SerializedName &&
song.BeatmapDifficulty == x.Beatmap.Difficulty &&
song.GameOptions == (int)x.GameplayModifiers.Options &&
song.PlayerOptions == (int)x.PlayerSettings.Options))
{
song.Old = true;
}
}
//Check for newly added songs
foreach (var song in qualifierEvent.QualifierMaps)
{
if (!Database.Songs.Any(x => !x.Old &&
x.EventId == qualifierEvent.EventId.ToString() &&
x.LevelId == song.Beatmap.LevelId &&
x.Characteristic == song.Beatmap.Characteristic.SerializedName &&
x.BeatmapDifficulty == song.Beatmap.Difficulty &&
x.GameOptions == (int)song.GameplayModifiers.Options &&
x.PlayerOptions == (int)song.PlayerSettings.Options))
{
Database.Songs.Add(new Discord.Database.Song
{
EventId = qualifierEvent.EventId.ToString(),
LevelId = song.Beatmap.LevelId,
Name = song.Beatmap.Name,
Characteristic = song.Beatmap.Characteristic.SerializedName,
BeatmapDifficulty = song.Beatmap.Difficulty,
GameOptions = (int)song.GameplayModifiers.Options,
PlayerOptions = (int)song.PlayerSettings.Options
});
}
}
await Database.SaveChangesAsync();
lock (State)
{
var eventToReplace = State.Events.FirstOrDefault(x => x.EventId == qualifierEvent.EventId);
State.Events.Remove(eventToReplace);
State.Events.Add(qualifierEvent);
}
NotifyPropertyChanged(nameof(State));
var @event = new Event
{
qualifier_updated_event = new Event.QualifierUpdatedEvent
{
Event = qualifierEvent
}
};
var updatePacket = new Packet
{
Event = @event
};
await BroadcastToAllClients(updatePacket);
return new Response
{
Type = ResponseType.Success,
Message = $"Successfully updated event: {newDatabaseEvent.Name}"
};
}
public async Task<Response> DeleteQualifierEvent(QualifierEvent qualifierEvent)
{
if (!Database.Events.Any(x => !x.Old && x.GuildId == (ulong)qualifierEvent.Guild.Id))
{
return new Response
{
Type = ResponseType.Fail,
Message = "There is not an event running for your guild"
};
}
//Mark all songs and scores as old
await Database.Events.Where(x => x.EventId == qualifierEvent.EventId.ToString())
.ForEachAsync(x => x.Old = true);
await Database.Songs.Where(x => x.EventId == qualifierEvent.EventId.ToString())
.ForEachAsync(x => x.Old = true);
await Database.Scores.Where(x => x.EventId == qualifierEvent.EventId.ToString())
.ForEachAsync(x => x.Old = true);
await Database.SaveChangesAsync();
lock (State)
{
var eventToRemove = State.Events.FirstOrDefault(x => x.EventId == qualifierEvent.EventId);
State.Events.Remove(eventToRemove);
}
NotifyPropertyChanged(nameof(State));
var @event = new Event
{
qualifier_deleted_event = new Event.QualifierDeletedEvent
{
Event = qualifierEvent
}
};
await BroadcastToAllClients(new Packet
{
Event = @event
});
return new Response
{
Type = ResponseType.Success,
Message = $"Successfully ended event: {qualifierEvent.Name}"
};
}
public async Task AddHost(CoreServer host)
{
lock (State)
{
State.KnownHosts.Add(host);
//Save to disk
config.SaveHosts(State.KnownHosts.ToArray());
}
NotifyPropertyChanged(nameof(State));
var @event = new Event
{
host_added_event = new Event.HostAddedEvent
{
Server = host
}
};
await BroadcastToAllClients(new Packet
{
Event = @event
});
}
public async Task RemoveHost(CoreServer host)
{
lock (State)
{
var hostToRemove = State.KnownHosts.FirstOrDefault(x => x.CoreServerEquals(host));
State.KnownHosts.Remove(hostToRemove);
}
NotifyPropertyChanged(nameof(State));
var @event = new Event
{
host_deleted_event = new Event.HostDeletedEvent
{
Server = host
}
};
await BroadcastToAllClients(new Packet
{
Event = @event
});
}
#endregion EventManagement
private async Task Server_PacketReceived(ConnectedUser user, Packet packet)
{
Logger.Debug($"Received data: {LogPacket(packet)}");
//Ready to go, only disabled since it is currently unusued
/*if (packet.Type != PacketType.Acknowledgement)
{
Send(packet.From, new Packet(new Acknowledgement()
{
PacketId = packet.Id
}));
}*/
if (packet.packetCase == Packet.packetOneofCase.Acknowledgement)
{
Acknowledgement acknowledgement = packet.Acknowledgement;
AckReceived?.Invoke(acknowledgement, Guid.Parse(packet.From));
}
/*else if (packet.Type == PacketType.SongList)
{
SongList songList = packet.SpecificPacket as SongList;
}*/
/*else if (packet.Type == PacketType.LoadedSong)
{
LoadedSong loadedSong = packet.SpecificPacket as LoadedSong;
}*/
else if (packet.packetCase == Packet.packetOneofCase.Connect)
{
Connect connect = packet.Connect;
if (connect.ClientVersion != VersionCode)
{
await Send(user.id, new Packet
{
ConnectResponse = new ConnectResponse()
{
Response = new Response()
{
Type = ResponseType.Fail,
Message = $"Version mismatch, this server is on version {Constants.Version}",
},
Self = null,
State = null,
ServerVersion = VersionCode
}
});
}
if (string.IsNullOrWhiteSpace(settings.Password) || connect.Password == settings.Password)
{
var newUser = new User()
{
Id = user.id.ToString(),
Name = connect.Name,
UserId = connect.UserId,
ClientType = connect.ClientType,
Team = new Team() { Id = Guid.Empty.ToString(), Name = "None" }
};
await AddUser(newUser);
//Give the newly connected player their Self and State
await Send(user.id, new Packet
{
ConnectResponse = new ConnectResponse()
{
Response = new Response()
{
Type = ResponseType.Success,
Message = $"Connected to {settings.ServerName}!"
},
Self = newUser,
State = State,
ServerVersion = VersionCode
}
});
}
else
{
await Send(user.id, new Packet
{
ConnectResponse = new ConnectResponse()
{
Response = new Response()
{
Type = ResponseType.Fail,
Message = $"Incorrect password for {settings.ServerName}!"
},
State = State,
ServerVersion = VersionCode
}
});
}
}
else if (packet.packetCase == Packet.packetOneofCase.ScoreRequest)
{
ScoreRequest request = packet.ScoreRequest;
var scores = Database.Scores
.Where(x => x.EventId == request.EventId.ToString() &&
x.LevelId == request.Parameters.Beatmap.LevelId &&
x.Characteristic == request.Parameters.Beatmap.Characteristic.SerializedName &&
x.BeatmapDifficulty == request.Parameters.Beatmap.Difficulty &&
x.GameOptions == (int)request.Parameters.GameplayModifiers.Options &&
//x.PlayerOptions == (int)request.Parameters.PlayerSettings.Options &&
!x.Old).OrderByDescending(x => x._Score)
.Select(x => new Score
{
EventId = request.EventId,
Parameters = request.Parameters,
Username = x.Username,
UserId = x.UserId.ToString(),
score = x._Score,
FullCombo = x.FullCombo,
Color = x.Username == "Moon" ? "#00ff00" : "#ffffff"
});
//If scores are disabled for this event, don't return them
var @event = Database.Events.FirstOrDefault(x => x.EventId == request.EventId.ToString());
if (((QualifierEvent.EventSettings)@event.Flags).HasFlag(QualifierEvent.EventSettings
.HideScoresFromPlayers))
{
await Send(user.id, new Packet
{
ScoreRequestResponse = new ScoreRequestResponse()
});
}
else
{
var scoreRequestResponse = new ScoreRequestResponse();
scoreRequestResponse.Scores.AddRange(scores);
await Send(user.id, new Packet
{
ScoreRequestResponse = scoreRequestResponse
});
}
}
else if (packet.packetCase == Packet.packetOneofCase.SubmitScore)
{
SubmitScore submitScore = packet.SubmitScore;
//Check to see if the song exists in the database
var song = Database.Songs.FirstOrDefault(x => x.EventId == submitScore.Score.EventId.ToString() &&
x.LevelId == submitScore.Score.Parameters.Beatmap
.LevelId &&
x.Characteristic == submitScore.Score.Parameters.Beatmap
.Characteristic.SerializedName &&
x.BeatmapDifficulty == submitScore.Score.Parameters
.Beatmap.Difficulty &&
x.GameOptions == (int)submitScore.Score.Parameters
.GameplayModifiers.Options &&
//x.PlayerOptions == (int)submitScore.Score.Parameters.PlayerSettings.Options &&
!x.Old);
if (song != null)
{
//Mark all older scores as old
var scores = Database.Scores
.Where(x => x.EventId == submitScore.Score.EventId.ToString() &&
x.LevelId == submitScore.Score.Parameters.Beatmap.LevelId &&
x.Characteristic == submitScore.Score.Parameters.Beatmap.Characteristic
.SerializedName &&
x.BeatmapDifficulty == submitScore.Score.Parameters.Beatmap.Difficulty &&
x.GameOptions == (int)submitScore.Score.Parameters.GameplayModifiers.Options &&
//x.PlayerOptions == (int)submitScore.Score.Parameters.PlayerSettings.Options &&
!x.Old &&
x.UserId == ulong.Parse(submitScore.Score.UserId));
var oldHighScore = (scores.OrderBy(x => x._Score).FirstOrDefault()?._Score ?? -1);
if (oldHighScore < submitScore.Score.score)
{
foreach (var score in scores) score.Old = true;
Database.Scores.Add(new Discord.Database.Score
{
EventId = submitScore.Score.EventId.ToString(),
UserId = ulong.Parse(submitScore.Score.UserId),
Username = submitScore.Score.Username,
LevelId = submitScore.Score.Parameters.Beatmap.LevelId,
Characteristic = submitScore.Score.Parameters.Beatmap.Characteristic.SerializedName,
BeatmapDifficulty = submitScore.Score.Parameters.Beatmap.Difficulty,
GameOptions = (int)submitScore.Score.Parameters.GameplayModifiers.Options,
PlayerOptions = (int)submitScore.Score.Parameters.PlayerSettings.Options,
_Score = submitScore.Score.score,
FullCombo = submitScore.Score.FullCombo,
});
await Database.SaveChangesAsync();
}
var newScores = Database.Scores
.Where(x => x.EventId == submitScore.Score.EventId.ToString() &&
x.LevelId == submitScore.Score.Parameters.Beatmap.LevelId &&
x.Characteristic == submitScore.Score.Parameters.Beatmap.Characteristic
.SerializedName &&
x.BeatmapDifficulty == submitScore.Score.Parameters.Beatmap.Difficulty &&
x.GameOptions == (int)submitScore.Score.Parameters.GameplayModifiers.Options &&
//x.PlayerOptions == (int)submitScore.Score.Parameters.PlayerSettings.Options &&
!x.Old).OrderByDescending(x => x._Score).Take(10)
.Select(x => new Score
{
EventId = submitScore.Score.EventId,
Parameters = submitScore.Score.Parameters,
Username = x.Username,
UserId = x.UserId.ToString(),
score = x._Score,
FullCombo = x.FullCombo,
Color = "#ffffff"
});
//Return the new scores for the song so the leaderboard will update immediately
//If scores are disabled for this event, don't return them
var @event = Database.Events.FirstOrDefault(x => x.EventId == submitScore.Score.EventId.ToString());
var hideScores =
((QualifierEvent.EventSettings)@event.Flags).HasFlag(QualifierEvent.EventSettings
.HideScoresFromPlayers);
var enableLeaderboardMessage =
((QualifierEvent.EventSettings)@event.Flags).HasFlag(QualifierEvent.EventSettings
.EnableLeaderboardMessage);
var scoreRequestResponse = new ScoreRequestResponse();
scoreRequestResponse.Scores.AddRange(hideScores ? new Score[] { } : newScores.ToArray());
await Send(user.id, new Packet
{
ScoreRequestResponse = scoreRequestResponse
});
if (oldHighScore < submitScore.Score.score && @event.InfoChannelId != default && !hideScores &&
QualifierBot != null)
{
QualifierBot.SendScoreEvent(@event.InfoChannelId, submitScore);
if (enableLeaderboardMessage)
{
var eventSongs = Database.Songs.Where(x =>
x.EventId == submitScore.Score.EventId.ToString() && !x.Old);
var eventScores = Database.Scores.Where(x =>
x.EventId == submitScore.Score.EventId.ToString() && !x.Old);
var newMessageId = await QualifierBot.SendLeaderboardUpdate(@event.InfoChannelId,
@event.LeaderboardMessageId, eventScores.ToList(), eventSongs.ToList());
if (@event.LeaderboardMessageId != newMessageId)
{
@event.LeaderboardMessageId = newMessageId;
await Database.SaveChangesAsync();
}
}
}
}
}
else if (packet.packetCase == Packet.packetOneofCase.Event)
{
Event @event = packet.Event;
switch (@event.ChangedObjectCase)
{
case Event.ChangedObjectOneofCase.match_created_event:
await CreateMatch(@event.match_created_event.Match);
break;
case Event.ChangedObjectOneofCase.match_updated_event:
await UpdateMatch(@event.match_updated_event.Match);
break;
case Event.ChangedObjectOneofCase.match_deleted_event:
await DeleteMatch(@event.match_deleted_event.Match);
break;
case Event.ChangedObjectOneofCase.user_added_event:
await AddUser(@event.user_added_event.User);
break;
case Event.ChangedObjectOneofCase.user_updated_event:
await UpdateUser(@event.user_updated_event.User);
break;
case Event.ChangedObjectOneofCase.user_left_event:
await RemoveUser(@event.user_left_event.User);
break;
case Event.ChangedObjectOneofCase.qualifier_created_event:
var createResponse = await CreateQualifierEvent(@event.qualifier_created_event.Event);
await Send(user.id, new Packet
{
Response = createResponse
});
break;
case Event.ChangedObjectOneofCase.qualifier_updated_event:
var updateResponse = await UpdateQualifierEvent(@event.qualifier_updated_event.Event);
await Send(user.id, new Packet
{
Response = updateResponse
});
break;
case Event.ChangedObjectOneofCase.qualifier_deleted_event:
var deleteResponse = await DeleteQualifierEvent(@event.qualifier_deleted_event.Event);
await Send(user.id, new Packet
{
Response = deleteResponse
});
break;
case Event.ChangedObjectOneofCase.host_added_event:
await AddHost(@event.host_added_event.Server);
break;
case Event.ChangedObjectOneofCase.host_deleted_event:
await RemoveHost(@event.host_deleted_event.Server);
break;
default:
Logger.Error($"Unknown command received from {user.id}!");
break;
}
}
else if (packet.packetCase == Packet.packetOneofCase.SongFinished)
{
await BroadcastToAllClients(packet, false);
PlayerFinishedSong?.Invoke(packet.SongFinished);
}
else if (packet.packetCase == Packet.packetOneofCase.ForwardingPacket)
{
var forwardingPacket = packet.ForwardingPacket;
var forwardedPacket = forwardingPacket.Packet;
await ForwardTo(forwardingPacket.ForwardToes.Select(x => Guid.Parse(x)).ToArray(),
Guid.Parse(packet.From),
forwardedPacket);
}
else if (packet.packetCase == Packet.packetOneofCase.SendBotMessage)
{
var sendBotMessage = packet.SendBotMessage;
QualifierBot.SendMessage(sendBotMessage.Channel, sendBotMessage.Message);
}
else if (packet.packetCase == Packet.packetOneofCase.MessageResponse)
{
await BroadcastToAllClients(packet, false);
}
}
}
} | 41.187547 | 323 | 0.49434 | [
"MIT"
] | raineio/TournamentAssistant | TournamentAssistantCore/SystemServer.cs | 54,246 | C# |
using OpenTracker.Models.Modes;
namespace OpenTracker.Models.UndoRedo.Mode
{
/// <summary>
/// This interface contains the <see cref="IUndoable"/> action to change the <see cref="IMode.BossShuffle"/>
/// property.
/// </summary>
public interface IChangeBossShuffle : IUndoable
{
/// <summary>
/// A factory for creating new <see cref="IChangeBossShuffle"/> objects.
/// </summary>
/// <param name="newValue">
/// A <see cref="bool"/> representing the new <see cref="IMode.BossShuffle"/> value.
/// </param>
/// <returns>
/// A new <see cref="IChangeBossShuffle"/> object.
/// </returns>
delegate IChangeBossShuffle Factory(bool newValue);
}
} | 34.5 | 112 | 0.594203 | [
"MIT"
] | AntyMew/OpenTracker | OpenTracker.Models/UndoRedo/Mode/IChangeBossShuffle.cs | 759 | C# |
using Actio.Common.Commands;
using Actio.Services.Identity.Services;
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;
namespace Actio.Services.Identity.Controllers
{
[Route("")]
public class AccountController : Controller
{
private readonly IUserService _userService;
public AccountController(IUserService userService)
{
_userService = userService;
}
[HttpPost("login")]
public async Task<IActionResult> Login([FromBody] AuthenticateUser command)
=> Json(await _userService.LoginAsync(command.Email, command.Password));
}
} | 28.5 | 84 | 0.69697 | [
"MIT"
] | josh-davis-git/Actio | src/Actio.Services.Identity/Controllers/AccountController.cs | 627 | 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 Microsoft.CodeAnalysis.Testing
{
public abstract class ProjectState
{
private readonly string _defaultPrefix;
private readonly string _defaultExtension;
protected ProjectState(string name, string defaultPrefix, string defaultExtension)
{
Name = name;
_defaultPrefix = defaultPrefix;
_defaultExtension = defaultExtension;
Sources = new SourceFileList(defaultPrefix, defaultExtension);
}
public string Name { get; }
public string AssemblyName => Name;
public abstract string Language { get; }
/// <summary>
/// Gets the set of source files for analyzer or code fix testing. Files may be added to this list using one of
/// the <see cref="SourceFileList.Add(string)"/> methods.
/// </summary>
public SourceFileList Sources { get; }
public MetadataReferenceCollection AdditionalReferences { get; } = new MetadataReferenceCollection();
}
}
| 34.138889 | 119 | 0.66965 | [
"MIT"
] | Danghor/roslyn-sdk | src/Microsoft.CodeAnalysis.Testing/Microsoft.CodeAnalysis.Analyzer.Testing/ProjectState.cs | 1,231 | 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("BS_PokedexManager")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("BS_PokedexManager")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[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("52093f6e-ebb9-44b4-b5de-b01e27caea3d")]
// 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")]
| 38.027027 | 84 | 0.746979 | [
"MIT"
] | ErazerBrecht/Pok-Dex | BS_PokedexManager/Properties/AssemblyInfo.cs | 1,410 | C# |
using BlazorApp.Shared.FileStorage;
namespace BlazorApp.Shared.Identity;
public class UpdateProfileRequest
{
public string? FirstName { get; set; }
public string? LastName { get; set; }
public string? PhoneNumber { get; set; }
public string? Email { get; set; }
public FileUploadRequest? Image { get; set; }
} | 20.9375 | 49 | 0.695522 | [
"MIT"
] | DurgaPrasadReddyV/BlazorApp | Source/BlazorApp.Shared/Identity/UpdateProfileRequest.cs | 335 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;
public partial class student_AcademicRecords : System.Web.UI.Page
{
string uname;
int Student_ID;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
if (Session["UserName"] != null)
{
uname = Session["UserName"].ToString();
Student_ID = Convert.ToInt32(Session["Student_ID"]);
bindStudentAttendance(Student_ID);
}
}
}
public void bindStudentAttendance(int Student_ID)
{
clsStudent cs = new clsStudent();
DataSet ds = cs.StudentAttendance(Student_ID);
if (ds.Tables[0].Rows.Count > 0)
{
lblStudent_Name.Text=ds.Tables[0].Rows[0]["Student_Name"].ToString();
lblLectureConducted.Text=ds.Tables[0].Rows[0]["LectureConducted"].ToString();
lblAbsent.Text = ds.Tables[0].Rows[0]["Abse"].ToString();
lblPresent.Text = ds.Tables[0].Rows[0]["Present"].ToString();
}
}
} | 30.302326 | 90 | 0.578665 | [
"MIT"
] | panchal0026/HKDI | student/AcademicRecords.aspx.cs | 1,305 | C# |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using ImageFramework.Utility;
using SharpDX.Direct3D11;
using SharpDX.DXGI;
using Resource = SharpDX.Direct3D11.Resource;
namespace ImageFramework.DirectX
{
public abstract class TextureBase<T> : ITexture where T : TextureBase<T>
{
public Size3 Size { get; protected set; }
public bool HasCubemap => LayerMipmap.Layers == 6 && Size.Width == Size.Height;
public LayerMipmapCount LayerMipmap { get; protected set; }
public int NumLayers => LayerMipmap.Layers;
public int NumMipmaps => LayerMipmap.Mipmaps;
public Format Format { get; protected set; }
public abstract bool Is3D { get; }
protected UnorderedAccessView[] uaViews;
protected RenderTargetView[] rtViews;
protected ShaderResourceView[] views;
public ShaderResourceView View { get; protected set; }
public bool HasUaViews => uaViews != null;
public bool HasSrViews => views != null;
public bool HasRtViews => rtViews != null;
public ShaderResourceView GetSrView(LayerMipmapSlice lm)
{
return views[GetSubresourceIndex(lm)];
}
public RenderTargetView GetRtView(LayerMipmapSlice lm)
{
Debug.Assert(rtViews != null);
return rtViews[GetSubresourceIndex(lm)];
}
public UnorderedAccessView GetUaView(int mipmap)
{
Debug.Assert(uaViews != null);
Debug.Assert(LayerMipmap.IsMipmapInside(mipmap));
return uaViews[mipmap];
}
protected int GetSubresourceIndex(LayerMipmapSlice lm)
{
Debug.Assert(lm.IsIn(LayerMipmap));
return lm.Layer * LayerMipmap.Mipmaps + lm.Mipmap;
}
protected abstract Resource GetStagingTexture(LayerMipmapSlice lm);
public Color[] GetPixelColors(LayerMipmapSlice lm)
{
// create staging texture
using (var staging = GetStagingTexture(lm))
{
// obtain data from staging resource
return Device.Get().GetColorData(staging, Format, 0, Size.GetMip(lm.Mipmap));
}
}
public unsafe byte[] GetBytes(LayerMipmapSlice lm, uint size)
{
byte[] res = new byte[size];
fixed (byte* ptr = res)
{
CopyPixels(lm, new IntPtr(ptr), size);
}
return res;
}
public unsafe byte[] GetBytes(uint pixelSize)
{
uint size = 0;
for (int mip = 0; mip < LayerMipmap.Mipmaps; ++mip)
{
size += (uint) (LayerMipmap.Layers * Size.GetMip(mip).Product) * pixelSize;
}
byte[] res = new byte[size];
uint offset = 0;
fixed (byte* ptr = res)
{
foreach (var lm in LayerMipmap.Range)
{
var mipSize = (uint)Size.GetMip(lm.Mipmap).Product * pixelSize;
CopyPixels(lm, new IntPtr(ptr + offset), mipSize);
offset += mipSize;
}
}
Debug.Assert(offset == size);
return res;
}
public void CopyPixels(LayerMipmapSlice lm, IntPtr destination, uint size)
{
// create staging texture
using (var staging = GetStagingTexture(lm))
{
// obtain data from staging resource
Device.Get().GetData(staging, Format, 0, Size.GetMip(lm.Mipmap), destination, size);
}
}
public ITexture CloneWithMipmaps(int nLevels)
{
var newTex = CreateT(new LayerMipmapCount(LayerMipmap.Layers, nLevels), Size, Format, uaViews != null, rtViews != null);
// copy all layers
for (int curLayer = 0; curLayer < LayerMipmap.Layers; ++curLayer)
{
// copy image data of first level
Device.Get().CopySubresource(GetHandle(), newTex.GetHandle(),
GetSubresourceIndex(new LayerMipmapSlice(curLayer, 0)),
newTex.GetSubresourceIndex(new LayerMipmapSlice(curLayer, 0)), Size);
}
return newTex;
}
public ITexture CloneWithoutMipmaps(int mipmap = 0)
{
return CloneWithoutMipmapsT(mipmap);
}
/// <summary>
/// creates a new texture that has only one mipmap level
/// </summary>
/// <returns></returns>
public T CloneWithoutMipmapsT(int mipmap = 0)
{
var newTex = CreateT(new LayerMipmapCount(LayerMipmap.Layers, 1), Size.GetMip(mipmap), Format,
uaViews != null, rtViews != null);
for (int curLayer = 0; curLayer < LayerMipmap.Layers; ++curLayer)
{
// copy data of first level
Device.Get().CopySubresource(GetHandle(), newTex.GetHandle(),
GetSubresourceIndex(new LayerMipmapSlice(curLayer, mipmap)),
newTex.GetSubresourceIndex(new LayerMipmapSlice(curLayer, 0)), Size.GetMip(mipmap));
}
return newTex;
}
public ITexture Clone()
{
return CloneT();
}
public bool HasSameDimensions(ITexture other)
{
if (LayerMipmap != other.LayerMipmap) return false;
if (Size != other.Size) return false;
if (GetType() != other.GetType()) return false;
return true;
}
public T CloneT()
{
var newTex = CreateT(LayerMipmap, Size, Format, uaViews != null, rtViews != null);
Device.Get().CopyResource(GetHandle(), newTex.GetHandle());
return newTex;
}
public ITexture Create(LayerMipmapCount lm, Size3 size, Format format, bool createUav, bool createRtv)
{
return CreateT(lm, size, format, createUav, createRtv);
}
public abstract T CreateT(LayerMipmapCount lm, Size3 size, Format format,
bool createUav, bool createRtv);
protected abstract Resource GetHandle();
public virtual void Dispose()
{
GetHandle()?.Dispose();
if (views != null)
{
foreach (var shaderResourceView in views)
{
shaderResourceView?.Dispose();
}
}
if (uaViews != null)
{
foreach (var unorderedAccessView in uaViews)
{
unorderedAccessView?.Dispose();
}
}
if (rtViews != null)
{
foreach (var renderTargetView in rtViews)
{
renderTargetView?.Dispose();
}
}
View?.Dispose();
}
}
}
| 33.018018 | 133 | 0.531924 | [
"MIT"
] | gaybro8777/ImageViewer | ImageFramework/DirectX/TextureBase.cs | 7,332 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using TMPro;
using UnityEngine;
using UnityEngine.Networking;
public class AIShooter : MonoBehaviour
{
[SerializeField] float moveSpeed = 10f;
private Grid<GridCell> grid;
private CharacterUnit stats;
private CombatCanvasController combatCanvasController;
private List<AICommand> commands;
private int currentCommand;
private bool isMoving = false;
private List<Vector2> movePath;
private int currentNode;
public Grid<GridCell> Grid { get => grid; set => grid = value; }
// Start is called before the first frame update
void Start()
{
combatCanvasController = FindObjectOfType<CombatCanvasController>();
commands = new List<AICommand>();
stats = GetComponent<CharacterUnit>();
}
private void Update()
{
if (isMoving)
{
Move();
}
}
public void HandleTurn()
{
if (commands.Count == 0)
{
Grid.GetXY(transform.position, out int unitX, out int unitY);
List<CharacterUnit> playerCharacters = GetPlayerCharacters();
if (HasCharacterInAttackRange(playerCharacters))
{
//Debug.Log("obj: " + gameObject + "character in range");
//Debug.Log("is flanked: " + CheckIsFlanked(transform.position));
if(CheckIsFlanked(transform.position))
{
// Moverse a una mejor posición, si es posible, y atacar
//Debug.Log("flanqueado, reposicionando");
Vector2 newPos = CheckForFlankingPosition(stats.GetCurrentAP() / stats.GetMovementCost());
//Debug.Log("new pos" + newPos);
if (newPos.x != transform.position.x || newPos.y != transform.position.y)
{
Grid.GetXY(newPos, out int newX, out int newY);
commands.Add(new AICommand(AICommand.Commands.move, newX, newY));
int distance = CalculateDistanceBetweenTwoPoints(unitX, unitY, newPos);
stats.RemoveActionPoints(distance * stats.GetMovementCost());
}
AttackBetterTarget();
}
else
{
if(UnityEngine.Random.Range(1, 100) <= 60)
{
//Debug.Log("reposicionarse y atacar");
Vector2 newPos = CheckForFlankingPosition((stats.GetCurrentAP()) / stats.GetMovementCost());
//Debug.Log("obj: " + gameObject + " new pos: " + newPos + " pos: " + transform.position);
if (newPos.x != transform.position.x || newPos.y != transform.position.y)
{
Grid.GetXY(newPos, out int newX, out int newY);
commands.Add(new AICommand(AICommand.Commands.move, newX, newY));
int distance = CalculateDistanceBetweenTwoPoints(unitX, unitY, newPos);
stats.RemoveActionPoints(distance * stats.GetMovementCost());
}
AttackBetterTarget();
}
else
{
//Debug.Log("quedarse y disparar");
// Permanecer en el sitio y disparar
AttackBetterTarget();
}
}
}
else
{
//Debug.Log("obj: " + gameObject + "no character in range");
Vector2 newPos = CheckForFlankingPosition(stats.GetCurrentAP() / stats.GetMovementCost());
//Debug.Log("obj: " + gameObject + " new pos: " + newPos + " pos: " + transform.position);
if (newPos.x != transform.position.x || newPos.y != transform.position.y)
{
Grid.GetXY(newPos, out int newX, out int newY);
commands.Add(new AICommand(AICommand.Commands.move, newX, newY));
int distance = CalculateDistanceBetweenTwoPoints(unitX, unitY, newPos);
stats.RemoveActionPoints(distance * stats.GetMovementCost());
}
else
{
newPos = AdvanceToCloserCharacter();
if (newPos.x != transform.position.x || newPos.y != transform.position.y)
{
Grid.GetXY(newPos, out int newX, out int newY);
commands.Add(new AICommand(AICommand.Commands.move, newX, newY));
int distance = CalculateDistanceBetweenTwoPoints(unitX, unitY, newPos);
stats.RemoveActionPoints(distance * stats.GetMovementCost());
}
}
}
AttackBetterTarget();
//List<ObstacleStats> osbtacles = GetObstaclesInRange();
/*foreach(AICommand comm in commands)
{
Debug.Log("command: " + comm.Command + " target: " + comm.Target + " X: " + comm.X +
" Y: " + comm.Y);
}*/
}
ExecuteNextCommand();
if (CheckTurnDone() && commands.Count <= currentCommand)
{
commands.Clear();
currentCommand = 0;
CombatSystem.Instance.NextTurn();
}
//CombatSystem.Instance.NextTurn();
}
private void AttackBetterTarget()
{
List<CharacterUnit> playerCharacters = GetPlayerCharacters();
while (!CheckTurnDone() && HasCharacterInAttackRange(playerCharacters))
{
CharacterUnit target = GetBetterTarget(playerCharacters);
commands.Add(new AICommand(AICommand.Commands.attack, target));
stats.RemoveActionPoints(stats.GetAttackCost());
}
}
public void ExecuteNextCommand()
{
//Debug.Log("counter: " + currentCommand + " commands count" + commands.Count);
if(currentCommand < commands.Count)
{
switch (commands[currentCommand].Command)
{
case AICommand.Commands.move:
Pathfinding pathfinding = Pathfinding.Instance;
movePath = pathfinding.FindPath(transform.position,
new Vector2(commands[currentCommand].X, commands[currentCommand].Y));
isMoving = true;
currentNode = 0;
grid.GetGridObject(transform.position).SetIsWalkable(true);
grid.GetGridObject(transform.position).SetUnit(null);
break;
case AICommand.Commands.attack:
if (commands[currentCommand].Target.IsAlive)
{
AttackCharacter(commands[currentCommand].Target);
}
else
{
stats.RestoreCurrentAP(stats.GetAttackCost());
}
break;
}
currentCommand++;
}
else
{
currentCommand = 0;
commands.Clear();
/*if (!CheckTurnDone()) HandleTurn();
else CombatSystem.Instance.NextTurn();*/
}
}
internal void ResetCommands()
{
commands.Clear();
currentCommand = 0;
}
private Vector2 AdvanceToCloserCharacter()
{
Pathfinding pathfinding = Pathfinding.Instance;
CharacterUnit character = GetCloserCharacter();
List<Vector2> path = new List<Vector2>();
List<Vector2> shortestPath = null;
/*foreach(Vector2 point in path) Debug.Log("Advancing to closer character, path: " + point);*/
GridCell cell;
Vector2 pos = new Vector2((int)character.transform.position.x,
(int)character.transform.position.y + 1);
cell = Grid.GetGridObject(pos);
if (cell != null && cell.IsWalkable())
{
path = pathfinding.FindPath(transform.position, pos);
//Debug.Log("up path count:" + path.Count);
//foreach (Vector2 point in path) Debug.Log("Advancing to closer character, path: " + point);
if (path != null && (shortestPath == null || path.Count < shortestPath.Count))
{
shortestPath = path;
}
}
pos.x = character.transform.position.x;
pos.y = character.transform.position.y - 1;
cell = Grid.GetGridObject(pos);
if (cell != null && cell.IsWalkable())
{
path = pathfinding.FindPath(transform.position, pos);
//Debug.Log("down path count:" + path.Count);
//foreach (Vector2 point in path) Debug.Log("Advancing to closer character, path: " + point);
if (path != null && (shortestPath == null || path.Count < shortestPath.Count))
{
shortestPath = path;
}
}
pos.x = character.transform.position.x + 1;
pos.y = character.transform.position.y;
cell = Grid.GetGridObject(pos);
if (cell != null && cell.IsWalkable())
{
path = pathfinding.FindPath(transform.position, pos);
//Debug.Log("right path count:" + path.Count);
//foreach (Vector2 point in path) Debug.Log("Advancing to closer character, path: " + point);
if (path != null && (shortestPath == null || path.Count < shortestPath.Count))
{
shortestPath = path;
}
}
pos.x = character.transform.position.x - 1;
pos.y = character.transform.position.y;
cell = Grid.GetGridObject(pos);
if (cell != null && cell.IsWalkable())
{
path = pathfinding.FindPath(transform.position, pos);
//Debug.Log("left path count:" + path.Count);
//foreach (Vector2 point in path) Debug.Log("Advancing to closer character, path: " + point);
if (path != null && (shortestPath == null || path.Count < shortestPath.Count))
{
shortestPath = path;
}
}
if (shortestPath != null) return shortestPath[Mathf.Min(shortestPath.Count - 1, stats.GetCurrentAP()/stats.GetMovementCost())];
return transform.position;
}
private CharacterUnit GetCloserCharacter()
{
List<CharacterUnit> playerCharacters = GetPlayerCharacters();
Grid.GetXY(transform.position, out int unitX, out int unitY);
CharacterUnit unit = playerCharacters[0];
int minDistance = int.MaxValue;
int distance;
foreach(CharacterUnit character in playerCharacters)
{
distance = CalculateDistanceBetweenTwoPoints(unitX, unitY, character.transform.position);
if(distance < minDistance)
{
minDistance = distance;
unit = character;
}
}
return unit;
}
private Vector2 CheckForFlankingPosition(int range)
{
if (!FlankingFromPosition(transform.position) || CheckIsFlanked(transform.position))
{
Pathfinding pathfinding = Pathfinding.Instance;
List<CharacterUnit> playerCharacters = GetPlayerCharacters();
List<ObstacleStats> obstacles = GetObstaclesInRange(range);
List<Vector2> potentialPositions = new List<Vector2>();
GridCell cell;
foreach(ObstacleStats obstacle in obstacles)
{
Grid.GetXY(obstacle.transform.position, out int obsX, out int obsY);
cell = Grid.GetGridObject(obsX, obsY + 1);
if (cell != null && cell.IsWalkable())
{
Vector2 pos = new Vector2(obstacle.transform.position.x, obstacle.transform.position.y + 1);
if (!CheckIsFlanked(pos) && HasCharacterInAttackRange(playerCharacters))
{
potentialPositions.Add(pos);
if(FlankingFromPosition(pos))
{
List<Vector2> path = pathfinding.FindPath(transform.position, pos);
if (path != null && path.Count - 1 <= range)
{
return pos;
}
}
}
}
cell = Grid.GetGridObject(obsX, obsY - 1);
if (cell != null && cell.IsWalkable())
{
Vector2 pos = new Vector2(obstacle.transform.position.x, obstacle.transform.position.y - 1);
if (!CheckIsFlanked(pos) && HasCharacterInAttackRange(playerCharacters))
{
potentialPositions.Add(pos);
if (FlankingFromPosition(pos))
{
List<Vector2> path = pathfinding.FindPath(transform.position, pos);
if (path != null && path.Count - 1 <= range)
{
return pos;
}
}
}
}
cell = Grid.GetGridObject(obsX + 1, obsY);
if (cell != null && cell.IsWalkable())
{
Vector2 pos = new Vector2(obstacle.transform.position.x + 1, obstacle.transform.position.y);
if (!CheckIsFlanked(pos) && HasCharacterInAttackRange(playerCharacters))
{
potentialPositions.Add(pos);
if (FlankingFromPosition(pos))
{
List<Vector2> path = pathfinding.FindPath(transform.position, pos);
if (path != null && path.Count - 1 <= range)
{
return pos;
}
}
}
}
cell = Grid.GetGridObject(obsX - 1, obsY);
if (cell != null && cell.IsWalkable())
{
Vector2 pos = new Vector2(obstacle.transform.position.x - 1, obstacle.transform.position.y);
if (!CheckIsFlanked(pos) && HasCharacterInAttackRange(playerCharacters))
{
potentialPositions.Add(pos);
if (FlankingFromPosition(pos))
{
List<Vector2> path = pathfinding.FindPath(transform.position, pos);
if (path != null && path.Count - 1 <= range)
{
return pos;
}
}
}
}
}
Debug.Log("potential positions: " + potentialPositions.Count);
if(potentialPositions.Count > 0)
{
return potentialPositions[UnityEngine.Random.Range(0, potentialPositions.Count - 1)];
}
}
return transform.position;
}
private bool FlankingFromPosition(Vector2 position)
{
List<CharacterUnit> playerCharacters = GetPlayerCharacters();
Grid.GetXY(new Vector2(transform.position.x, transform.position.y),
out int unitX, out int unitY);
foreach (CharacterUnit character in playerCharacters)
{
int distance = CalculateDistanceBetweenTwoPoints(unitX, unitY, character.transform.position);
if(distance <= stats.GetAttackRange())
{
if (CheckCharacterIsFlankedFromPosition(character, transform.position)) return true;
}
}
return false;
}
private bool CheckCharacterIsFlankedFromPosition(CharacterUnit character, Vector2 position)
{
bool coverUp = HasCoverUp(character.transform.position);
bool coverRight = HasCoverRight(character.transform.position);
bool coverDown = HasCoverDown(character.transform.position);
bool coverLeft = HasCoverLeft(character.transform.position);
if(character.transform.position.y > position.y && !coverDown)
{
if (character.transform.position.x == position.x) return true;
if (character.transform.position.x < position.x && !coverRight) return true;
if (character.transform.position.x > position.x && !coverLeft) return true;
}
else if(character.transform.position.y < position.y && !coverUp)
{
if (character.transform.position.x == position.x) return true;
if (character.transform.position.x < position.x && !coverRight) return true;
if (character.transform.position.x > position.x && !coverLeft) return true;
}
else
{
if (character.transform.position.x < position.x && !coverRight) return true;
if (character.transform.position.x > position.x && !coverLeft) return true;
}
return false;
}
private bool CheckTurnDone()
{
if (stats.GetCurrentAP() > 0)
{
if (stats.GetCurrentAP() >= stats.GetAttackCost() &&
HasCharacterInAttackRange(GetPlayerCharacters())) return false;
else
{
/*if (stats.GetCurrentAP() >= stats.GetMovementCost())
{
Vector2 newPos = CheckForBetterPositionWithinRange(stats.GetCurrentAP() / stats.GetMovementCost());
if (newPos.x != transform.position.x || newPos.y != transform.position.y) return false;
else return true;
}
else return true;*/
return true;
}
}
else return true;
}
private Vector2 CheckForBetterPositionWithinRange(int range)
{
if (CheckIsFlanked(transform.position))
{
Pathfinding pathfinding = Pathfinding.Instance;
List<ObstacleStats> obstacles = GetObstaclesInRange(range);
GridCell cell;
foreach(ObstacleStats obstacle in obstacles)
{
Grid.GetXY(obstacle.transform.position, out int obsX, out int obsY);
cell = Grid.GetGridObject(obsX, obsY + 1);
if (cell != null && cell.IsWalkable())
{
if (!CheckIsFlanked(new Vector2(obstacle.transform.position.x, obstacle.transform.position.y + 1)))
{
List<Vector2> path = pathfinding.FindPath(transform.position,
new Vector2(obstacle.transform.position.x, obstacle.transform.position.y + 1));
if(path != null && path.Count -1 <= range)
{
return new Vector2(obstacle.transform.position.x, obstacle.transform.position.y + 1);
}
}
}
cell = Grid.GetGridObject(obsX, obsY - 1);
if (cell != null && cell.IsWalkable())
{
if (!CheckIsFlanked(new Vector2(obstacle.transform.position.x, obstacle.transform.position.y + 1)))
{
List<Vector2> path = pathfinding.FindPath(transform.position,
new Vector2(obstacle.transform.position.x, obstacle.transform.position.y - 1));
if (path != null && path.Count - 1 <= range)
{
return new Vector2(obstacle.transform.position.x, obstacle.transform.position.y - 1);
}
}
}
cell = Grid.GetGridObject(obsX + 1, obsY);
if (cell != null && cell.IsWalkable())
{
if (!CheckIsFlanked(new Vector2(obstacle.transform.position.x, obstacle.transform.position.y + 1)))
{
List<Vector2> path = pathfinding.FindPath(transform.position,
new Vector2(obstacle.transform.position.x + 1, obstacle.transform.position.y));
if (path != null && path.Count - 1 <= range)
{
return new Vector2(obstacle.transform.position.x + 1, obstacle.transform.position.y);
}
}
}
cell = Grid.GetGridObject(obsX - 1, obsY);
if (cell != null && cell.IsWalkable())
{
if (!CheckIsFlanked(new Vector2(obstacle.transform.position.x, obstacle.transform.position.y + 1)))
{
List<Vector2> path = pathfinding.FindPath(transform.position,
new Vector2(obstacle.transform.position.x - 1, obstacle.transform.position.y));
if (path != null && path.Count - 1 <= range)
{
return new Vector2(obstacle.transform.position.x - 1, obstacle.transform.position.y);
}
}
}
}
}
return transform.position;
}
private List<ObstacleStats> GetObstaclesInRange(int range)
{
List<ObstacleStats> list = new List<ObstacleStats>();
ObstacleStats[] obstacles = FindObjectsOfType<ObstacleStats>();
Grid.GetXY(new Vector2(transform.position.x, transform.position.y),
out int unitX, out int unitY);
foreach(ObstacleStats obstacle in obstacles)
{
int distance = CalculateDistanceBetweenTwoPoints(unitX, unitY, obstacle.transform.position);
if (distance <= range + 1)
{
list.Add(obstacle);
}
}
return list;
}
private int CalculateDistanceBetweenTwoPoints(int unitX, int unitY, Vector2 otherPos)
{
Grid.GetXY(new Vector2(otherPos.x, otherPos.y), out int otherX, out int otherY);
int xDistance = Mathf.Abs(unitX - otherX);
int yDistance = Mathf.Abs(unitY - otherY);
return xDistance + yDistance;
}
private bool CheckIsFlanked(Vector2 position)
{
bool coverUp = HasCoverUp(position);
bool coverRight = HasCoverRight(position);
bool coverDown = HasCoverDown(position);
bool coverLeft = HasCoverLeft(position);
List<CharacterUnit> playerCharacters = GetPlayerCharacters();
foreach(CharacterUnit character in playerCharacters)
{
if (IsInRangeOfPlayer(character))
{
if(character.transform.position.y > position.y && !coverUp)
{
if (character.transform.position.x == position.x) return true;
else if (character.transform.position.x < position.x && !coverLeft) return true;
else if (character.transform.position.x > position.x && !coverRight) return true;
}
else if (character.transform.position.y < position.y && !coverDown)
{
if (character.transform.position.x == position.x) return true;
else if (character.transform.position.x < position.x && !coverLeft) return true;
else if (character.transform.position.x > position.x && !coverRight) return true;
}
else
{
if (character.transform.position.x < position.x && !coverLeft) return true;
else if (character.transform.position.x > position.x && !coverRight) return true;
}
}
}
return false;
}
private bool IsInRangeOfPlayer(CharacterUnit character)
{
int range = character.GetAttackRange();
Grid.GetXY(new Vector2(transform.position.x, transform.position.y),
out int unitX, out int unitY);
int distance = CalculateDistanceBetweenTwoPoints(unitX, unitY, character.transform.position);
if (distance <= range) return true;
return false;
}
private bool HasCoverLeft(Vector2 position)
{
GridCell cell = Grid.GetGridObject(new Vector2(position.x - 1, position.y));
if (cell != null)
{
if (!cell.IsWalkable() && !cell.HasUnit()) return true;
}
return false;
}
private bool HasCoverDown(Vector2 position)
{
GridCell cell = Grid.GetGridObject(new Vector2(position.x, position.y - 1));
if (cell != null)
{
if (!cell.IsWalkable() && !cell.HasUnit()) return true;
}
return false;
}
private bool HasCoverRight(Vector2 position)
{
GridCell cell = Grid.GetGridObject(new Vector2(position.x + 1, position.y));
if (cell != null)
{
if (!cell.IsWalkable() && !cell.HasUnit()) return true;
}
return false;
}
private bool HasCoverUp(Vector2 position)
{
GridCell cell = Grid.GetGridObject(new Vector2(position.x, position.y + 1));
if (cell != null)
{
if (!cell.IsWalkable() && !cell.HasUnit()) return true;
}
return false;
}
private void AttackCharacter(CharacterUnit characterUnit)
{
//Debug.Log("Attack");
int cover = CheckCover(stats, characterUnit);
int hitChance = Mathf.Max(stats.GetBaseHitChance() - cover, 0);
hitChance = Mathf.Clamp(hitChance, 5, 95);
int roll = UnityEngine.Random.Range(1, 100);
if (roll <= hitChance)
{
StartCoroutine(CombatSystem.Instance.UpdateUIAfterAttack(stats, characterUnit));
/*characterUnit.RemoveCurrentHealth(stats.GetAttackDamage());
if (characterUnit.GetCurrentHealth() <= 0)
{
characterUnit.SetState(CharacterUnit.State.dead);
Grid.GetGridObject(characterUnit.transform.position).SetIsWalkable(true);
Grid.GetGridObject(characterUnit.transform.position).SetUnit(null);
}*/
}
combatCanvasController.HitChance = hitChance;
combatCanvasController.Roll = roll;
combatCanvasController.Damage = roll <= hitChance ? stats.GetAttackDamage() : 0;
combatCanvasController.StartAttackAnimations(stats, characterUnit);
}
private CharacterUnit GetBetterTarget(List<CharacterUnit> playerCharacters)
{
int maxChance = 0, chance;
CharacterUnit unit = playerCharacters[0];
grid.GetXY(transform.position, out int unitX, out int unitY);
foreach(CharacterUnit character in playerCharacters)
{
if (CalculateDistanceBetweenTwoPoints(unitX, unitY, character.transform.position) <= stats.GetAttackRange())
{
chance = stats.GetBaseHitChance() - CheckCover(stats, character);
Debug.Log("char" + character.gameObject + "chance" + chance + "maxChance" + maxChance);
if (chance > maxChance)
{
unit = character;
maxChance = chance;
}
}
}
return unit;
}
private bool HasCharacterInAttackRange(List<CharacterUnit> playerCharacters)
{
int range = stats.GetAttackRange();
Grid.GetXY(new Vector2(transform.position.x, transform.position.y),
out int unitX, out int unitY);
foreach(CharacterUnit character in playerCharacters)
{
int distance = CalculateDistanceBetweenTwoPoints(unitX, unitY, character.transform.position);
if (distance <= range) return true;
}
return false;
}
private List<CharacterUnit> GetPlayerCharacters()
{
CharacterUnit[] characters = FindObjectsOfType<CharacterUnit>();
List<CharacterUnit> playerCharacters = new List<CharacterUnit>();
foreach(CharacterUnit c in characters)
{
if (c.IsPlayerControlled() && c.IsAlive) playerCharacters.Add(c);
}
return playerCharacters;
}
private int CheckCover(CharacterUnit attacker, CharacterUnit defender)
{
int cover = 0;
GridCell cell;
if (attacker.transform.position.x < defender.transform.position.x)
{
cell = Grid.GetGridObject(new Vector2(
defender.transform.position.x - 1,
defender.transform.position.y));
if (cell != null && !cell.IsWalkable() && !cell.HasUnit())
{
cover = Mathf.Max(cover, cell.GetObstacle().GetCover());
}
}
else if (attacker.transform.position.x > defender.transform.position.x)
{
cell = Grid.GetGridObject(new Vector2(
defender.transform.position.x + 1,
defender.transform.position.y));
if (cell != null && !cell.IsWalkable() && !cell.HasUnit())
{
cover = Mathf.Max(cover, cell.GetObstacle().GetCover());
}
}
else
{
if (attacker.transform.position.y < defender.transform.position.y)
{
cell = Grid.GetGridObject(new Vector2(
defender.transform.position.x,
defender.transform.position.y - 1));
if (cell != null && !cell.IsWalkable() && !cell.HasUnit())
{
cover = Mathf.Max(cover, cell.GetObstacle().GetCover());
}
}
else
{
cell = Grid.GetGridObject(new Vector2(
defender.transform.position.x,
defender.transform.position.y + 1));
if (cell != null && !cell.IsWalkable() && !cell.HasUnit())
{
cover = Mathf.Max(cover, cell.GetObstacle().GetCover());
}
}
}
if (attacker.transform.position.y < defender.transform.position.y)
{
cell = Grid.GetGridObject(new Vector2(
defender.transform.position.x,
defender.transform.position.y - 1));
if (cell != null && !cell.IsWalkable() && !cell.HasUnit())
{
cover = Mathf.Max(cover, cell.GetObstacle().GetCover());
}
}
else if (attacker.transform.position.y > defender.transform.position.y)
{
cell = Grid.GetGridObject(new Vector2(
defender.transform.position.x,
defender.transform.position.y + 1));
if (cell != null && !cell.IsWalkable() && !cell.HasUnit())
{
cover = Mathf.Max(cover, cell.GetObstacle().GetCover());
}
}
else
{
if (attacker.transform.position.x < defender.transform.position.x)
{
cell = Grid.GetGridObject(new Vector2(
defender.transform.position.x - 1,
defender.transform.position.y));
if (cell != null && !cell.IsWalkable() && !cell.HasUnit())
{
cover = Mathf.Max(cover, cell.GetObstacle().GetCover());
}
}
else
{
cell = Grid.GetGridObject(new Vector2(
defender.transform.position.x + 1,
defender.transform.position.y));
if (cell != null && !cell.IsWalkable() && !cell.HasUnit())
{
cover = Mathf.Max(cover, cell.GetObstacle().GetCover());
}
}
}
if (cover > 0) cover += defender.GetDefenseModifierWithCover();
else cover += defender.GetDefenseModifierWithoutCover();
return cover;
}
private void Move()
{
Vector2 currentPos = new Vector2(transform.position.x, transform.position.y);
if (currentPos == movePath[currentNode])
{
currentNode++;
}
if (currentNode >= movePath.Count)
{
grid.GetGridObject(transform.position).SetIsWalkable(false);
grid.GetGridObject(transform.position).SetUnit(stats);
isMoving = false;
ExecuteNextCommand();
}
else
{
Vector2 targetPosition = movePath[currentNode];
var moveStep = moveSpeed * Time.deltaTime;
transform.position = Vector2.MoveTowards(currentPos, targetPosition, moveStep);
}
}
}
| 41.405507 | 135 | 0.53133 | [
"MIT"
] | XCJGames/Damng-la-balada-del-capitan | Damng La Balada del Capitan/Assets/Scripts/AIShooter.cs | 33,086 | C# |
using System.Runtime.Serialization;
namespace SchinkZeShips.Server
{
[DataContract]
public class GameState
{
[DataMember]
public bool CurrentPlayerIsGameCreator { get; set; }
[DataMember]
public BoardState BoardCreator { get; set; }
[DataMember]
public BoardState BoardParticipant { get; set; }
}
} | 18.705882 | 54 | 0.738994 | [
"MIT"
] | StarlordTheCoder/SchinkZeShips | SchinkZeShips.Server/GameState.cs | 320 | C# |
using System;
using System.Threading.Tasks;
using Core.Arango.Serialization.Json;
using Core.Arango.Serialization.Newtonsoft;
using Xunit;
namespace Core.Arango.Tests.Core
{
public abstract class TestBase : IAsyncLifetime
{
public IArangoContext Arango { get; protected set; }
public virtual Task InitializeAsync()
{
return Task.CompletedTask;
}
public async Task DisposeAsync()
{
try
{
foreach (var db in await Arango.Database.ListAsync())
await Arango.Database.DropAsync(db);
}
catch
{
//
}
}
public async Task SetupAsync(string serializer, string createDatabase = "test")
{
Arango = new ArangoContext(UniqueTestRealm(), new ArangoConfiguration
{
Serializer = serializer switch
{
"newton-default" => new ArangoNewtonsoftSerializer(new ArangoNewtonsoftDefaultContractResolver()),
"newton-camel" => new ArangoNewtonsoftSerializer(new ArangoNewtonsoftCamelCaseContractResolver()),
"system-default" => new ArangoJsonSerializer(new ArangoJsonDefaultPolicy()),
"system-camel" => new ArangoJsonSerializer(new ArangoJsonCamelCasePolicy()),
_ => new ArangoNewtonsoftSerializer(new ArangoNewtonsoftDefaultContractResolver())
}
});
if (!string.IsNullOrEmpty(createDatabase))
await Arango.Database.CreateAsync("test");
}
protected string UniqueTestRealm()
{
var cs = Environment.GetEnvironmentVariable("ARANGODB_CONNECTION");
if (string.IsNullOrWhiteSpace(cs))
cs = "Server=http://localhost:8529;Realm=CI-{UUID};User=root;Password=;";
return cs.Replace("{UUID}", Guid.NewGuid().ToString("D"));
}
}
} | 34.118644 | 118 | 0.584699 | [
"Apache-2.0"
] | ASolomatin/dotnet-arangodb | Core.Arango.Tests/Core/TestBase.cs | 2,013 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace Xunit.MySql.Tests.Models
{
public class TestModel
{
public uint Id { get; set; }
public DateTime Created { get; set; }
public string Description { get; set; }
}
}
| 17.5 | 47 | 0.639286 | [
"MIT"
] | twsl/xunit.MySql | test/xunit.MySql.Tests/Models/TestModel.cs | 282 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Rainbow.Model;
using Sitecore;
using Sitecore.Configuration;
using Sitecore.Data;
using Sitecore.Data.Items;
using Sitecore.Data.Managers;
using Sitecore.Globalization;
using Sitecore.SecurityModel;
using SitecoreSidekick.Models;
using SitecoreSidekick.Services.Interface;
using ItemData = Rainbow.Storage.Sc.ItemData;
using Version = Sitecore.Data.Version;
namespace SitecoreSidekick.Services
{
public class SitecoreDataAccessService : ISitecoreDataAccessService
{
private readonly Database _db = Factory.GetDatabase("master", false);
public ScsSitecoreItem GetScsSitecoreItem(string id)
{
Item item = _db.GetItem(id);
return new ScsSitecoreItem(item);
}
public IItemData GetLatestItemData(Guid idataId, string database = null) => GetLatestItemData(new ID(idataId).ToString(), database);
public IItemData GetLatestItemData(string id, string database = null)
{
var item = GetItem(id, database, LanguageManager.DefaultLanguage, Version.Latest);
if (item == null)
return null;
return new ItemData(item);
}
public IItemData GetItemData(Guid idataId, string database = null) => GetItemData(new ID(idataId).ToString(), database);
public IEnumerable<IItemData> GetChildren(IItemData parent)
{
using (new SecurityDisabler())
{
return parent.GetChildren();
}
}
public IItemData GetItemData(string id, string database = null)
{
var item = GetItem(id, database);
if (item == null)
return null;
return new ItemData(item);
}
public string GetItemRevision(Guid idataId, string database = null)
{
var item = GetItem(idataId, database);
return item?[FieldIDs.Revision];
}
public Dictionary<Guid, string> GetItemAndChildrenRevision(Guid idataId, string database = null)
{
using (new SecurityDisabler())
{
var item = GetItem(idataId, database);
var revs = item?.GetChildren().ToDictionary(x => x.ID.Guid, x => x[FieldIDs.Revision]);
if (revs == null) return null;
revs.Add(item.ID.Guid, item?[FieldIDs.Revision]);
return revs;
}
}
public IItemData GetRootItemData(string database = null)
{
Database db = database == null ? _db : Factory.GetDatabase(database);
using (new SecurityDisabler())
{
return new ItemData(db.GetRootItem());
}
}
public List<Guid> GetChildrenIds(Guid guid)
{
using (new SecurityDisabler())
{
return GetItem(guid).Children.Select(x => x.ID.Guid).ToList();
}
}
public IEnumerable<string> GetVersions(IItemData itemData)
{
Item item = GetItem(itemData.Id);
return item.Versions.GetVersions(true).Select(v => v[FieldIDs.Revision]);
}
public HashSet<Guid> GetSubtreeOfGuids(IEnumerable<Guid> rootIds)
{
HashSet<Guid> ret = new HashSet<Guid>();
Stack<Item> processing = new Stack<Item>(rootIds.Select(x=>GetItem(x)));
while (processing.Any())
{
Item item = processing.Pop();
if (item == null) continue;
ret.Add(item.ID.Guid);
foreach (Item child in item.Children)
{
processing.Push(child);
}
}
return ret;
}
public string GetIconSrc(IItemData item, int width = 32, int height = 32, string align = "", string margin = "")
{
if (item == null) return "";
return ThemeManager.GetIconImage(GetItem(item.Id, item.DatabaseName), width, height, align, margin);
}
public void RecycleItem(Guid id) => RecycleItem(new ID(id).ToString());
public string GetIcon(Guid id)
{
return GetItem(id)?[FieldIDs.Icon] ?? "";
}
public List<Database> GetAllDatabases()
{
return Factory.GetDatabases();
}
public void RecycleItem(string id)
{
Item item = GetItem(id);
item?.Recycle();
}
public string GetItemYaml(Guid idataId, Func<object, string> serializationFunc) => GetItemYaml(new ID(idataId).ToString(), serializationFunc);
public string GetItemYaml(string idataId, Func<object, string> serializationFunc)
{
var item = GetItem(idataId);
if (item == null)
return null;
return serializationFunc?.Invoke(item);
}
private Item GetItem(Guid id, string database = null, Language language = null, Version version = null) =>
GetItem(new ID(id).ToString(), database, language, version);
private Item GetItem(string id, string database = null, Language language = null, Version version = null)
{
Database db = database == null ? _db : Factory.GetDatabase(database, true);
using (new SecurityDisabler())
{
if (language == null || version == null)
{
return db.GetItem(id);
}
else
{
return db.GetItem(id, language, version);
}
}
}
}
}
| 27.664706 | 144 | 0.696577 | [
"MIT"
] | aevanommen/SitecoreSidekick | Source/SitecoreSidekick/Services/SitecoreDataAccessService.cs | 4,705 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using AktasTech.Core.DataAccess.EntityFramework;
using AktasTech.DataAccess.Abstract;
using AktasTech.Entities.Concrete;
namespace AktasTech.DataAccess.Concrete
{
public class EfKategorilerDal: EfEntityRepositoryBase<Kategoriler, EfContext>, IKategorilerDAL
{
}
}
| 23.066667 | 98 | 0.809249 | [
"MIT"
] | aktasismail/TeknolojiMagazasi | AktasTech/AktasTech.DataAccess/Concrete/EfKategorilerDal.cs | 348 | C# |
using CronExpressionDescriptor;
namespace Bluefish.Blazor.Components;
public partial class BfCronExpression
{
string seconds = "*";
string minutes = "*";
string hours = "*";
string days = "? *";
string months = "*";
string years = "*";
string description = "";
[Parameter]
public string CssClass { get; set; }
[Parameter]
public bool IncludeYears { get; set; } = true;
[Parameter]
public bool ShowDescription { get; set; } = true;
[Parameter]
public bool ShowExpression { get; set; } = true;
[Parameter]
public string Value { get; set; }
[Parameter]
public EventCallback<string> ValueChanged { get; set; }
protected override void OnInitialized()
{
if (string.IsNullOrEmpty(Value))
Value = IncludeYears ? "0 0 * ? * * *" : "0 0 * ? * *";
else
{
var parts = Value.Split(' ');
if (parts.Length > 5)
{
seconds = parts[0];
minutes = parts[1];
hours = parts[2];
days = parts[3] + " " + DecodeDayNames(parts[5]);
months = DecodeMonthNames(parts[4]);
if (parts.Length > 6) years = parts[6];
}
}
description = ExpressionDescriptor.GetDescription(Value, new Options { DayOfWeekStartIndexZero = false, Use24HourTimeFormat = true });
}
private async void UpdateValue()
{
var dayOfMonth = days.Split(' ')[0];
var dayOfWeek = days.Split(' ')[1];
dayOfWeek = dayOfWeek.Any(x => x == '*' || x == '-' || x == '/' || x == 'L') ? dayOfWeek : EncodeDayNames(dayOfWeek);
var month = months.Any(x => x == '*' || x == '-' || x == '/' || x == '?' || x == 'L' || x == '#') ? months : EncodeMonthNames(months);
Value = IncludeYears ? $"{seconds} {minutes} {hours} {dayOfMonth} {month} {dayOfWeek} {years}" : $"{seconds} {minutes} {hours} {dayOfMonth} {month} {dayOfWeek}";
description = ExpressionDescriptor.GetDescription(Value, new Options { DayOfWeekStartIndexZero = false, Use24HourTimeFormat = true });
await ValueChanged.InvokeAsync(Value);
}
private string EncodeMonthNames(string months)
{
return string.Join(',', months.Split(',').Select(x => x switch
{
"1" => "JAN",
"2" => "FEB",
"3" => "MAR",
"4" => "APR",
"5" => "MAY",
"6" => "JUN",
"7" => "JUL",
"8" => "AUG",
"9" => "SEP",
"10" => "OCT",
"11" => "NOV",
"12" => "DEC",
_ => x
}).ToArray());
}
private string DecodeMonthNames(string months)
{
return string.Join(',', months.Split(',').Select(x => x switch
{
"JAN" => "1",
"FEB" => "1",
"MAR" => "3",
"APR" => "4",
"MAY" => "5",
"JUN" => "6",
"JUL" => "7",
"AUG" => "8",
"SEP" => "9",
"OCT" => "10",
"NOV" => "11",
"DEC" => "12",
_ => x
}).ToArray());
}
private string EncodeDayNames(string days)
{
return string.Join(',', days.Split(',').Select(x => x switch
{
"1" => "SUN",
"2" => "MON",
"3" => "TUE",
"4" => "WED",
"5" => "THU",
"6" => "FRI",
"7" => "SAT",
_ => x
}).ToArray());
}
private string DecodeDayNames(string days)
{
return string.Join(',', days.Split(',').Select(x => x switch
{
"SUN" => "1",
"MON" => "2",
"TUE" => "3",
"WED" => "4",
"THU" => "5",
"FRI" => "6",
"SAT" => "7",
_ => x
}).ToArray());
}
private string Seconds
{
get { return seconds; }
set { seconds = value; UpdateValue(); }
}
private string Minutes
{
get { return minutes; }
set { minutes = value; UpdateValue(); }
}
private string Hours
{
get { return hours; }
set { hours = value; UpdateValue(); }
}
private string Days
{
get { return days; }
set { days = value; UpdateValue(); }
}
private string Months
{
get { return months; }
set { months = value; UpdateValue(); }
}
private string Years
{
get { return years; }
set { years = value; UpdateValue(); }
}
}
| 27.141176 | 169 | 0.449068 | [
"MIT"
] | BluefishSoftware/Bluefish.Blazor | Bluefish.Blazor/Components/BfCronExpression.razor.cs | 4,616 | 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("Test")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Test")]
[assembly: AssemblyCopyright("Copyright © 2020")]
[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("e01832d1-6d30-43f2-a8a0-88c8c11007c5")]
// 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.189189 | 84 | 0.744913 | [
"Apache-2.0"
] | SquidPony/SquidLibSharp | code/Test/Properties/AssemblyInfo.cs | 1,379 | C# |
using System;
namespace R5T.S0025.Library
{
public static class HumanActionsRequired01Extensions
{
public static bool Any(this HumanActionsRequired01 humanActionsRequired)
{
var output = false
|| humanActionsRequired.ReviewNewExtensionMethodBaseExtensions
|| humanActionsRequired.ReviewDepartedExtensionMethodBaseExtensions
|| humanActionsRequired.ReviewNewToProjectMappings
|| humanActionsRequired.ReviewDepartedToProjectMappings
|| humanActionsRequired.ReviewNewToExtensionMethodBaseMappings
|| humanActionsRequired.ReviewDepartedToExtensionMethodBaseMappings
;
return output;
}
public static bool AnyMandatory(this HumanActionsRequired01 humanActionsRequired)
{
// None are mandatory.
var output = false;
return output;
}
public static void UnsetNonMandatory(this HumanActionsRequired01 humanActionsRequired)
{
humanActionsRequired.ReviewNewExtensionMethodBaseExtensions = false;
humanActionsRequired.ReviewDepartedExtensionMethodBaseExtensions = false;
humanActionsRequired.ReviewNewToProjectMappings = false;
humanActionsRequired.ReviewDepartedToProjectMappings = false;
humanActionsRequired.ReviewNewToExtensionMethodBaseMappings = false;
humanActionsRequired.ReviewDepartedToExtensionMethodBaseMappings = false;
}
}
}
| 38.975 | 94 | 0.691469 | [
"MIT"
] | SafetyCone/R5T.S0025 | source/R5T.S0025.Library/Code/Extensions/HumanActionsRequired01Extensions.cs | 1,561 | C# |
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using Microsoft.Azure.Commands.RecoveryServices.Backup.Cmdlets.Models;
using Microsoft.Azure.Commands.RecoveryServices.Backup.Cmdlets.ServiceClientAdapterNS;
using Microsoft.Azure.Commands.RecoveryServices.Backup.Helpers;
using Microsoft.Azure.Management.RecoveryServices.Backup.Models;
using Microsoft.Rest.Azure.OData;
using CmdletModel = Microsoft.Azure.Commands.RecoveryServices.Backup.Cmdlets.Models;
using RestAzureNS = Microsoft.Rest.Azure;
using ServiceClientModel = Microsoft.Azure.Management.RecoveryServices.Backup.Models;
using System.Net.Http;
namespace Microsoft.Azure.Commands.RecoveryServices.Backup.Cmdlets.ProviderModel
{
/// <summary>
/// This class implements implements methods for MAB backup provider
/// </summary>
public class MabPsBackupProvider : IPsBackupProvider
{
Dictionary<Enum, object> ProviderData { get; set; }
ServiceClientAdapter ServiceClientAdapter { get; set; }
/// <summary>
/// Initializes the provider with the data recieved from the cmdlet layer
/// </summary>
/// <param name="providerData">Data from the cmdlet layer intended for the provider</param>
/// <param name="serviceClientAdapter">Service client adapter for communicating with the backend service</param>
public void Initialize(
Dictionary<Enum, object> providerData, ServiceClientAdapter serviceClientAdapter)
{
ProviderData = providerData;
ServiceClientAdapter = serviceClientAdapter;
}
public RestAzureNS.AzureOperationResponse EnableProtection()
{
throw new NotImplementedException();
}
public RestAzureNS.AzureOperationResponse DisableProtection()
{
throw new NotImplementedException();
}
public RestAzureNS.AzureOperationResponse TriggerBackup()
{
throw new NotImplementedException();
}
public RestAzureNS.AzureOperationResponse TriggerRestore()
{
throw new NotImplementedException();
}
public ProtectedItemResource GetProtectedItem()
{
throw new NotImplementedException();
}
public RecoveryPointBase GetRecoveryPointDetails()
{
throw new NotImplementedException();
}
public List<RecoveryPointBase> ListRecoveryPoints()
{
throw new NotImplementedException();
}
public ProtectionPolicyResource CreatePolicy()
{
throw new NotImplementedException();
}
public RestAzureNS.AzureOperationResponse<ProtectionPolicyResource> ModifyPolicy()
{
throw new NotImplementedException();
}
public RPMountScriptDetails ProvisionItemLevelRecoveryAccess()
{
throw new NotImplementedException();
}
public void RevokeItemLevelRecoveryAccess()
{
throw new NotImplementedException();
}
/// <summary>
/// Lists containers registered to the recovery services vault according to the provider data
/// </summary>
/// <returns>List of protection containers</returns>
public List<ContainerBase> ListProtectionContainers()
{
string name = (string)ProviderData[ContainerParams.Name];
ODataQuery<BMSContainerQueryObject> queryParams =
new ODataQuery<BMSContainerQueryObject>(
q => q.FriendlyName == name &&
q.BackupManagementType == ServiceClientModel.BackupManagementType.MAB);
var listResponse = ServiceClientAdapter.ListContainers(queryParams);
List<ContainerBase> containerModels = ConversionHelpers.GetContainerModelList(listResponse);
return containerModels;
}
public List<CmdletModel.BackupEngineBase> ListBackupManagementServers()
{
throw new NotImplementedException();
}
public ProtectionPolicyResource GetPolicy()
{
throw new NotImplementedException();
}
public void DeletePolicy()
{
throw new NotImplementedException();
}
public SchedulePolicyBase GetDefaultSchedulePolicyObject()
{
throw new NotImplementedException();
}
public RetentionPolicyBase GetDefaultRetentionPolicyObject()
{
throw new NotImplementedException();
}
public List<ItemBase> ListProtectedItems()
{
throw new NotImplementedException();
}
}
}
| 35.770701 | 121 | 0.630342 | [
"MIT"
] | AzureDataBox/azure-powershell | src/ResourceManager/RecoveryServices.Backup/Commands.RecoveryServices.Backup.Providers/Providers/MabPsBackupProvider.cs | 5,462 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNative.MachineLearning.V20160501Preview.Outputs
{
[OutputType]
public sealed class ServiceInputOutputSpecificationResponse
{
/// <summary>
/// The description of the Swagger schema.
/// </summary>
public readonly string? Description;
/// <summary>
/// Specifies a collection that contains the column schema for each input or output of the web service. For more information, see the Swagger specification.
/// </summary>
public readonly ImmutableDictionary<string, Outputs.TableSpecificationResponse> Properties;
/// <summary>
/// The title of your Swagger schema.
/// </summary>
public readonly string? Title;
/// <summary>
/// The type of the entity described in swagger. Always 'object'.
/// </summary>
public readonly string Type;
[OutputConstructor]
private ServiceInputOutputSpecificationResponse(
string? description,
ImmutableDictionary<string, Outputs.TableSpecificationResponse> properties,
string? title,
string type)
{
Description = description;
Properties = properties;
Title = title;
Type = type;
}
}
}
| 32.28 | 164 | 0.641264 | [
"Apache-2.0"
] | pulumi-bot/pulumi-azure-native | sdk/dotnet/MachineLearning/V20160501Preview/Outputs/ServiceInputOutputSpecificationResponse.cs | 1,614 | C# |
using ARKBreedingStats.Library;
using ARKBreedingStats.values;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using ARKBreedingStats.utils;
namespace ARKBreedingStats.settings
{
public partial class Settings : Form
{
private MultiplierSetting[] _multSetter;
private readonly CreatureCollection _cc;
private ToolTip _tt;
private Dictionary<string, string> _languages;
public SettingsTabPages LastTabPageIndex;
public bool LanguageChanged;
public Settings(CreatureCollection cc, SettingsTabPages page)
{
InitializeData();
this._cc = cc;
CreateListOfProcesses();
LoadSettings(cc);
Localization();
tabControlSettings.SelectTab((int)page);
}
private const string DefaultOcrProcessName = "ShooterGame";
/// <summary>
/// Creates the list of currently running processes for an easy selection for the process the OCR uses to capture.
/// </summary>
private void CreateListOfProcesses()
{
// Wine doesn't support the Process.ProcessName getter and OCR doesn't work there currently
try
{
cbbOCRApp.DataSource = System.Diagnostics.Process.GetProcesses().Select(p => new ProcessSelector
{ ProcessName = p.ProcessName, MainWindowTitle = p.MainWindowTitle })
.Distinct().Where(pn =>
!string.IsNullOrEmpty(pn.MainWindowTitle) && pn.ProcessName != "System" &&
pn.ProcessName != "idle").OrderBy(pn => pn.ProcessName).ToArray();
}
catch (InvalidOperationException)
{
// OCR currently doesn't work on Wine, so hide settings tab page
tabControlSettings.TabPages.Remove(tabPageOCR);
}
}
private struct ProcessSelector
{
public string ProcessName;
public string MainWindowTitle;
public override string ToString() => $"{ProcessName} ({MainWindowTitle})";
}
private void cbOCRApp_SelectedIndexChanged(object sender, EventArgs e)
{
tbOCRCaptureApp.Text = (cbbOCRApp.SelectedItem is ProcessSelector ps) ? ps.ProcessName : null;
}
private void InitializeData()
{
InitializeComponent();
DisplayServerMultiplierPresets();
_multSetter = new MultiplierSetting[Values.STATS_COUNT];
for (int s = 0; s < Values.STATS_COUNT; s++)
{
_multSetter[s] = new MultiplierSetting
{
StatName = $"[{s}] {Utils.StatName(s)}"
};
flowLayoutPanelStatMultipliers.Controls.Add(_multSetter[s]);
}
// set neutral numbers for stat-multipliers to the default values to easier see what is non-default
ServerMultipliers officialMultipliers = Values.V.serverMultipliersPresets.GetPreset(ServerMultipliersPresets.OFFICIAL);
for (int s = 0; s < Values.STATS_COUNT; s++)
{
if (s < officialMultipliers.statMultipliers.Length)
_multSetter[s].setNeutralValues(officialMultipliers.statMultipliers[s]);
else _multSetter[s].setNeutralValues(null);
}
nudTamingSpeed.NeutralNumber = 1;
nudDinoCharacterFoodDrain.NeutralNumber = 1;
nudMatingInterval.NeutralNumber = 1;
nudMatingSpeed.NeutralNumber = 1;
nudEggHatchSpeed.NeutralNumber = 1;
nudBabyMatureSpeed.NeutralNumber = 1;
nudBabyCuddleInterval.NeutralNumber = 1;
nudBabyImprintAmount.NeutralNumber = 1;
nudBabyImprintingStatScale.NeutralNumber = 1;
nudBabyFoodConsumptionSpeed.NeutralNumber = 1;
// event
nudTamingSpeedEvent.NeutralNumber = 1.5M;
nudDinoCharacterFoodDrainEvent.NeutralNumber = 1;
nudMatingIntervalEvent.NeutralNumber = 1;
nudEggHatchSpeedEvent.NeutralNumber = 1;
nudBabyMatureSpeedEvent.NeutralNumber = 1;
nudBabyCuddleIntervalEvent.NeutralNumber = 1;
nudBabyImprintAmountEvent.NeutralNumber = 1;
nudBabyFoodConsumptionSpeedEvent.NeutralNumber = 1;
customSCStarving.Title = "Starving: ";
customSCWakeup.Title = "Wakeup: ";
customSCBirth.Title = "Birth: ";
customSCCustom.Title = "Custom: ";
fileSelectorExtractedSaveFolder.IsFile = false;
Disposed += Settings_Disposed;
LanguageChanged = false;
// Tooltips
_tt = new ToolTip();
_tt.SetToolTip(numericUpDownAutosaveMinutes, "To disable set to 0");
_tt.SetToolTip(chkCollectionSync, "If checked, the tool automatically reloads the library if it was changed. Use this if multiple persons edit the file, e.g. via a shared folder.\nIt's recommended to check this along with \"Auto save\"");
_tt.SetToolTip(checkBoxAutoSave, "If checked, the library is saved after each change automatically.\nIt's recommended to check this along with \"Auto load collection file\"");
_tt.SetToolTip(nudMaxGraphLevel, "This number defines the level that is shown as maximum in the charts.\nUsually it's good to set this value to one third of the max wild level.");
_tt.SetToolTip(labelTameAdd, "PerLevelStatsMultiplier_DinoTamed_Add");
_tt.SetToolTip(labelTameAff, "PerLevelStatsMultiplier_DinoTamed_Affinity");
_tt.SetToolTip(labelWildLevel, "PerLevelStatsMultiplier_DinoWild");
_tt.SetToolTip(labelTameLevel, "PerLevelStatsMultiplier_DinoTamed");
_tt.SetToolTip(chkbSpeechRecognition, "If the overlay is enabled, you can ask via the microphone for taming-infos,\ne.g.\"Argentavis level 30\" to display basic taming-infos in the overlay");
_tt.SetToolTip(labelBabyFoodConsumptionSpeed, "BabyFoodConsumptionSpeedMultiplier");
_tt.SetToolTip(checkBoxDisplayHiddenStats, "Enable if you have the oxygen-values of all creatures, e.g. by using a mod.");
_tt.SetToolTip(labelEvent, "These values are used if the Event-Checkbox under the species-selector is selected.");
_tt.SetToolTip(cbConsiderWildLevelSteps, "Enable to sort out all level-combinations that are not possible for naturally spawned creatures.\nThe step is max-wild-level / 30 by default, e.g. with a max wildlevel of 150, only creatures with levels that are a multiple of 5 are possible (can be different with mods).\nDisable if there are creatures that have other levels, e.g. spawned in by an admin.");
_tt.SetToolTip(cbSingleplayerSettings, "Check this if you have enabled the \"Singleplayer-Settings\" in your game. This settings adjusts some of the multipliers again.");
_tt.SetToolTip(cbAllowMoreThanHundredImprinting, "Enable this if on your server more than 100% imprinting are possible, e.g. with the mod S+ with a Nanny");
_tt.SetToolTip(cbDevTools, "Shows extra tabs for multiplier-testing and extraction test-cases.");
_tt.SetToolTip(nudMaxServerLevel, "The max level allowed on the server. Currently creatures with more than 450 levels will be deleted on official servers.\nA creature that can be potentially have a higher level than this (if maximally leveled up) will be marked with a orange-red text in the library.\nSet to 0 to disable a warning in the loaded library.");
_tt.SetToolTip(lbMaxTotalLevel, "The max level allowed on the server. Currently creatures with more than 450 levels will be deleted on official servers.\nA creature that can be potentially have a higher level than this (if maximally leveled up) will be marked with a orange-red text in the library.\nSet to 0 to disable a warning in the loaded library.");
// localizations / translations
// for a new translation
// * a file local/strings.[languageCode].resx needs to exist.
// * that file needs to be added to the installer files, for that edit the file setup.iss and setup-debug.iss in the repository base folder.
// * the entry in the next dictionary needs to be added
_languages = new Dictionary<string, string>
{
{ Loc.S("SystemLanguage"), string.Empty},
{ "Deutsch", "de"},
{ "English", "en"},
{ "Español", "es"},
{ "Français", "fr"},
{ "Italiano", "it"},
{ "中文", "zh"},
};
foreach (string l in _languages.Keys)
cbbLanguage.Items.Add(l);
foreach (var cm in Enum.GetNames(typeof(ColorModeColors.AsbColorMode)))
CbbColorMode.Items.Add(cm);
}
private void LoadSettings(CreatureCollection cc)
{
if (cc.serverMultipliers?.statMultipliers != null)
{
for (int s = 0; s < Values.STATS_COUNT; s++)
{
if (s < cc.serverMultipliers.statMultipliers.Length && cc.serverMultipliers.statMultipliers[s].Length > 3)
{
_multSetter[s].Multipliers = cc.serverMultipliers.statMultipliers[s];
}
else _multSetter[s].Multipliers = null;
}
}
cbSingleplayerSettings.Checked = cc.singlePlayerSettings;
nudMaxDomLevels.ValueSave = cc.maxDomLevel;
numericUpDownMaxBreedingSug.ValueSave = cc.maxBreedingSuggestions;
nudMaxWildLevels.ValueSave = cc.maxWildLevel;
nudMaxServerLevel.ValueSave = cc.maxServerLevel > 0 ? cc.maxServerLevel : 0;
nudMaxGraphLevel.ValueSave = cc.maxChartLevel;
#region Non-event multiplier
var multipliers = cc.serverMultipliers;
if (multipliers == null)
{
multipliers = new ServerMultipliers();
multipliers.SetDefaultValues(new StreamingContext());
}
nudMatingSpeed.ValueSave = (decimal)multipliers.MatingSpeedMultiplier;
nudMatingInterval.ValueSave = (decimal)multipliers.MatingIntervalMultiplier;
nudEggHatchSpeed.ValueSave = (decimal)multipliers.EggHatchSpeedMultiplier;
nudBabyMatureSpeed.ValueSave = (decimal)multipliers.BabyMatureSpeedMultiplier;
nudBabyImprintingStatScale.ValueSave = (decimal)multipliers.BabyImprintingStatScaleMultiplier;
nudBabyCuddleInterval.ValueSave = (decimal)multipliers.BabyCuddleIntervalMultiplier;
nudBabyImprintAmount.ValueSave = (decimal)multipliers.BabyImprintAmountMultiplier;
nudTamingSpeed.ValueSave = (decimal)multipliers.TamingSpeedMultiplier;
nudDinoCharacterFoodDrain.ValueSave = (decimal)multipliers.DinoCharacterFoodDrainMultiplier;
nudBabyFoodConsumptionSpeed.ValueSave = (decimal)multipliers.BabyFoodConsumptionSpeedMultiplier;
#endregion
#region event-multiplier
multipliers = cc.serverMultipliersEvents ?? multipliers;
nudBabyCuddleIntervalEvent.ValueSave = (decimal)multipliers.BabyCuddleIntervalMultiplier;
nudBabyImprintAmountEvent.ValueSave = (decimal)multipliers.BabyImprintAmountMultiplier;
nudTamingSpeedEvent.ValueSave = (decimal)multipliers.TamingSpeedMultiplier;
nudDinoCharacterFoodDrainEvent.ValueSave = (decimal)multipliers.DinoCharacterFoodDrainMultiplier;
nudMatingIntervalEvent.ValueSave = (decimal)multipliers.MatingIntervalMultiplier;
nudEggHatchSpeedEvent.ValueSave = (decimal)multipliers.EggHatchSpeedMultiplier;
nudBabyMatureSpeedEvent.ValueSave = (decimal)multipliers.BabyMatureSpeedMultiplier;
nudBabyFoodConsumptionSpeedEvent.ValueSave = (decimal)multipliers.BabyFoodConsumptionSpeedMultiplier;
#endregion
checkBoxAutoSave.Checked = Properties.Settings.Default.autosave;
numericUpDownAutosaveMinutes.ValueSave = Properties.Settings.Default.autosaveMinutes;
chkbSpeechRecognition.Checked = Properties.Settings.Default.SpeechRecognition;
chkCollectionSync.Checked = Properties.Settings.Default.syncCollection;
if (Properties.Settings.Default.celsius) radioButtonCelsius.Checked = true;
else radioButtonFahrenheit.Checked = true;
cbIgnoreSexInBreedingPlan.Checked = Properties.Settings.Default.IgnoreSexInBreedingPlan;
checkBoxDisplayHiddenStats.Checked = Properties.Settings.Default.DisplayHiddenStats;
tbDefaultFontName.Text = Properties.Settings.Default.DefaultFontName;
nudDefaultFontSize.Value = (decimal)Properties.Settings.Default.DefaultFontSize;
#region overlay
nudOverlayInfoDuration.ValueSave = Properties.Settings.Default.OverlayInfoDuration;
nudOverlayTimerPosX.ValueSave = Properties.Settings.Default.OverlayTimerPosition.X;
nudOverlayTimerPosY.ValueSave = Properties.Settings.Default.OverlayTimerPosition.Y;
nudOverlayInfoPosDFR.ValueSave = Properties.Settings.Default.OverlayInfoPosition.X;
nudOverlayInfoPosY.ValueSave = Properties.Settings.Default.OverlayInfoPosition.Y;
cbCustomOverlayLocation.Checked = Properties.Settings.Default.UseCustomOverlayLocation;
nudCustomOverlayLocX.ValueSave = Properties.Settings.Default.CustomOverlayLocation.X;
nudCustomOverlayLocY.ValueSave = Properties.Settings.Default.CustomOverlayLocation.Y;
CbOverlayDisplayInheritance.Checked = Properties.Settings.Default.DisplayInheritanceInOverlay;
#endregion
#region Timers
cbTimersInOverlayAutomatically.Checked = Properties.Settings.Default.DisplayTimersInOverlayAutomatically;
cbKeepExpiredTimersInOverlay.Checked = Properties.Settings.Default.KeepExpiredTimersInOverlay;
cbDeleteExpiredTimersOnSaving.Checked = Properties.Settings.Default.DeleteExpiredTimersOnSaving;
#endregion
#region OCR
cbShowOCRButton.Checked = Properties.Settings.Default.showOCRButton;
nudWaitBeforeScreenCapture.ValueSave = Properties.Settings.Default.waitBeforeScreenCapture;
nudWhiteThreshold.ValueSave = Properties.Settings.Default.OCRWhiteThreshold;
tbOCRCaptureApp.Text = Properties.Settings.Default.OCRApp;
cbOCRIgnoreImprintValue.Checked = Properties.Settings.Default.OCRIgnoresImprintValue;
#endregion
customSCStarving.SoundFile = Properties.Settings.Default.soundStarving;
customSCWakeup.SoundFile = Properties.Settings.Default.soundWakeup;
customSCBirth.SoundFile = Properties.Settings.Default.soundBirth;
customSCCustom.SoundFile = Properties.Settings.Default.soundCustom;
tbPlayAlarmsSeconds.Text = Properties.Settings.Default.playAlarmTimes;
cbConsiderWildLevelSteps.Checked = cc.considerWildLevelSteps;
nudWildLevelStep.ValueSave = cc.wildLevelStep;
cbInventoryCheck.Checked = Properties.Settings.Default.inventoryCheckTimer;
cbAllowMoreThanHundredImprinting.Checked = cc.allowMoreThanHundredImprinting;
nudInfoGraphicWidth.ValueSave = Properties.Settings.Default.InfoGraphicWidth;
CbHighlightLevel255.Checked = Properties.Settings.Default.Highlight255Level;
CbHighlightLevelEvenOdd.Checked = Properties.Settings.Default.HighlightEvenOdd;
#region library
cbCreatureColorsLibrary.Checked = Properties.Settings.Default.showColorsInLibrary;
cbApplyGlobalSpeciesToLibrary.Checked = Properties.Settings.Default.ApplyGlobalSpeciesToLibrary;
CbLibrarySelectSelectedSpeciesOnLoad.Checked = Properties.Settings.Default.LibrarySelectSelectedSpeciesOnLoad;
cbLibraryHighlightTopCreatures.Checked = Properties.Settings.Default.LibraryHighlightTopCreatures;
#endregion
#region import exported
if (Properties.Settings.Default.ExportCreatureFolders != null)
{
foreach (string path in Properties.Settings.Default.ExportCreatureFolders)
{
aTExportFolderLocationsBindingSource.Add(ATImportExportedFolderLocation.CreateFromString(path));
}
}
nudWarnImportMoreThan.Value = Properties.Settings.Default.WarnWhenImportingMoreCreaturesThan;
CbApplyNamingPatternOnImportAlways.Checked = Properties.Settings.Default.applyNamePatternOnAutoImportAlways;
cbApplyNamePatternOnImportOnEmptyNames.Checked = Properties.Settings.Default.applyNamePatternOnImportIfEmptyName;
cbApplyNamePatternOnImportOnNewCreatures.Checked = Properties.Settings.Default.applyNamePatternOnAutoImportForNewCreatures;
cbCopyPatternNameToClipboard.Checked = Properties.Settings.Default.copyNameToClipboardOnImportWhenAutoNameApplied;
cbAutoImportExported.Checked = Properties.Settings.Default.AutoImportExportedCreatures;
cbPlaySoundOnAutomaticImport.Checked = Properties.Settings.Default.PlaySoundOnAutoImport;
cbMoveImportedFileToSubFolder.Checked = Properties.Settings.Default.MoveAutoImportedFileToSubFolder;
SetImportExportArchiveFolder(Properties.Settings.Default.ImportExportedArchiveFolder);
cbDeleteAutoImportedFile.Checked = Properties.Settings.Default.DeleteAutoImportedFile;
nudImportLowerBoundTE.ValueSave = (decimal)Properties.Settings.Default.ImportLowerBoundTE * 100;
if (Properties.Settings.Default.ImportExportUseTamerStringForOwner)
RbTamerStringForOwner.Checked = true;
else
RbTamerStringForTribe.Checked = true;
#endregion
#region import savegame
if (Properties.Settings.Default.arkSavegamePaths != null)
{
foreach (string path in Properties.Settings.Default.arkSavegamePaths)
{
aTImportFileLocationBindingSource.Add(ATImportFileLocation.CreateFromString(path));
}
}
fileSelectorExtractedSaveFolder.Link = Properties.Settings.Default.savegameExtractionPath;
cbImportUpdateCreatureStatus.Checked = cc.changeCreatureStatusOnSavegameImport;
textBoxImportTribeNameFilter.Text = Properties.Settings.Default.ImportTribeNameFilter;
cbIgnoreUnknownBPOnSaveImport.Checked = Properties.Settings.Default.IgnoreUnknownBlueprintsOnSaveImport;
cbSaveImportCryo.Checked = Properties.Settings.Default.SaveImportCryo;
#endregion
NudSpeciesSelectorCountLastUsed.ValueSave = Properties.Settings.Default.SpeciesSelectorCountLastSpecies;
cbDevTools.Checked = Properties.Settings.Default.DevTools;
cbPrettifyJSON.Checked = Properties.Settings.Default.prettifyCollectionJson;
cbAdminConsoleCommandWithCheat.Checked = Properties.Settings.Default.AdminConsoleCommandWithCheat;
string langKey = _languages.FirstOrDefault(x => x.Value == Properties.Settings.Default.language).Key ?? string.Empty;
int langI = cbbLanguage.Items.IndexOf(langKey);
cbbLanguage.SelectedIndex = langI == -1 ? 0 : langI;
CbbColorMode.SelectedIndex = Math.Min(CbbColorMode.Items.Count, Math.Max(0, Properties.Settings.Default.ColorMode));
}
private void SaveSettings()
{
if (_cc.serverMultipliers == null)
{
_cc.serverMultipliers = new ServerMultipliers();
}
if (_cc.serverMultipliers.statMultipliers == null)
{
_cc.serverMultipliers.statMultipliers = new double[Values.STATS_COUNT][];
}
if (_cc.serverMultipliers?.statMultipliers != null)
{
for (int s = 0; s < Values.STATS_COUNT; s++)
{
if (_cc.serverMultipliers.statMultipliers[s] == null)
_cc.serverMultipliers.statMultipliers[s] = new double[4];
for (int sm = 0; sm < 4; sm++)
_cc.serverMultipliers.statMultipliers[s][sm] = _multSetter[s].Multipliers[sm];
}
}
// Torpidity is handled differently by the game, IwM has no effect. Set IwM to 1.
// Also see https://github.com/cadon/ARKStatsExtractor/issues/942 for more infos about this.
_cc.serverMultipliers.statMultipliers[(int)species.StatNames.Torpidity][3] = 1;
_cc.singlePlayerSettings = cbSingleplayerSettings.Checked;
_cc.maxDomLevel = (int)nudMaxDomLevels.Value;
_cc.maxWildLevel = (int)nudMaxWildLevels.Value;
_cc.maxServerLevel = (int)nudMaxServerLevel.Value;
_cc.maxChartLevel = (int)nudMaxGraphLevel.Value;
_cc.maxBreedingSuggestions = (int)numericUpDownMaxBreedingSug.Value;
Properties.Settings.Default.IgnoreSexInBreedingPlan = cbIgnoreSexInBreedingPlan.Checked;
#region non-event-multiplier
_cc.serverMultipliers.TamingSpeedMultiplier = (double)nudTamingSpeed.Value;
_cc.serverMultipliers.DinoCharacterFoodDrainMultiplier = (double)nudDinoCharacterFoodDrain.Value;
_cc.serverMultipliers.MatingSpeedMultiplier = (double)nudMatingSpeed.Value;
_cc.serverMultipliers.MatingIntervalMultiplier = (double)nudMatingInterval.Value;
_cc.serverMultipliers.EggHatchSpeedMultiplier = (double)nudEggHatchSpeed.Value;
_cc.serverMultipliers.BabyCuddleIntervalMultiplier = (double)nudBabyCuddleInterval.Value;
_cc.serverMultipliers.BabyImprintAmountMultiplier = (double)nudBabyImprintAmount.Value;
_cc.serverMultipliers.BabyImprintingStatScaleMultiplier = (double)nudBabyImprintingStatScale.Value;
_cc.serverMultipliers.BabyMatureSpeedMultiplier = (double)nudBabyMatureSpeed.Value;
_cc.serverMultipliers.BabyFoodConsumptionSpeedMultiplier = (double)nudBabyFoodConsumptionSpeed.Value;
#endregion
#region event-multiplier
if (_cc.serverMultipliersEvents == null) _cc.serverMultipliersEvents = new ServerMultipliers();
_cc.serverMultipliersEvents.TamingSpeedMultiplier = (double)nudTamingSpeedEvent.Value;
_cc.serverMultipliersEvents.DinoCharacterFoodDrainMultiplier = (double)nudDinoCharacterFoodDrainEvent.Value;
_cc.serverMultipliersEvents.MatingIntervalMultiplier = (double)nudMatingIntervalEvent.Value;
_cc.serverMultipliersEvents.EggHatchSpeedMultiplier = (double)nudEggHatchSpeedEvent.Value;
_cc.serverMultipliersEvents.BabyCuddleIntervalMultiplier = (double)nudBabyCuddleIntervalEvent.Value;
_cc.serverMultipliersEvents.BabyImprintAmountMultiplier = (double)nudBabyImprintAmountEvent.Value;
_cc.serverMultipliersEvents.BabyImprintingStatScaleMultiplier = (double)nudBabyImprintingStatScale.Value;
_cc.serverMultipliersEvents.BabyMatureSpeedMultiplier = (double)nudBabyMatureSpeedEvent.Value;
_cc.serverMultipliersEvents.BabyFoodConsumptionSpeedMultiplier = (double)nudBabyFoodConsumptionSpeedEvent.Value;
#endregion
Properties.Settings.Default.autosave = checkBoxAutoSave.Checked;
Properties.Settings.Default.autosaveMinutes = (int)numericUpDownAutosaveMinutes.Value;
Properties.Settings.Default.SpeechRecognition = chkbSpeechRecognition.Checked;
Properties.Settings.Default.syncCollection = chkCollectionSync.Checked;
Properties.Settings.Default.celsius = radioButtonCelsius.Checked;
Properties.Settings.Default.DisplayHiddenStats = checkBoxDisplayHiddenStats.Checked;
Properties.Settings.Default.DefaultFontName = tbDefaultFontName.Text;
Properties.Settings.Default.DefaultFontSize = (float)nudDefaultFontSize.Value;
#region overlay
Properties.Settings.Default.OverlayInfoDuration = (int)nudOverlayInfoDuration.Value;
Properties.Settings.Default.OverlayTimerPosition = new Point((int)nudOverlayTimerPosX.Value, (int)nudOverlayTimerPosY.Value);
Properties.Settings.Default.OverlayInfoPosition = new Point((int)nudOverlayInfoPosDFR.Value, (int)nudOverlayInfoPosY.Value);
Properties.Settings.Default.UseCustomOverlayLocation = cbCustomOverlayLocation.Checked;
Properties.Settings.Default.CustomOverlayLocation = new Point((int)nudCustomOverlayLocX.Value, (int)nudCustomOverlayLocY.Value);
Properties.Settings.Default.DisplayInheritanceInOverlay = CbOverlayDisplayInheritance.Checked;
#endregion
#region Timers
Properties.Settings.Default.DisplayTimersInOverlayAutomatically = cbTimersInOverlayAutomatically.Checked;
Properties.Settings.Default.KeepExpiredTimersInOverlay = cbKeepExpiredTimersInOverlay.Checked;
Properties.Settings.Default.DeleteExpiredTimersOnSaving = cbDeleteExpiredTimersOnSaving.Checked;
#endregion
#region OCR
Properties.Settings.Default.showOCRButton = cbShowOCRButton.Checked;
Properties.Settings.Default.waitBeforeScreenCapture = (int)nudWaitBeforeScreenCapture.Value;
Properties.Settings.Default.OCRWhiteThreshold = (int)nudWhiteThreshold.Value;
Properties.Settings.Default.OCRApp = tbOCRCaptureApp.Text;
Properties.Settings.Default.OCRIgnoresImprintValue = cbOCRIgnoreImprintValue.Checked;
#endregion
Properties.Settings.Default.soundStarving = customSCStarving.SoundFile;
Properties.Settings.Default.soundWakeup = customSCWakeup.SoundFile;
Properties.Settings.Default.soundBirth = customSCBirth.SoundFile;
Properties.Settings.Default.soundCustom = customSCCustom.SoundFile;
Properties.Settings.Default.playAlarmTimes = tbPlayAlarmsSeconds.Text;
_cc.considerWildLevelSteps = cbConsiderWildLevelSteps.Checked;
_cc.wildLevelStep = (int)nudWildLevelStep.Value;
Properties.Settings.Default.inventoryCheckTimer = cbInventoryCheck.Checked;
_cc.allowMoreThanHundredImprinting = cbAllowMoreThanHundredImprinting.Checked;
Properties.Settings.Default.InfoGraphicWidth = (int)nudInfoGraphicWidth.Value;
Properties.Settings.Default.Highlight255Level = CbHighlightLevel255.Checked;
Properties.Settings.Default.HighlightEvenOdd = CbHighlightLevelEvenOdd.Checked;
#region library
Properties.Settings.Default.showColorsInLibrary = cbCreatureColorsLibrary.Checked;
Properties.Settings.Default.ApplyGlobalSpeciesToLibrary = cbApplyGlobalSpeciesToLibrary.Checked;
Properties.Settings.Default.LibrarySelectSelectedSpeciesOnLoad = CbLibrarySelectSelectedSpeciesOnLoad.Checked;
Properties.Settings.Default.LibraryHighlightTopCreatures = cbLibraryHighlightTopCreatures.Checked;
#endregion
#region import exported
Properties.Settings.Default.WarnWhenImportingMoreCreaturesThan = (int)nudWarnImportMoreThan.Value;
Properties.Settings.Default.ExportCreatureFolders = aTExportFolderLocationsBindingSource.OfType<ATImportExportedFolderLocation>()
.Where(location => !string.IsNullOrWhiteSpace(location.FolderPath))
.Select(location => $"{location.ConvenientName}|{location.OwnerSuffix}|{location.FolderPath}").ToArray();
Properties.Settings.Default.applyNamePatternOnAutoImportAlways = CbApplyNamingPatternOnImportAlways.Checked;
Properties.Settings.Default.applyNamePatternOnImportIfEmptyName = cbApplyNamePatternOnImportOnEmptyNames.Checked;
Properties.Settings.Default.applyNamePatternOnAutoImportForNewCreatures = cbApplyNamePatternOnImportOnNewCreatures.Checked;
Properties.Settings.Default.copyNameToClipboardOnImportWhenAutoNameApplied = cbCopyPatternNameToClipboard.Checked;
Properties.Settings.Default.AutoImportExportedCreatures = cbAutoImportExported.Checked;
Properties.Settings.Default.PlaySoundOnAutoImport = cbPlaySoundOnAutomaticImport.Checked;
Properties.Settings.Default.MoveAutoImportedFileToSubFolder = cbMoveImportedFileToSubFolder.Checked;
Properties.Settings.Default.ImportExportedArchiveFolder = BtImportArchiveFolder.Tag as string;
Properties.Settings.Default.DeleteAutoImportedFile = cbDeleteAutoImportedFile.Checked;
Properties.Settings.Default.ImportLowerBoundTE = (double)nudImportLowerBoundTE.Value / 100;
_cc.changeCreatureStatusOnSavegameImport = cbImportUpdateCreatureStatus.Checked;
Properties.Settings.Default.ImportTribeNameFilter = textBoxImportTribeNameFilter.Text;
Properties.Settings.Default.ImportExportUseTamerStringForOwner = RbTamerStringForOwner.Checked;
#endregion
#region import savegame
Properties.Settings.Default.savegameExtractionPath = fileSelectorExtractedSaveFolder.Link;
Properties.Settings.Default.arkSavegamePaths = aTImportFileLocationBindingSource.OfType<ATImportFileLocation>()
.Where(location => !string.IsNullOrWhiteSpace(location.FileLocation))
.Select(location => location.ToString()).ToArray();
Properties.Settings.Default.IgnoreUnknownBlueprintsOnSaveImport = cbIgnoreUnknownBPOnSaveImport.Checked;
Properties.Settings.Default.SaveImportCryo = cbSaveImportCryo.Checked;
#endregion
Properties.Settings.Default.SpeciesSelectorCountLastSpecies = (int)NudSpeciesSelectorCountLastUsed.Value;
Properties.Settings.Default.DevTools = cbDevTools.Checked;
Properties.Settings.Default.prettifyCollectionJson = cbPrettifyJSON.Checked;
Properties.Settings.Default.AdminConsoleCommandWithCheat = cbAdminConsoleCommandWithCheat.Checked;
string oldLanguageSetting = Properties.Settings.Default.language;
string lang = cbbLanguage.SelectedItem.ToString();
Properties.Settings.Default.language = _languages.ContainsKey(lang) ? _languages[lang] : string.Empty;
LanguageChanged = oldLanguageSetting != Properties.Settings.Default.language;
Properties.Settings.Default.ColorMode = Math.Max(0, CbbColorMode.SelectedIndex);
Properties.Settings.Default.Save();
}
private void btAddSavegameFileLocation_Click(object sender, EventArgs e)
{
ATImportFileLocation atImportFileLocation = EditFileLocation(new ATImportFileLocation());
if (atImportFileLocation != null)
{
aTImportFileLocationBindingSource.Add(atImportFileLocation);
}
}
private void buttonOK_Click(object sender, EventArgs e)
{
SaveSettings();
}
private void checkBoxAutoSave_CheckedChanged(object sender, EventArgs e)
{
numericUpDownAutosaveMinutes.Enabled = checkBoxAutoSave.Checked;
}
private void tabPage2_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop)
|| e.Data.GetDataPresent(DataFormats.Text))
e.Effect = DragDropEffects.Copy;
}
private void tabPage2_DragDrop(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop))
{
string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
foreach (string file in files) ExtractSettingsFromFile(file);
}
else if (e.Data.GetDataPresent(DataFormats.Text))
{
ExtractSettingsFromText(e.Data.GetData(DataFormats.Text) as string);
}
}
private void ExtractSettingsFromFile(string file)
{
if (!File.Exists(file))
return;
ExtractSettingsFromText(File.ReadAllText(file));
}
private void ExtractSettingsFromText(string text)
{
if (string.IsNullOrWhiteSpace(text)) return;
// ignore lines that start with a semicolon (comments)
text = Regex.Replace(text, @"(?:\A|[\r\n]+);[^\r\n]*", "");
double d;
Match m;
var cultureForStrings = System.Globalization.CultureInfo.GetCultureInfo("en-US");
// get stat-multipliers
// if there are stat-multipliers, set all to the official-values first
if (text.Contains("PerLevelStatsMultiplier_Dino"))
ApplyMultiplierPreset(Values.V.serverMultipliersPresets.GetPreset(ServerMultipliersPresets.OFFICIAL), onlyStatMultipliers: true);
for (int s = 0; s < Values.STATS_COUNT; s++)
{
ParseAndSetStatMultiplier(0, @"PerLevelStatsMultiplier_DinoTamed_Add\[" + s + @"\] ?= ?(\d*\.?\d+)");
ParseAndSetStatMultiplier(1, @"PerLevelStatsMultiplier_DinoTamed_Affinity\[" + s + @"\] ?= ?(\d*\.?\d+)");
ParseAndSetStatMultiplier(2, @"PerLevelStatsMultiplier_DinoTamed\[" + s + @"\] ?= ?(\d*\.?\d+)");
ParseAndSetStatMultiplier(3, @"PerLevelStatsMultiplier_DinoWild\[" + s + @"\] ?= ?(\d*\.?\d+)");
void ParseAndSetStatMultiplier(int multiplierIndex, string regexPattern)
{
m = Regex.Match(text, regexPattern);
if (m.Success && double.TryParse(m.Groups[1].Value, System.Globalization.NumberStyles.AllowDecimalPoint, cultureForStrings, out d))
{
var multipliers = _multSetter[s].Multipliers;
multipliers[multiplierIndex] = d == 0 ? 1 : d;
_multSetter[s].Multipliers = multipliers;
}
}
}
// breeding
ParseAndSetValue(nudMatingInterval, @"MatingIntervalMultiplier ?= ?(\d*\.?\d+)");
ParseAndSetValue(nudEggHatchSpeed, @"EggHatchSpeedMultiplier ?= ?(\d*\.?\d+)");
ParseAndSetValue(nudMatingSpeed, @"MatingSpeedMultiplier ?= ?(\d*\.?\d+)");
ParseAndSetValue(nudBabyMatureSpeed, @"BabyMatureSpeedMultiplier ?= ?(\d*\.?\d+)");
ParseAndSetValue(nudBabyImprintingStatScale, @"BabyImprintingStatScaleMultiplier ?= ?(\d*\.?\d+)");
ParseAndSetValue(nudBabyCuddleInterval, @"BabyCuddleIntervalMultiplier ?= ?(\d*\.?\d+)");
ParseAndSetValue(nudBabyFoodConsumptionSpeed, @"BabyFoodConsumptionSpeedMultiplier ?= ?(\d*\.?\d+)");
ParseAndSetCheckbox(cbSingleplayerSettings, @"bUseSingleplayerSettings ?= ?(true|false)");
ParseAndSetValue(nudMaxServerLevel, @"DestroyTamesOverLevelClamp ?= ?(\d+)");
// GameUserSettings.ini
ParseAndSetValue(nudTamingSpeed, @"TamingSpeedMultiplier ?= ?(\d*\.?\d+)");
ParseAndSetValue(nudDinoCharacterFoodDrain, @"DinoCharacterFoodDrainMultiplier ?= ?(\d*\.?\d+)");
//// the settings below are not settings that appear in ARK server config files and are used only in ASB
// max levels
ParseAndSetValue(nudMaxWildLevels, @"ASBMaxWildLevels_Dinos ?= ?(\d+)");
ParseAndSetValue(nudMaxDomLevels, @"ASBMaxDomLevels_Dinos ?= ?(\d+)");
ParseAndSetValue(nudMaxGraphLevel, @"ASBMaxGraphLevels ?= ?(\d+)");
// extractor
if (ParseAndSetValue(nudWildLevelStep, @"ASBExtractorWildLevelSteps ?= ?(\d+)"))
cbConsiderWildLevelSteps.Checked = nudWildLevelStep.Value != 1;
ParseAndSetCheckbox(cbAllowMoreThanHundredImprinting, @"ASBAllowHyperImprinting ?= ?(true|false)");
// event multipliers breeding
ParseAndSetValue(nudMatingIntervalEvent, @"ASBEvent_MatingIntervalMultiplier ?= ?(\d*\.?\d+)");
ParseAndSetValue(nudEggHatchSpeedEvent, @"ASBEvent_EggHatchSpeedMultiplier ?= ?(\d*\.?\d+)");
ParseAndSetValue(nudBabyMatureSpeedEvent, @"ASBEvent_BabyMatureSpeedMultiplier ?= ?(\d*\.?\d+)");
ParseAndSetValue(nudBabyCuddleIntervalEvent, @"ASBEvent_BabyCuddleIntervalMultiplier ?= ?(\d*\.?\d+)");
ParseAndSetValue(nudBabyFoodConsumptionSpeedEvent, @"ASBEvent_BabyFoodConsumptionSpeedMultiplier ?= ?(\d*\.?\d+)");
// event multipliers taming
ParseAndSetValue(nudTamingSpeedEvent, @"ASBEvent_TamingSpeedMultiplier ?= ?(\d*\.?\d+)");
ParseAndSetValue(nudDinoCharacterFoodDrainEvent, @"ASBEvent_DinoCharacterFoodDrainMultiplier ?= ?(\d*\.?\d+)");
bool ParseAndSetValue(uiControls.Nud nud, string regexPattern)
{
m = Regex.Match(text, regexPattern);
if (m.Success && double.TryParse(m.Groups[1].Value, System.Globalization.NumberStyles.AllowDecimalPoint, cultureForStrings, out d))
{
nud.ValueSave = (decimal)d;
return true;
}
return false;
}
void ParseAndSetCheckbox(CheckBox cb, string regexPattern)
{
m = Regex.Match(text, regexPattern, RegexOptions.IgnoreCase);
if (m.Success)
{
cb.Checked = m.Groups[1].Value.ToLower() == "true";
}
}
}
private void Settings_Disposed(object sender, EventArgs e)
{
_tt.RemoveAll();
_tt.Dispose();
}
private void buttonAllTBMultipliersOne_Click(object sender, EventArgs e)
{
SetBreedingTamingToOne();
}
private void SetBreedingTamingToOne()
{
nudTamingSpeed.ValueSave = 1;
nudDinoCharacterFoodDrain.ValueSave = 1;
nudMatingInterval.ValueSave = 1;
nudEggHatchSpeed.ValueSave = 1;
nudBabyMatureSpeed.ValueSave = 1;
nudBabyImprintingStatScale.ValueSave = 1;
nudBabyCuddleInterval.ValueSave = 1;
nudBabyFoodConsumptionSpeed.ValueSave = 1;
}
private void buttonEventToDefault_Click(object sender, EventArgs e)
{
nudTamingSpeedEvent.ValueSave = nudTamingSpeed.Value;
nudDinoCharacterFoodDrainEvent.ValueSave = nudDinoCharacterFoodDrain.Value;
nudMatingIntervalEvent.ValueSave = nudMatingInterval.Value;
nudEggHatchSpeedEvent.ValueSave = nudEggHatchSpeed.Value;
nudBabyMatureSpeedEvent.ValueSave = nudBabyMatureSpeed.Value;
nudBabyCuddleIntervalEvent.ValueSave = nudBabyCuddleInterval.Value;
nudBabyFoodConsumptionSpeedEvent.ValueSave = nudBabyFoodConsumptionSpeed.Value;
}
private void btAddExportFolder_Click(object sender, EventArgs e)
{
ATImportExportedFolderLocation aTImportExportedFolderLocation = EditFolderLocation(new ATImportExportedFolderLocation());
if (aTImportExportedFolderLocation != null)
{
aTExportFolderLocationsBindingSource.Add(aTImportExportedFolderLocation);
}
}
private void dataGridView_FileLocations_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex == -1 || e.RowIndex >= aTImportFileLocationBindingSource.Count)
{
return;
}
if (e.ColumnIndex == dgvFileLocation_Change.Index)
{
ATImportFileLocation atImportFileLocation = EditFileLocation((ATImportFileLocation)aTImportFileLocationBindingSource[e.RowIndex]);
if (atImportFileLocation != null)
{
aTImportFileLocationBindingSource[e.RowIndex] = atImportFileLocation;
}
}
else if (e.ColumnIndex == dgvFileLocation_Delete.Index)
{
aTImportFileLocationBindingSource.RemoveAt(e.RowIndex);
}
}
private void dataGridViewExportFolders_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex == -1 || e.RowIndex >= aTExportFolderLocationsBindingSource.Count)
{
return;
}
if (e.ColumnIndex == dgvExportFolderChange.Index)
{
ATImportExportedFolderLocation aTImportExportedFolderLocation = EditFolderLocation((ATImportExportedFolderLocation)aTExportFolderLocationsBindingSource[e.RowIndex]);
if (aTImportExportedFolderLocation != null)
{
aTExportFolderLocationsBindingSource[e.RowIndex] = aTImportExportedFolderLocation;
}
}
else if (e.ColumnIndex == dgvExportFolderDelete.Index)
{
aTExportFolderLocationsBindingSource.RemoveAt(e.RowIndex);
}
}
private static ATImportFileLocation EditFileLocation(ATImportFileLocation atImportFileLocation)
{
ATImportFileLocation atifl = null;
using (ATImportFileLocationDialog atImportFileLocationDialog = new ATImportFileLocationDialog(atImportFileLocation))
{
if (atImportFileLocationDialog.ShowDialog() == DialogResult.OK &&
!string.IsNullOrWhiteSpace(atImportFileLocationDialog.AtImportFileLocation.FileLocation))
atifl = atImportFileLocationDialog.AtImportFileLocation;
}
return atifl;
}
private static ATImportExportedFolderLocation EditFolderLocation(ATImportExportedFolderLocation atExportFolderLocation)
{
ATImportExportedFolderLocation atiefl = null;
using (ATImportExportedFolderLocationDialog aTImportExportedFolderLocationDialog = new ATImportExportedFolderLocationDialog(atExportFolderLocation))
{
if (aTImportExportedFolderLocationDialog.ShowDialog() == DialogResult.OK &&
!string.IsNullOrWhiteSpace(aTImportExportedFolderLocationDialog.ATImportExportedFolderLocation.FolderPath))
atiefl = aTImportExportedFolderLocationDialog.ATImportExportedFolderLocation;
}
return atiefl;
}
/// <summary>
/// Displays the server multiplier presets in a combobox
/// </summary>
private void DisplayServerMultiplierPresets()
{
cbbStatMultiplierPresets.Items.Clear();
foreach (var sm in Values.V.serverMultipliersPresets.PresetNameList)
{
if (!string.IsNullOrWhiteSpace(sm) && sm != "singleplayer")
cbbStatMultiplierPresets.Items.Add(sm);
}
if (cbbStatMultiplierPresets.Items.Count > 0)
cbbStatMultiplierPresets.SelectedIndex = 0;
}
private void BtApplyPreset_Click(object sender, EventArgs e)
{
ServerMultipliers multiplierPreset = Values.V.serverMultipliersPresets.GetPreset(cbbStatMultiplierPresets.SelectedItem.ToString());
if (multiplierPreset == null) return;
// first set multipliers to default/official values, then set different values of preset
ApplyMultiplierPreset(Values.V.serverMultipliersPresets.GetPreset(ServerMultipliersPresets.OFFICIAL));
ApplyMultiplierPreset(multiplierPreset);
}
/// <summary>
/// Applies the multipliers of the preset.
/// </summary>
private void ApplyMultiplierPreset(ServerMultipliers sm, bool onlyStatMultipliers = false)
{
if (sm == null) return;
if (!onlyStatMultipliers)
{
nudTamingSpeed.ValueSave = (decimal)sm.TamingSpeedMultiplier;
nudDinoCharacterFoodDrain.ValueSave = (decimal)sm.DinoCharacterFoodDrainMultiplier;
nudEggHatchSpeed.ValueSave = (decimal)sm.EggHatchSpeedMultiplier;
nudBabyMatureSpeed.ValueSave = (decimal)sm.BabyMatureSpeedMultiplier;
nudBabyImprintingStatScale.ValueSave = (decimal)sm.BabyImprintingStatScaleMultiplier;
nudBabyCuddleInterval.ValueSave = (decimal)sm.BabyCuddleIntervalMultiplier;
nudBabyImprintAmount.ValueSave = (decimal)sm.BabyImprintAmountMultiplier;
nudMatingInterval.ValueSave = (decimal)sm.MatingIntervalMultiplier;
nudMatingSpeed.ValueSave = (decimal)sm.MatingSpeedMultiplier;
nudBabyFoodConsumptionSpeed.ValueSave = (decimal)sm.BabyFoodConsumptionSpeedMultiplier;
////numericUpDownDomLevelNr.ValueSave = ;
//numericUpDownMaxBreedingSug.ValueSave = cc.maxBreedingSuggestions;
//numericUpDownMaxWildLevel.ValueSave = cc.maxWildLevel;
//nudMaxServerLevel.ValueSave = cc.maxServerLevel > 0 ? cc.maxServerLevel : 0;
}
if (sm.statMultipliers == null) return;
int loopTo = Math.Min(Values.STATS_COUNT, sm.statMultipliers.Length);
for (int s = 0; s < loopTo; s++)
{
_multSetter[s].Multipliers = sm.statMultipliers[s];
}
}
private void Settings_FormClosing(object sender, FormClosingEventArgs e)
{
LastTabPageIndex = (SettingsTabPages)tabControlSettings.SelectedIndex;
}
private void cbMoveImportedFileToSubFolder_CheckedChanged(object sender, EventArgs e)
{
if (cbMoveImportedFileToSubFolder.Checked)
cbDeleteAutoImportedFile.Checked = false;
}
private void cbDeleteAutoImportedFile_CheckedChanged(object sender, EventArgs e)
{
if (cbDeleteAutoImportedFile.Checked)
cbMoveImportedFileToSubFolder.Checked = false;
}
private void btExportMultipliers_Click(object sender, EventArgs e)
{
using (SaveFileDialog dlg = new SaveFileDialog
{
Filter = "ARK Multiplier File (*.ini)|*.ini",
InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop),
FileName = "ASBMultipliers"
})
{
if (dlg.ShowDialog() == DialogResult.OK)
{
SaveMultiplierSettingsToFile(dlg.FileName);
}
}
}
/// <summary>
/// Saves the multipliers for the stats, taming and breeding to an ini-file.
/// </summary>
/// <param name="fileName"></param>
private void SaveMultiplierSettingsToFile(string fileName)
{
var sb = new System.Text.StringBuilder();
var cultureForStrings = System.Globalization.CultureInfo.GetCultureInfo("en-US");
// stat multipliers
for (int s = 0; s < Values.STATS_COUNT; s++)
{
sb.AppendLine($"PerLevelStatsMultiplier_DinoTamed_Add[{s}] = {_multSetter[s].Multipliers[0].ToString(cultureForStrings)}");
sb.AppendLine($"PerLevelStatsMultiplier_DinoTamed_Affinity[{s}] = {_multSetter[s].Multipliers[1].ToString(cultureForStrings)}");
sb.AppendLine($"PerLevelStatsMultiplier_DinoTamed[{s}] = {_multSetter[s].Multipliers[2].ToString(cultureForStrings)}");
sb.AppendLine($"PerLevelStatsMultiplier_DinoWild[{s}] = {_multSetter[s].Multipliers[3].ToString(cultureForStrings)}");
}
// breeding multipliers
sb.AppendLine($"MatingIntervalMultiplier = {nudMatingInterval.Value.ToString(cultureForStrings)}");
sb.AppendLine($"EggHatchSpeedMultiplier = {nudEggHatchSpeed.Value.ToString(cultureForStrings)}");
sb.AppendLine($"MatingSpeedMultiplier = {nudMatingSpeed.Value.ToString(cultureForStrings)}");
sb.AppendLine($"BabyMatureSpeedMultiplier = {nudBabyMatureSpeed.Value.ToString(cultureForStrings)}");
sb.AppendLine($"BabyImprintingStatScaleMultiplier = {nudBabyImprintingStatScale.Value.ToString(cultureForStrings)}");
sb.AppendLine($"BabyCuddleIntervalMultiplier = {nudBabyCuddleInterval.Value.ToString(cultureForStrings)}");
sb.AppendLine($"BabyFoodConsumptionSpeedMultiplier = {nudBabyFoodConsumptionSpeed.Value.ToString(cultureForStrings)}");
sb.AppendLine($"bUseSingleplayerSettings = {(cbSingleplayerSettings.Checked ? "true" : "false")}");
sb.AppendLine($"DestroyTamesOverLevelClamp = {nudMaxServerLevel.Value.ToString(cultureForStrings)}");
// taming multipliers
sb.AppendLine($"TamingSpeedMultiplier = {nudTamingSpeed.Value.ToString(cultureForStrings)}");
sb.AppendLine($"DinoCharacterFoodDrainMultiplier = {nudDinoCharacterFoodDrain.Value.ToString(cultureForStrings)}");
//// the settings below are not settings that appear in ARK server config files and are used only in ASB
// max levels
sb.AppendLine($"ASBMaxWildLevels_Dinos = {nudMaxWildLevels.Value.ToString(cultureForStrings)}");
sb.AppendLine($"ASBMaxDomLevels_Dinos = {nudMaxDomLevels.Value.ToString(cultureForStrings)}");
sb.AppendLine($"ASBMaxGraphLevels = {nudMaxGraphLevel.Value.ToString(cultureForStrings)}");
// extractor
sb.AppendLine($"ASBExtractorWildLevelSteps = {(cbConsiderWildLevelSteps.Checked ? nudWildLevelStep.Value.ToString(cultureForStrings) : "1")}");
sb.AppendLine($"ASBAllowHyperImprinting = {(cbAllowMoreThanHundredImprinting.Checked ? "true" : "false")}");
// event multipliers
sb.AppendLine($"ASBEvent_MatingIntervalMultiplier = {nudMatingIntervalEvent.Value.ToString(cultureForStrings)}");
sb.AppendLine($"ASBEvent_EggHatchSpeedMultiplier = {nudEggHatchSpeedEvent.Value.ToString(cultureForStrings)}");
sb.AppendLine($"ASBEvent_BabyMatureSpeedMultiplier = {nudBabyMatureSpeedEvent.Value.ToString(cultureForStrings)}");
sb.AppendLine($"ASBEvent_BabyCuddleIntervalMultiplier = {nudBabyCuddleIntervalEvent.Value.ToString(cultureForStrings)}");
sb.AppendLine($"ASBEvent_BabyFoodConsumptionSpeedMultiplier = {nudBabyFoodConsumptionSpeedEvent.Value.ToString(cultureForStrings)}");
sb.AppendLine($"ASBEvent_TamingSpeedMultiplier = {nudTamingSpeedEvent.Value.ToString(cultureForStrings)}");
sb.AppendLine($"ASBEvent_DinoCharacterFoodDrainMultiplier = {nudDinoCharacterFoodDrainEvent.Value.ToString(cultureForStrings)}");
try
{
File.WriteAllText(fileName, sb.ToString());
}
catch (Exception ex)
{
MessageBoxes.ExceptionMessageBox(ex, "Error while writing settings file:", "File writing error");
}
}
public enum SettingsTabPages
{
Unknown = -1,
Multipliers = 0,
General = 1,
SaveImport = 2,
ExportedImport = 3,
Ocr = 4,
}
private void cbCustomOverlayLocation_CheckedChanged(object sender, EventArgs e)
{
pCustomOverlayLocation.Enabled = cbCustomOverlayLocation.Checked;
}
private void button1_Click(object sender, EventArgs e)
{
tbOCRCaptureApp.Text = DefaultOcrProcessName;
}
private void Localization()
{
Loc.ControlText(buttonOK, "OK");
Loc.ControlText(buttonCancel, "Cancel");
Loc.ControlText(BtBeepFailure, _tt);
Loc.ControlText(BtBeepSuccess, _tt);
Loc.ControlText(BtBeepTop, _tt);
Loc.ControlText(BtBeepNewTop, _tt);
Loc.ControlText(BtGetExportFolderAutomatically);
}
private void cbSingleplayerSettings_CheckedChanged(object sender, EventArgs e)
{
if (cbSingleplayerSettings.Checked)
{
if (nudMaxDomLevels.Value != CreatureCollection.MaxDomLevelSinglePlayerDefault)
LbDefaultLevelups.Text = $"default: {CreatureCollection.MaxDomLevelSinglePlayerDefault}";
else LbDefaultLevelups.Text = string.Empty;
}
else
{
if (nudMaxDomLevels.Value != CreatureCollection.MaxDomLevelDefault)
LbDefaultLevelups.Text = $"default: {CreatureCollection.MaxDomLevelDefault}";
else LbDefaultLevelups.Text = string.Empty;
}
}
private void BtBeepFailure_Click(object sender, EventArgs e)
{
SoundFeedback.BeepSignal(SoundFeedback.FeedbackSounds.Failure);
}
private void BtBeepSuccess_Click(object sender, EventArgs e)
{
SoundFeedback.BeepSignal(SoundFeedback.FeedbackSounds.Success);
}
private void BtBeepTop_Click(object sender, EventArgs e)
{
SoundFeedback.BeepSignal(SoundFeedback.FeedbackSounds.Good);
}
private void BtBeepNewTop_Click(object sender, EventArgs e)
{
SoundFeedback.BeepSignal(SoundFeedback.FeedbackSounds.Great);
}
private void BtImportArchiveFolder_Click(object sender, EventArgs e)
{
using (var dlg = new FolderBrowserDialog())
{
// get folder of first export path
var exportFolder = BtImportArchiveFolder.Tag is string lastFolder && !string.IsNullOrEmpty(lastFolder) ? lastFolder
: aTExportFolderLocationsBindingSource.OfType<ATImportExportedFolderLocation>()
.Where(location => !string.IsNullOrWhiteSpace(location.FolderPath))
.Select(location => location.FolderPath).FirstOrDefault();
dlg.RootFolder = Environment.SpecialFolder.Desktop;
if (exportFolder != null && Directory.Exists(exportFolder))
dlg.SelectedPath = exportFolder;
if (dlg.ShowDialog() == DialogResult.OK)
{
SetImportExportArchiveFolder(dlg.SelectedPath);
}
}
}
private void SetImportExportArchiveFolder(string folderPath)
{
BtImportArchiveFolder.Text = string.IsNullOrEmpty(folderPath) ? "…" : Path.GetFileName(folderPath);
BtImportArchiveFolder.Tag = folderPath;
_tt.SetToolTip(BtImportArchiveFolder, folderPath);
}
private void BtGetExportFolderAutomatically_Click(object sender, EventArgs e)
{
if (ExportFolderLocation.GetListOfExportFolders(out (string path, string steamPlayerName)[] arkInstallFolders, out string error))
{
int i = 0;
foreach (var p in arkInstallFolders)
aTExportFolderLocationsBindingSource.Insert(i++, ATImportExportedFolderLocation.CreateFromString(
$"default ({p.steamPlayerName})||{p.path}"));
}
else
{
MessageBox.Show(
Loc.S("ExportFolderDetectionFailed") + (string.IsNullOrEmpty(error) ? string.Empty : "\n\n" + error),
"Folder detection failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
| 55.852036 | 412 | 0.669808 | [
"MIT"
] | Leyrix/ARKStatsExtractor | ARKBreedingStats/settings/Settings.cs | 56,253 | C# |
using System;
using System.Collections.Generic;
using Host4Travel.Core.DTO.PostRatingDtos;
using Host4Travel.UI;
namespace Host4Travel.BLL.Abstract
{
public interface IPostRatingService
{
List<PostRatingListDto> GetAllRatings();
PostRatingDetailDto GetById(Guid ratingId);
List<PostRatingListDto> GetUsersRatings(string id);
List<PostRatingListDto> GetMyPostRatings(string userId);
void AddRating(PostRatingAddDto dto);
void UpdateRating(PostRatingUpdateDto dto);
void DeleteRating(PostRatingDeleteDto dto);
}
} | 29.15 | 64 | 0.740995 | [
"MIT"
] | SadettinKepenek/Host4Travel | Host4Travel.BLL/Abstract/IPostRatingService.cs | 585 | C# |
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using RDG.Chop_Chop.Scripts.Animation;
using UnityEngine;
namespace RDG.Chop_Chop.Scripts.Combat {
[Serializable]
public class CombatAttackConfig {
public string attackAnimName = "Attack";
public float attackSpeed = 1.2f;
public float attackDelayFactor = 0.5f;
}
public enum CombatAttackerState {
Idle, Locked, AttackPre, AttackPost
}
public class CombatAttackerAnimTrigger : AnimationTrigger {
private readonly float attackAnimSpeed;
private readonly CombatAttackConfig config;
private readonly Animator anim;
private readonly MonoBehaviour parent;
private float priorSpeed;
private bool triggered;
public CombatAttackerAnimTrigger(float attackAnimSpeed, CombatAttackConfig config, Animator anim, MonoBehaviour parent) {
this.attackAnimSpeed = attackAnimSpeed;
this.config = config;
this.anim = anim;
this.parent = parent;
}
public Task Trigger() {
triggered = true;
var source = new TaskCompletionSource<bool>();
parent.StartCoroutine(WaitForAttack(source));
return source.Task;
}
private IEnumerator<YieldInstruction> WaitForAttack(TaskCompletionSource<bool> source) {
yield return new WaitForSeconds(config.attackSpeed);
triggered = false;
source.SetResult(true);
}
public string AnimName => config.attackAnimName;
public bool Eval() {
if (!triggered) {
return false;
}
triggered = false;
priorSpeed = anim.speed;
anim.speed = attackAnimSpeed / config.attackSpeed;
return true;
}
public void OnExit() {
anim.speed = priorSpeed;
}
}
public class CombatAttacker {
public event Action OnAttackDone;
public CombatAttackerState State { get; private set; }
public CombatAttackerAnimTrigger AnimTrigger { get; }
public CombatAttacker(CombatAttackConfig attackConfig, Animator anim, MonoBehaviour parent) {
if (attackConfig.attackDelayFactor >= 1.0f || attackConfig.attackDelayFactor <= 0) {
throw new Exception($"attack delay factor invalid {attackConfig.attackDelayFactor}");
}
State = CombatAttackerState.Idle;
var attackAnimSpeed = -1.0f;
foreach (var clip in anim.runtimeAnimatorController.animationClips) {
if (clip.name != attackConfig.attackAnimName) {
continue;
}
attackAnimSpeed = clip.length;
break;
}
if (attackAnimSpeed < 0.0f) {
throw new Exception($"Attack Animation {attackConfig.attackAnimName} not found");
}
AnimTrigger = new CombatAttackerAnimTrigger(attackAnimSpeed, attackConfig, anim, parent);
}
public Task Attack() {
if (State != CombatAttackerState.Idle) {
return Task.CompletedTask;
}
State = CombatAttackerState.AttackPre;
return AnimTrigger.Trigger().ContinueWith(_ => {
OnAttackDone?.Invoke();
State = CombatAttackerState.Idle;
});
}
public void Release() {
OnAttackDone = null;
}
}
}
| 29.736364 | 126 | 0.653623 | [
"Apache-2.0"
] | RunDotGames/chop-chop | chop-chop-client/Assets/RDG/Chop Chop/Scripts/Combat/CombatAttacker.cs | 3,273 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Devices.Geolocation;
namespace AmadeusW.KindleNav.Device
{
public static class Location
{
static Geolocator _geolocator = null;
public static async Task<bool> Start()
{
// Request permission to access location
var accessStatus = await Geolocator.RequestAccessAsync();
switch (accessStatus)
{
case GeolocationAccessStatus.Allowed:
// You should set MovementThreshold for distance-based tracking
// or ReportInterval for periodic-based tracking before adding event
// handlers. If none is set, a ReportInterval of 1 second is used
// as a default and a position will be returned every 1 second.
//
// Value of 2000 milliseconds (2 seconds)
// isn't a requirement, it is just an example.
_geolocator = new Geolocator { ReportInterval = 2000 };
// Subscribe to PositionChanged event to get updated tracking positions
_geolocator.PositionChanged += OnPositionChanged;
// Subscribe to StatusChanged event to get updates of location status changes
_geolocator.StatusChanged += OnStatusChanged;
await Logger.Log("Starting geolocation...");
return true;
case GeolocationAccessStatus.Denied:
await Logger.Log("Access to geolocation is denied.");
return false;
case GeolocationAccessStatus.Unspecified:
await Logger.Log("Unspecificed error with geolocation!");
return false;
}
return false;
}
public static async Task Stop()
{
_geolocator.PositionChanged -= OnPositionChanged;
_geolocator.StatusChanged -= OnStatusChanged;
_geolocator = null;
}
/// <summary>
/// Event handler for PositionChanged events. It is raised when
/// a location is available for the tracking session specified.
/// </summary>
/// <param name="sender">Geolocator instance</param>
/// <param name="e">Position data</param>
static async private void OnPositionChanged(Geolocator sender, PositionChangedEventArgs e)
{
await Logger.Log($"{e.Position.Coordinate.Latitude}, {e.Position.Coordinate.Longitude}");
}
/// <summary>
/// Event handler for StatusChanged events. It is raised when the
/// location status in the system changes.
/// </summary>
/// <param name="sender">Geolocator instance</param>
/// <param name="e">Statu data</param>
static async private void OnStatusChanged(Geolocator sender, StatusChangedEventArgs e)
{
await Logger.Log($"{e.Status}");
}
// See if we need the background task, or is basic implementation ok
/*
private const string BackgroundTaskName = "SampleLocationBackgroundTask";
private const string BackgroundTaskEntryPoint = "BackgroundTask.LocationBackgroundTask";
private IBackgroundTaskRegistration _geolocTask = null;
public static bool Register()
{
try
{
// Get permission for a background task from the user. If the user has already answered once,
// this does nothing and the user must manually update their preference via PC Settings.
BackgroundAccessStatus backgroundAccessStatus = await BackgroundExecutionManager.RequestAccessAsync();
// Regardless of the answer, register the background task. If the user later adds this application
// to the lock screen, the background task will be ready to run.
// Create a new background task builder
BackgroundTaskBuilder geolocTaskBuilder = new BackgroundTaskBuilder();
geolocTaskBuilder.Name = BackgroundTaskName;
geolocTaskBuilder.TaskEntryPoint = BackgroundTaskEntryPoint;
// Create a new timer triggering at a 15 minute interval
var trigger = new TimeTrigger(15, false);
// Associate the timer trigger with the background task builder
geolocTaskBuilder.SetTrigger(trigger);
// Register the background task
_geolocTask = geolocTaskBuilder.Register();
// Associate an event handler with the new background task
_geolocTask.Completed += OnCompleted;
UpdateButtonStates(/*registered*//* true);
switch (backgroundAccessStatus)
{
case BackgroundAccessStatus.Unspecified:
case BackgroundAccessStatus.Denied:
_rootPage.NotifyUser("Not able to run in background. Application must be added to the lock screen.",
NotifyType.ErrorMessage);
break;
default:
// BckgroundTask is allowed
_rootPage.NotifyUser("Background task registered.", NotifyType.StatusMessage);
// Need to request access to location
// This must be done with the background task registeration
// because the background task cannot display UI.
RequestLocationAccess();
break;
}
}
catch (Exception ex)
{
_rootPage.NotifyUser(ex.ToString(), NotifyType.ErrorMessage);
UpdateButtonStates(/*registered:*//* false);
}
}
public static bool Deregister()
{
// Unregister the background task
if (null != _geolocTask)
{
_geolocTask.Unregister(true);
_geolocTask = null;
}
ScenarioOutput_Latitude.Text = "No data";
ScenarioOutput_Longitude.Text = "No data";
ScenarioOutput_Accuracy.Text = "No data";
UpdateButtonStates(/*registered:*//* false);
_rootPage.NotifyUser("Background task unregistered", NotifyType.StatusMessage);
}
/// <summary>
/// Get permission for location from the user. If the user has already answered once,
/// this does nothing and the user must manually update their preference via Settings.
/// </summary>
private async void RequestLocationAccess()
{
// Request permission to access location
var accessStatus = await Geolocator.RequestAccessAsync();
switch (accessStatus)
{
case GeolocationAccessStatus.Allowed:
break;
case GeolocationAccessStatus.Denied:
_rootPage.NotifyUser("Access to location is denied.", NotifyType.ErrorMessage);
break;
case GeolocationAccessStatus.Unspecified:
_rootPage.NotifyUser("Unspecificed error!", NotifyType.ErrorMessage);
break;
}
}
/// <summary>
/// Event handle to be raised when the background task is completed
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private async void OnCompleted(IBackgroundTaskRegistration sender, BackgroundTaskCompletedEventArgs e)
{
if (sender != null)
{
// Update the UI with progress reported by the background task
await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
try
{
// If the background task threw an exception, display the exception in
// the error text box.
e.CheckResult();
// Update the UI with the completion status of the background task
// The Run method of the background task sets this status.
var settings = ApplicationData.Current.LocalSettings;
if (settings.Values["Status"] != null)
{
_rootPage.NotifyUser(settings.Values["Status"].ToString(), NotifyType.StatusMessage);
}
// Extract and display location data set by the background task if not null
ScenarioOutput_Latitude.Text = (settings.Values["Latitude"] == null) ? "No data" : settings.Values["Latitude"].ToString();
ScenarioOutput_Longitude.Text = (settings.Values["Longitude"] == null) ? "No data" : settings.Values["Longitude"].ToString();
ScenarioOutput_Accuracy.Text = (settings.Values["Accuracy"] == null) ? "No data" : settings.Values["Accuracy"].ToString();
}
catch (Exception ex)
{
// The background task had an error
_rootPage.NotifyUser(ex.ToString(), NotifyType.ErrorMessage);
}
});
}
}
*/
}
}
| 43.151786 | 149 | 0.561453 | [
"MIT"
] | AmadeusW/kindlenav | src/AmadeusW.KindleNav/Device/Location.cs | 9,668 | C# |
// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using ICSharpCode.NRefactory;
using ICSharpCode.RubyBinding;
using NUnit.Framework;
namespace RubyBinding.Tests.Converter
{
/// <summary>
/// Tests the CSharpToRubyConverter class.
/// </summary>
[TestFixture]
public class EmptyCSharpClassConversionTestFixture
{
string csharp = "class Foo\r\n" +
"{\r\n" +
"}";
[Test]
public void ConvertedRubyCode()
{
NRefactoryToRubyConverter converter = new NRefactoryToRubyConverter(SupportedLanguage.CSharp);
string Ruby = converter.Convert(csharp);
string expectedRuby = "class Foo\r\n" +
"end";
Assert.AreEqual(expectedRuby, Ruby);
}
}
}
| 37.291667 | 97 | 0.745251 | [
"MIT"
] | galich/SharpDevelop | src/AddIns/BackendBindings/Ruby/RubyBinding/Test/Converter/EmptyCSharpClassConversionTestFixture.cs | 1,792 | C# |
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
namespace Test.MissionTest
{
public class MissionMonolithSetupSystemTest : ContextsTest
{
[SetUp]
public void Init()
{
_systems.Add(new MissionBossMonolithSetupSystem(_contexts));
_contexts.game.SetMainMission(MainMission.BossMonolith);
var sp = _contexts.tile.CreateEntity();
sp.AddMapPosition(1, 1);
sp.AddSpawnpoint(-1);
_contexts.game.SetPlayingOrder(new List<GameEntity>());
}
[Test]
public void Execute_MissionEntityMonolithAdded_BossPlayerEntityCreated()
{
_systems.Execute();
Assert.IsTrue(_contexts.game.isBossPlayer);
var e = _contexts.unit.bossUnitEntity;
Assert.IsTrue(e.owner.Entity.hasPlayer);
}
[Test]
public void Execute_MissionEntityMonolithAdded_BossUnitEntityCreated()
{
_systems.Execute();
Assert.IsTrue(_contexts.unit.hasBossUnit);
var e = _contexts.unit.bossUnitEntity;
Assert.AreEqual(Boss.Monolith, e.bossUnit.Type);
Assert.AreEqual(1, e.mapPosition.x);
Assert.AreEqual(1, e.mapPosition.y);
}
[Test]
public void Execute_MissionEntityMonolithAdded_BossPlayerAddToLastOfPlayingOrder()
{
_systems.Execute();
var e = _contexts.unit.bossUnitEntity;
var order = _contexts.game.playingOrder.PlayerOrder;
Assert.IsTrue(order.Contains(e.owner.Entity));
Assert.AreEqual(e.owner.Entity, order.Last());
}
}
}
| 25.089286 | 84 | 0.747331 | [
"MIT"
] | Arpple/projectend | Assets/Scripts/Test/Editor/Mission/Main/MainMissionMonolithSetupSystemTest.cs | 1,407 | C# |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
using System.Collections.Generic;
using Aliyun.Acs.Core;
using Aliyun.Acs.Core.Http;
using Aliyun.Acs.Core.Transform;
using Aliyun.Acs.Core.Utils;
using Aliyun.Acs.ROS;
using Aliyun.Acs.ROS.Transform;
using Aliyun.Acs.ROS.Transform.V20150901;
namespace Aliyun.Acs.ROS.Model.V20150901
{
public class CreateStacksRequest : RoaAcsRequest<CreateStacksResponse>
{
public CreateStacksRequest()
: base("ROS", "2015-09-01", "CreateStacks")
{
if (this.GetType().GetProperty("ProductEndpointMap") != null && this.GetType().GetProperty("ProductEndpointType") != null)
{
this.GetType().GetProperty("ProductEndpointMap").SetValue(this, Endpoint.endpointMap, null);
this.GetType().GetProperty("ProductEndpointType").SetValue(this, Endpoint.endpointRegionalType, null);
}
UriPattern = "/stacks";
Method = MethodType.POST;
}
public override CreateStacksResponse GetResponse(UnmarshallerContext unmarshallerContext)
{
return CreateStacksResponseUnmarshaller.Unmarshall(unmarshallerContext);
}
}
}
| 38.294118 | 134 | 0.712238 | [
"Apache-2.0"
] | slipjimmy/aliyun-openapi-net-sdk | aliyun-net-sdk-ros/ROS/Model/V20150901/CreateStacksRequest.cs | 1,953 | C# |
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information.
// Ported from um/MsHTML.h in the Windows SDK for Windows 10.0.20348.0
// Original source is Copyright © Microsoft. All rights reserved.
using NUnit.Framework;
using System;
using System.Runtime.InteropServices;
using static TerraFX.Interop.Windows;
namespace TerraFX.Interop.UnitTests
{
/// <summary>Provides validation of the <see cref="ISVGGradientElement" /> struct.</summary>
public static unsafe partial class ISVGGradientElementTests
{
/// <summary>Validates that the <see cref="Guid" /> of the <see cref="ISVGGradientElement" /> struct is correct.</summary>
[Test]
public static void GuidOfTest()
{
Assert.That(typeof(ISVGGradientElement).GUID, Is.EqualTo(IID_ISVGGradientElement));
}
/// <summary>Validates that the <see cref="ISVGGradientElement" /> struct is blittable.</summary>
[Test]
public static void IsBlittableTest()
{
Assert.That(Marshal.SizeOf<ISVGGradientElement>(), Is.EqualTo(sizeof(ISVGGradientElement)));
}
/// <summary>Validates that the <see cref="ISVGGradientElement" /> struct has the right <see cref="LayoutKind" />.</summary>
[Test]
public static void IsLayoutSequentialTest()
{
Assert.That(typeof(ISVGGradientElement).IsLayoutSequential, Is.True);
}
/// <summary>Validates that the <see cref="ISVGGradientElement" /> struct has the correct size.</summary>
[Test]
public static void SizeOfTest()
{
if (Environment.Is64BitProcess)
{
Assert.That(sizeof(ISVGGradientElement), Is.EqualTo(8));
}
else
{
Assert.That(sizeof(ISVGGradientElement), Is.EqualTo(4));
}
}
}
}
| 37.730769 | 145 | 0.643221 | [
"MIT"
] | DaZombieKiller/terrafx.interop.windows | tests/Interop/Windows/um/MsHTML/ISVGGradientElementTests.cs | 1,964 | C# |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Text;
using Bicep.Core;
using Bicep.Core.UnitTests.Assertions;
using Bicep.Core.UnitTests.Utils;
using Bicep.LanguageServer.Handlers;
using FluentAssertions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using OmniSharp.Extensions.JsonRpc;
using OmniSharp.Extensions.LanguageServer.Protocol;
namespace Bicep.LangServer.UnitTests.Handlers
{
[TestClass]
public class BicepDisableLinterRuleCommandHandlerTests
{
[NotNull]
public TestContext? TestContext { get; set; }
private static readonly MockRepository Repository = new(MockBehavior.Strict);
private static readonly ISerializer Serializer = Repository.Create<ISerializer>().Object;
private BicepDisableLinterRuleCommandHandler BicepDisableLinterRuleHandler = new(Serializer);
[TestMethod]
public void DisableLinterRule_WithInvalidBicepConfig_ShouldThrow()
{
string bicepConfig = @"{
""analyzers"": {
""core"": {
""verbose"": false,
""enabled"": true,
""rules"": {
""no-unused-params"": {
""level"": ""warning""
}";
Action disableLinterRule = () => BicepDisableLinterRuleHandler.DisableLinterRule(bicepConfig, "no-unused-params");
disableLinterRule.Should().Throw<Exception>().WithMessage("File bicepconfig.json already exists and is invalid. If overwriting the file is intended, delete it manually and retry disable linter rule lightBulb option again");
}
[TestMethod]
public void DisableLinterRule_WithRuleEnabledInBicepConfig_ShouldTurnOffRule()
{
string bicepConfigFileContents = @"{
""analyzers"": {
""core"": {
""verbose"": false,
""enabled"": true,
""rules"": {
""no-unused-params"": {
""level"": ""warning""
}
}
}
}
}";
string actual = BicepDisableLinterRuleHandler.DisableLinterRule(bicepConfigFileContents, "no-unused-params");
actual.Should().BeEquivalentToIgnoringNewlines(@"{
""analyzers"": {
""core"": {
""verbose"": false,
""enabled"": true,
""rules"": {
""no-unused-params"": {
""level"": ""off""
}
}
}
}
}");
}
[TestMethod]
public void DisableLinterRule_WithRuleDisabledInBicepConfig_DoesNothing()
{
string bicepConfigFileContents = @"{
""analyzers"": {
""core"": {
""verbose"": false,
""enabled"": true,
""rules"": {
""no-unused-params"": {
""level"": ""off""
}
}
}
}
}";
string actual = BicepDisableLinterRuleHandler.DisableLinterRule(bicepConfigFileContents, "no-unused-params");
actual.Should().BeEquivalentToIgnoringNewlines(@"{
""analyzers"": {
""core"": {
""verbose"": false,
""enabled"": true,
""rules"": {
""no-unused-params"": {
""level"": ""off""
}
}
}
}
}");
}
[TestMethod]
public void DisableLinterRule_WithNoRuleInBicepConfig_ShouldAddAnEntryInBicepConfig()
{
string bicepConfigFileContents = @"{
""analyzers"": {
""core"": {
""verbose"": false,
""enabled"": true,
""rules"": {
}
}
}
}";
string actual = BicepDisableLinterRuleHandler.DisableLinterRule(bicepConfigFileContents, "no-unused-params");
actual.Should().BeEquivalentToIgnoringNewlines(@"{
""analyzers"": {
""core"": {
""verbose"": false,
""enabled"": true,
""rules"": {
""no-unused-params"": {
""level"": ""off""
}
}
}
}
}");
}
[TestMethod]
public void DisableLinterRule_WithNoLevelPropertyInRule_ShouldAddAnEntryInBicepConfigAndTurnOffRule()
{
string bicepConfigFileContents = @"{
""analyzers"": {
""core"": {
""verbose"": false,
""enabled"": true,
""rules"": {
""no-unused-params"": {
}
}
}
}
}";
string actual = BicepDisableLinterRuleHandler.DisableLinterRule(bicepConfigFileContents, "no-unused-params");
actual.Should().BeEquivalentToIgnoringNewlines(@"{
""analyzers"": {
""core"": {
""verbose"": false,
""enabled"": true,
""rules"": {
""no-unused-params"": {
""level"": ""off""
}
}
}
}
}");
}
[TestMethod]
public void DisableLinterRule_WithNoRulesNode_ShouldAddAnEntryInBicepConfigAndTurnOffRule()
{
string bicepConfigFileContents = @"{
""analyzers"": {
""core"": {
""verbose"": false,
""enabled"": true
}
}
}";
string actual = BicepDisableLinterRuleHandler.DisableLinterRule(bicepConfigFileContents, "no-unused-params");
actual.Should().BeEquivalentToIgnoringNewlines(@"{
""analyzers"": {
""core"": {
""verbose"": false,
""enabled"": true,
""rules"": {
""no-unused-params"": {
""level"": ""off""
}
}
}
}
}");
}
[TestMethod]
public void DisableLinterRule_WithOnlyCurlyBraces_ShouldUseDefaultConfigAndTurnOffRule()
{
string actual = BicepDisableLinterRuleHandler.DisableLinterRule("{}", "no-unused-params");
actual.Should().BeEquivalentToIgnoringNewlines(@"{
""cloud"": {
""currentProfile"": ""AzureCloud"",
""profiles"": {
""AzureCloud"": {
""resourceManagerEndpoint"": ""https://management.azure.com""
},
""AzureChinaCloud"": {
""resourceManagerEndpoint"": ""https://management.chinacloudapi.cn""
},
""AzureUSGovernment"": {
""resourceManagerEndpoint"": ""https://management.usgovcloudapi.net""
}
},
""credentialPrecedence"": [
""AzureCLI"",
""AzurePowerShell""
]
},
""moduleAliases"": {
""ts"": {},
""br"": {}
},
""analyzers"": {
""core"": {
""verbose"": false,
""enabled"": true,
""rules"": {
""no-hardcoded-env-urls"": {
""level"": ""warning"",
""disallowedhosts"": [
""gallery.azure.com"",
""management.core.windows.net"",
""management.azure.com"",
""database.windows.net"",
""core.windows.net"",
""login.microsoftonline.com"",
""graph.windows.net"",
""trafficmanager.net"",
""datalake.azure.net"",
""azuredatalakestore.net"",
""azuredatalakeanalytics.net"",
""vault.azure.net"",
""api.loganalytics.io"",
""asazure.windows.net"",
""region.asazure.windows.net"",
""batch.core.windows.net""
],
""excludedhosts"": [
""schema.management.azure.com""
]
},
""no-unused-params"": {
""level"": ""off""
}
}
}
}
}");
}
[TestMethod]
public void GetBicepConfigFilePathAndContents_WithInvalidBicepConfigFilePath_ShouldCreateBicepConfigFileUsingDefaultSettings()
{
var bicepPath = FileHelper.SaveResultFile(TestContext, "main.bicep", @"param storageAccountName string = 'test'");
DocumentUri documentUri = DocumentUri.FromFileSystemPath(bicepPath);
(string actualBicepConfigFilePath, string actualBicepConfigContents) = BicepDisableLinterRuleHandler.GetBicepConfigFilePathAndContents(documentUri, "no-unused-params", string.Empty);
var directoryContainingSourceFile = Path.GetDirectoryName(documentUri.GetFileSystemPath());
string expectedBicepConfigFilePath = Path.Combine(directoryContainingSourceFile!, LanguageConstants.BicepConfigurationFileName);
actualBicepConfigFilePath.Should().Be(expectedBicepConfigFilePath);
actualBicepConfigContents.Should().BeEquivalentToIgnoringNewlines(@"{
""cloud"": {
""currentProfile"": ""AzureCloud"",
""profiles"": {
""AzureCloud"": {
""resourceManagerEndpoint"": ""https://management.azure.com""
},
""AzureChinaCloud"": {
""resourceManagerEndpoint"": ""https://management.chinacloudapi.cn""
},
""AzureUSGovernment"": {
""resourceManagerEndpoint"": ""https://management.usgovcloudapi.net""
}
},
""credentialPrecedence"": [
""AzureCLI"",
""AzurePowerShell""
]
},
""moduleAliases"": {
""ts"": {},
""br"": {}
},
""analyzers"": {
""core"": {
""verbose"": false,
""enabled"": true,
""rules"": {
""no-hardcoded-env-urls"": {
""level"": ""warning"",
""disallowedhosts"": [
""gallery.azure.com"",
""management.core.windows.net"",
""management.azure.com"",
""database.windows.net"",
""core.windows.net"",
""login.microsoftonline.com"",
""graph.windows.net"",
""trafficmanager.net"",
""datalake.azure.net"",
""azuredatalakestore.net"",
""azuredatalakeanalytics.net"",
""vault.azure.net"",
""api.loganalytics.io"",
""asazure.windows.net"",
""region.asazure.windows.net"",
""batch.core.windows.net""
],
""excludedhosts"": [
""schema.management.azure.com""
]
},
""no-unused-params"": {
""level"": ""off""
}
}
}
}
}");
}
[TestMethod]
public void GetBicepConfigFilePathAndContents_WithNonExistentBicepConfigFile_ShouldCreateBicepConfigFileUsingDefaultSettings()
{
var bicepPath = FileHelper.SaveResultFile(TestContext, "main.bicep", @"param storageAccountName string = 'test'");
DocumentUri documentUri = DocumentUri.FromFileSystemPath(bicepPath);
(string actualBicepConfigFilePath, string actualBicepConfigContents) = BicepDisableLinterRuleHandler.GetBicepConfigFilePathAndContents(documentUri, "no-unused-params", @"\nonExistent\bicepconfig.json");
var directoryContainingSourceFile = Path.GetDirectoryName(documentUri.GetFileSystemPath());
string expectedBicepConfigFilePath = Path.Combine(directoryContainingSourceFile!, LanguageConstants.BicepConfigurationFileName);
actualBicepConfigFilePath.Should().Be(expectedBicepConfigFilePath);
actualBicepConfigContents.Should().BeEquivalentToIgnoringNewlines(@"{
""cloud"": {
""currentProfile"": ""AzureCloud"",
""profiles"": {
""AzureCloud"": {
""resourceManagerEndpoint"": ""https://management.azure.com""
},
""AzureChinaCloud"": {
""resourceManagerEndpoint"": ""https://management.chinacloudapi.cn""
},
""AzureUSGovernment"": {
""resourceManagerEndpoint"": ""https://management.usgovcloudapi.net""
}
},
""credentialPrecedence"": [
""AzureCLI"",
""AzurePowerShell""
]
},
""moduleAliases"": {
""ts"": {},
""br"": {}
},
""analyzers"": {
""core"": {
""verbose"": false,
""enabled"": true,
""rules"": {
""no-hardcoded-env-urls"": {
""level"": ""warning"",
""disallowedhosts"": [
""gallery.azure.com"",
""management.core.windows.net"",
""management.azure.com"",
""database.windows.net"",
""core.windows.net"",
""login.microsoftonline.com"",
""graph.windows.net"",
""trafficmanager.net"",
""datalake.azure.net"",
""azuredatalakestore.net"",
""azuredatalakeanalytics.net"",
""vault.azure.net"",
""api.loganalytics.io"",
""asazure.windows.net"",
""region.asazure.windows.net"",
""batch.core.windows.net""
],
""excludedhosts"": [
""schema.management.azure.com""
]
},
""no-unused-params"": {
""level"": ""off""
}
}
}
}
}");
}
[TestMethod]
public void GetBicepConfigFilePathAndContents_WithValidBicepConfigFile_ShouldReturnUpdatedBicepConfigFile()
{
string testOutputPath = Path.Combine(TestContext.ResultsDirectory, Guid.NewGuid().ToString());
string bicepConfigFileContents = @"{
""analyzers"": {
""core"": {
""verbose"": false,
""enabled"": true,
""rules"": {
""no-unused-params"": {
""level"": ""warning""
}
}
}
}
}";
string bicepConfigFilePath = FileHelper.SaveResultFile(TestContext, "bicepconfig.json", bicepConfigFileContents, testOutputPath, Encoding.UTF8);
DocumentUri documentUri = DocumentUri.FromFileSystemPath("/path/to/main.bicep");
(string actualBicepConfigFilePath, string actualBicepConfigContents) = BicepDisableLinterRuleHandler.GetBicepConfigFilePathAndContents(documentUri, "no-unused-params", bicepConfigFilePath);
actualBicepConfigFilePath.Should().Be(bicepConfigFilePath);
actualBicepConfigContents.Should().BeEquivalentToIgnoringNewlines(@"{
""analyzers"": {
""core"": {
""verbose"": false,
""enabled"": true,
""rules"": {
""no-unused-params"": {
""level"": ""off""
}
}
}
}
}");
}
}
}
| 30.481236 | 235 | 0.565614 | [
"MIT"
] | Manny27nyc/bicep | src/Bicep.LangServer.UnitTests/Handlers/BicepDisableLinterRuleCommandHandlerTests.cs | 13,808 | C# |
/*
* Gridly API
*
* Gridly API documentation
*
* The version of the OpenAPI document: 3.29.0
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters;
using System.Text;
using System.Threading;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Web;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using ErrorEventArgs = Newtonsoft.Json.Serialization.ErrorEventArgs;
using RestSharp;
using RestSharp.Deserializers;
using RestSharpMethod = RestSharp.Method;
using Polly;
namespace Com.Gridly.Client
{
/// <summary>
/// Allows RestSharp to Serialize/Deserialize JSON using our custom logic, but only when ContentType is JSON.
/// </summary>
internal class CustomJsonCodec : RestSharp.Serializers.ISerializer, RestSharp.Deserializers.IDeserializer
{
private readonly IReadableConfiguration _configuration;
private static readonly string _contentType = "application/json";
private readonly JsonSerializerSettings _serializerSettings = new JsonSerializerSettings
{
// OpenAPI generated types generally hide default constructors.
ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor,
ContractResolver = new DefaultContractResolver
{
NamingStrategy = new CamelCaseNamingStrategy
{
OverrideSpecifiedNames = false
}
}
};
public CustomJsonCodec(IReadableConfiguration configuration)
{
_configuration = configuration;
}
public CustomJsonCodec(JsonSerializerSettings serializerSettings, IReadableConfiguration configuration)
{
_serializerSettings = serializerSettings;
_configuration = configuration;
}
/// <summary>
/// Serialize the object into a JSON string.
/// </summary>
/// <param name="obj">Object to be serialized.</param>
/// <returns>A JSON string.</returns>
public string Serialize(object obj)
{
if (obj != null && obj is Com.Gridly.Model.AbstractOpenAPISchema)
{
// the object to be serialized is an oneOf/anyOf schema
return ((Com.Gridly.Model.AbstractOpenAPISchema)obj).ToJson();
}
else
{
return JsonConvert.SerializeObject(obj, _serializerSettings);
}
}
public T Deserialize<T>(IRestResponse response)
{
var result = (T)Deserialize(response, typeof(T));
return result;
}
/// <summary>
/// Deserialize the JSON string into a proper object.
/// </summary>
/// <param name="response">The HTTP response.</param>
/// <param name="type">Object type.</param>
/// <returns>Object representation of the JSON string.</returns>
internal object Deserialize(IRestResponse response, Type type)
{
if (type == typeof(byte[])) // return byte array
{
return response.RawBytes;
}
// TODO: ? if (type.IsAssignableFrom(typeof(Stream)))
if (type == typeof(Stream))
{
var bytes = response.RawBytes;
if (response.Headers != null)
{
var filePath = string.IsNullOrEmpty(_configuration.TempFolderPath)
? Path.GetTempPath()
: _configuration.TempFolderPath;
var regex = new Regex(@"Content-Disposition=.*filename=['""]?([^'""\s]+)['""]?$");
foreach (var header in response.Headers)
{
var match = regex.Match(header.ToString());
if (match.Success)
{
string fileName = filePath + ClientUtils.SanitizeFilename(match.Groups[1].Value.Replace("\"", "").Replace("'", ""));
File.WriteAllBytes(fileName, bytes);
return new FileStream(fileName, FileMode.Open);
}
}
}
var stream = new MemoryStream(bytes);
return stream;
}
if (type.Name.StartsWith("System.Nullable`1[[System.DateTime")) // return a datetime object
{
return DateTime.Parse(response.Content, null, System.Globalization.DateTimeStyles.RoundtripKind);
}
if (type == typeof(string) || type.Name.StartsWith("System.Nullable")) // return primitive type
{
return Convert.ChangeType(response.Content, type);
}
// at this point, it must be a model (json)
try
{
return JsonConvert.DeserializeObject(response.Content, type, _serializerSettings);
}
catch (Exception e)
{
throw new ApiException(500, e.Message);
}
}
public string RootElement { get; set; }
public string Namespace { get; set; }
public string DateFormat { get; set; }
public string ContentType
{
get { return _contentType; }
set { throw new InvalidOperationException("Not allowed to set content type."); }
}
}
/// <summary>
/// Provides a default implementation of an Api client (both synchronous and asynchronous implementations),
/// encapsulating general REST accessor use cases.
/// </summary>
public partial class ApiClient : ISynchronousClient, IAsynchronousClient
{
private readonly string _baseUrl;
/// <summary>
/// Specifies the settings on a <see cref="JsonSerializer" /> object.
/// These settings can be adjusted to accommodate custom serialization rules.
/// </summary>
public JsonSerializerSettings SerializerSettings { get; set; } = new JsonSerializerSettings
{
// OpenAPI generated types generally hide default constructors.
ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor,
ContractResolver = new DefaultContractResolver
{
NamingStrategy = new CamelCaseNamingStrategy
{
OverrideSpecifiedNames = false
}
}
};
/// <summary>
/// Allows for extending request processing for <see cref="ApiClient"/> generated code.
/// </summary>
/// <param name="request">The RestSharp request object</param>
partial void InterceptRequest(IRestRequest request);
/// <summary>
/// Allows for extending response processing for <see cref="ApiClient"/> generated code.
/// </summary>
/// <param name="request">The RestSharp request object</param>
/// <param name="response">The RestSharp response object</param>
partial void InterceptResponse(IRestRequest request, IRestResponse response);
/// <summary>
/// Initializes a new instance of the <see cref="ApiClient" />, defaulting to the global configurations' base url.
/// </summary>
public ApiClient()
{
_baseUrl = Com.Gridly.Client.GlobalConfiguration.Instance.BasePath;
}
/// <summary>
/// Initializes a new instance of the <see cref="ApiClient" />
/// </summary>
/// <param name="basePath">The target service's base path in URL format.</param>
/// <exception cref="ArgumentException"></exception>
public ApiClient(string basePath)
{
if (string.IsNullOrEmpty(basePath))
throw new ArgumentException("basePath cannot be empty");
_baseUrl = basePath;
}
/// <summary>
/// Constructs the RestSharp version of an http method
/// </summary>
/// <param name="method">Swagger Client Custom HttpMethod</param>
/// <returns>RestSharp's HttpMethod instance.</returns>
/// <exception cref="ArgumentOutOfRangeException"></exception>
private RestSharpMethod Method(HttpMethod method)
{
RestSharpMethod other;
switch (method)
{
case HttpMethod.Get:
other = RestSharpMethod.GET;
break;
case HttpMethod.Post:
other = RestSharpMethod.POST;
break;
case HttpMethod.Put:
other = RestSharpMethod.PUT;
break;
case HttpMethod.Delete:
other = RestSharpMethod.DELETE;
break;
case HttpMethod.Head:
other = RestSharpMethod.HEAD;
break;
case HttpMethod.Options:
other = RestSharpMethod.OPTIONS;
break;
case HttpMethod.Patch:
other = RestSharpMethod.PATCH;
break;
default:
throw new ArgumentOutOfRangeException("method", method, null);
}
return other;
}
/// <summary>
/// Provides all logic for constructing a new RestSharp <see cref="RestRequest"/>.
/// At this point, all information for querying the service is known. Here, it is simply
/// mapped into the RestSharp request.
/// </summary>
/// <param name="method">The http verb.</param>
/// <param name="path">The target path (or resource).</param>
/// <param name="options">The additional request options.</param>
/// <param name="configuration">A per-request configuration object. It is assumed that any merge with
/// GlobalConfiguration has been done before calling this method.</param>
/// <returns>[private] A new RestRequest instance.</returns>
/// <exception cref="ArgumentNullException"></exception>
private RestRequest NewRequest(
HttpMethod method,
string path,
RequestOptions options,
IReadableConfiguration configuration)
{
if (path == null) throw new ArgumentNullException("path");
if (options == null) throw new ArgumentNullException("options");
if (configuration == null) throw new ArgumentNullException("configuration");
RestRequest request = new RestRequest(Method(method))
{
Resource = path,
JsonSerializer = new CustomJsonCodec(SerializerSettings, configuration)
};
if (options.PathParameters != null)
{
foreach (var pathParam in options.PathParameters)
{
request.AddParameter(pathParam.Key, pathParam.Value, ParameterType.UrlSegment);
}
}
if (options.QueryParameters != null)
{
foreach (var queryParam in options.QueryParameters)
{
foreach (var value in queryParam.Value)
{
request.AddQueryParameter(queryParam.Key, value);
}
}
}
if (configuration.DefaultHeaders != null)
{
foreach (var headerParam in configuration.DefaultHeaders)
{
request.AddHeader(headerParam.Key, headerParam.Value);
}
}
if (options.HeaderParameters != null)
{
foreach (var headerParam in options.HeaderParameters)
{
foreach (var value in headerParam.Value)
{
request.AddHeader(headerParam.Key, value);
}
}
}
if (options.FormParameters != null)
{
foreach (var formParam in options.FormParameters)
{
request.AddParameter(formParam.Key, formParam.Value);
}
}
if (options.Data != null)
{
if (options.Data is Stream stream)
{
var contentType = "application/octet-stream";
if (options.HeaderParameters != null)
{
var contentTypes = options.HeaderParameters["Content-Type"];
contentType = contentTypes[0];
}
var bytes = ClientUtils.ReadAsBytes(stream);
request.AddParameter(contentType, bytes, ParameterType.RequestBody);
}
else
{
if (options.HeaderParameters != null)
{
var contentTypes = options.HeaderParameters["Content-Type"];
if (contentTypes == null || contentTypes.Any(header => header.Contains("application/json")))
{
request.RequestFormat = DataFormat.Json;
}
else
{
// TODO: Generated client user should add additional handlers. RestSharp only supports XML and JSON, with XML as default.
}
}
else
{
// Here, we'll assume JSON APIs are more common. XML can be forced by adding produces/consumes to openapi spec explicitly.
request.RequestFormat = DataFormat.Json;
}
request.AddJsonBody(options.Data);
}
}
if (options.FileParameters != null)
{
foreach (var fileParam in options.FileParameters)
{
foreach (var file in fileParam.Value)
{
var bytes = ClientUtils.ReadAsBytes(file);
var fileStream = file as FileStream;
if (fileStream != null)
request.Files.Add(FileParameter.Create(fileParam.Key, bytes, System.IO.Path.GetFileName(fileStream.Name)));
else
request.Files.Add(FileParameter.Create(fileParam.Key, bytes, "no_file_name_provided"));
}
}
}
if (options.Cookies != null && options.Cookies.Count > 0)
{
foreach (var cookie in options.Cookies)
{
request.AddCookie(cookie.Name, cookie.Value);
}
}
return request;
}
private ApiResponse<T> ToApiResponse<T>(IRestResponse<T> response)
{
T result = response.Data;
string rawContent = response.Content;
var transformed = new ApiResponse<T>(response.StatusCode, new Multimap<string, string>(), result, rawContent)
{
ErrorText = response.ErrorMessage,
Cookies = new List<Cookie>()
};
if (response.Headers != null)
{
foreach (var responseHeader in response.Headers)
{
transformed.Headers.Add(responseHeader.Name, ClientUtils.ParameterToString(responseHeader.Value));
}
}
if (response.Cookies != null)
{
foreach (var responseCookies in response.Cookies)
{
transformed.Cookies.Add(
new Cookie(
responseCookies.Name,
responseCookies.Value,
responseCookies.Path,
responseCookies.Domain)
);
}
}
return transformed;
}
private ApiResponse<T> Exec<T>(RestRequest req, RequestOptions options, IReadableConfiguration configuration)
{
var baseUrl = configuration.GetOperationServerUrl(options.Operation, options.OperationIndex) ?? _baseUrl;
RestClient client = new RestClient(baseUrl);
client.ClearHandlers();
var existingDeserializer = req.JsonSerializer as IDeserializer;
if (existingDeserializer != null)
{
client.AddHandler("application/json", () => existingDeserializer);
client.AddHandler("text/json", () => existingDeserializer);
client.AddHandler("text/x-json", () => existingDeserializer);
client.AddHandler("text/javascript", () => existingDeserializer);
client.AddHandler("*+json", () => existingDeserializer);
}
else
{
var customDeserializer = new CustomJsonCodec(SerializerSettings, configuration);
client.AddHandler("application/json", () => customDeserializer);
client.AddHandler("text/json", () => customDeserializer);
client.AddHandler("text/x-json", () => customDeserializer);
client.AddHandler("text/javascript", () => customDeserializer);
client.AddHandler("*+json", () => customDeserializer);
}
var xmlDeserializer = new XmlDeserializer();
client.AddHandler("application/xml", () => xmlDeserializer);
client.AddHandler("text/xml", () => xmlDeserializer);
client.AddHandler("*+xml", () => xmlDeserializer);
client.AddHandler("*", () => xmlDeserializer);
client.Timeout = configuration.Timeout;
if (configuration.Proxy != null)
{
client.Proxy = configuration.Proxy;
}
if (configuration.UserAgent != null)
{
client.UserAgent = configuration.UserAgent;
}
if (configuration.ClientCertificates != null)
{
client.ClientCertificates = configuration.ClientCertificates;
}
InterceptRequest(req);
IRestResponse<T> response;
if (RetryConfiguration.RetryPolicy != null)
{
var policy = RetryConfiguration.RetryPolicy;
var policyResult = policy.ExecuteAndCapture(() => client.Execute(req));
response = (policyResult.Outcome == OutcomeType.Successful) ? client.Deserialize<T>(policyResult.Result) : new RestResponse<T>
{
Request = req,
ErrorException = policyResult.FinalException
};
}
else
{
response = client.Execute<T>(req);
}
// if the response type is oneOf/anyOf, call FromJSON to deserialize the data
if (typeof(Com.Gridly.Model.AbstractOpenAPISchema).IsAssignableFrom(typeof(T)))
{
try
{
response.Data = (T) typeof(T).GetMethod("FromJson").Invoke(null, new object[] { response.Content });
}
catch (Exception ex)
{
throw ex.InnerException != null ? ex.InnerException : ex;
}
}
else if (typeof(T).Name == "Stream") // for binary response
{
response.Data = (T)(object)new MemoryStream(response.RawBytes);
}
else if (typeof(T).Name == "Byte[]") // for byte response
{
response.Data = (T)(object)response.RawBytes;
}
InterceptResponse(req, response);
var result = ToApiResponse(response);
if (response.ErrorMessage != null)
{
result.ErrorText = response.ErrorMessage;
}
if (response.Cookies != null && response.Cookies.Count > 0)
{
if (result.Cookies == null) result.Cookies = new List<Cookie>();
foreach (var restResponseCookie in response.Cookies)
{
var cookie = new Cookie(
restResponseCookie.Name,
restResponseCookie.Value,
restResponseCookie.Path,
restResponseCookie.Domain
)
{
Comment = restResponseCookie.Comment,
CommentUri = restResponseCookie.CommentUri,
Discard = restResponseCookie.Discard,
Expired = restResponseCookie.Expired,
Expires = restResponseCookie.Expires,
HttpOnly = restResponseCookie.HttpOnly,
Port = restResponseCookie.Port,
Secure = restResponseCookie.Secure,
Version = restResponseCookie.Version
};
result.Cookies.Add(cookie);
}
}
return result;
}
private async Task<ApiResponse<T>> ExecAsync<T>(RestRequest req, RequestOptions options, IReadableConfiguration configuration, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
var baseUrl = configuration.GetOperationServerUrl(options.Operation, options.OperationIndex) ?? _baseUrl;
RestClient client = new RestClient(baseUrl);
client.ClearHandlers();
var existingDeserializer = req.JsonSerializer as IDeserializer;
if (existingDeserializer != null)
{
client.AddHandler("application/json", () => existingDeserializer);
client.AddHandler("text/json", () => existingDeserializer);
client.AddHandler("text/x-json", () => existingDeserializer);
client.AddHandler("text/javascript", () => existingDeserializer);
client.AddHandler("*+json", () => existingDeserializer);
}
else
{
var customDeserializer = new CustomJsonCodec(SerializerSettings, configuration);
client.AddHandler("application/json", () => customDeserializer);
client.AddHandler("text/json", () => customDeserializer);
client.AddHandler("text/x-json", () => customDeserializer);
client.AddHandler("text/javascript", () => customDeserializer);
client.AddHandler("*+json", () => customDeserializer);
}
var xmlDeserializer = new XmlDeserializer();
client.AddHandler("application/xml", () => xmlDeserializer);
client.AddHandler("text/xml", () => xmlDeserializer);
client.AddHandler("*+xml", () => xmlDeserializer);
client.AddHandler("*", () => xmlDeserializer);
client.Timeout = configuration.Timeout;
if (configuration.Proxy != null)
{
client.Proxy = configuration.Proxy;
}
if (configuration.UserAgent != null)
{
client.UserAgent = configuration.UserAgent;
}
if (configuration.ClientCertificates != null)
{
client.ClientCertificates = configuration.ClientCertificates;
}
InterceptRequest(req);
IRestResponse<T> response;
if (RetryConfiguration.AsyncRetryPolicy != null)
{
var policy = RetryConfiguration.AsyncRetryPolicy;
var policyResult = await policy.ExecuteAndCaptureAsync((ct) => client.ExecuteAsync(req, ct), cancellationToken).ConfigureAwait(false);
response = (policyResult.Outcome == OutcomeType.Successful) ? client.Deserialize<T>(policyResult.Result) : new RestResponse<T>
{
Request = req,
ErrorException = policyResult.FinalException
};
}
else
{
response = await client.ExecuteAsync<T>(req, cancellationToken).ConfigureAwait(false);
}
// if the response type is oneOf/anyOf, call FromJSON to deserialize the data
if (typeof(Com.Gridly.Model.AbstractOpenAPISchema).IsAssignableFrom(typeof(T)))
{
response.Data = (T) typeof(T).GetMethod("FromJson").Invoke(null, new object[] { response.Content });
}
else if (typeof(T).Name == "Stream") // for binary response
{
response.Data = (T)(object)new MemoryStream(response.RawBytes);
}
else if (typeof(T).Name == "Byte[]") // for byte response
{
response.Data = (T)(object)response.RawBytes;
}
InterceptResponse(req, response);
var result = ToApiResponse(response);
if (response.ErrorMessage != null)
{
result.ErrorText = response.ErrorMessage;
}
if (response.Cookies != null && response.Cookies.Count > 0)
{
if (result.Cookies == null) result.Cookies = new List<Cookie>();
foreach (var restResponseCookie in response.Cookies)
{
var cookie = new Cookie(
restResponseCookie.Name,
restResponseCookie.Value,
restResponseCookie.Path,
restResponseCookie.Domain
)
{
Comment = restResponseCookie.Comment,
CommentUri = restResponseCookie.CommentUri,
Discard = restResponseCookie.Discard,
Expired = restResponseCookie.Expired,
Expires = restResponseCookie.Expires,
HttpOnly = restResponseCookie.HttpOnly,
Port = restResponseCookie.Port,
Secure = restResponseCookie.Secure,
Version = restResponseCookie.Version
};
result.Cookies.Add(cookie);
}
}
return result;
}
#region IAsynchronousClient
/// <summary>
/// Make a HTTP GET request (async).
/// </summary>
/// <param name="path">The target path (or resource).</param>
/// <param name="options">The additional request options.</param>
/// <param name="configuration">A per-request configuration object. It is assumed that any merge with
/// GlobalConfiguration has been done before calling this method.</param>
/// <param name="cancellationToken">Token that enables callers to cancel the request.</param>
/// <returns>A Task containing ApiResponse</returns>
public Task<ApiResponse<T>> GetAsync<T>(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
var config = configuration ?? GlobalConfiguration.Instance;
return ExecAsync<T>(NewRequest(HttpMethod.Get, path, options, config), options, config, cancellationToken);
}
/// <summary>
/// Make a HTTP POST request (async).
/// </summary>
/// <param name="path">The target path (or resource).</param>
/// <param name="options">The additional request options.</param>
/// <param name="configuration">A per-request configuration object. It is assumed that any merge with
/// GlobalConfiguration has been done before calling this method.</param>
/// <param name="cancellationToken">Token that enables callers to cancel the request.</param>
/// <returns>A Task containing ApiResponse</returns>
public Task<ApiResponse<T>> PostAsync<T>(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
var config = configuration ?? GlobalConfiguration.Instance;
return ExecAsync<T>(NewRequest(HttpMethod.Post, path, options, config), options, config, cancellationToken);
}
/// <summary>
/// Make a HTTP PUT request (async).
/// </summary>
/// <param name="path">The target path (or resource).</param>
/// <param name="options">The additional request options.</param>
/// <param name="configuration">A per-request configuration object. It is assumed that any merge with
/// GlobalConfiguration has been done before calling this method.</param>
/// <param name="cancellationToken">Token that enables callers to cancel the request.</param>
/// <returns>A Task containing ApiResponse</returns>
public Task<ApiResponse<T>> PutAsync<T>(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
var config = configuration ?? GlobalConfiguration.Instance;
return ExecAsync<T>(NewRequest(HttpMethod.Put, path, options, config), options, config, cancellationToken);
}
/// <summary>
/// Make a HTTP DELETE request (async).
/// </summary>
/// <param name="path">The target path (or resource).</param>
/// <param name="options">The additional request options.</param>
/// <param name="configuration">A per-request configuration object. It is assumed that any merge with
/// GlobalConfiguration has been done before calling this method.</param>
/// <param name="cancellationToken">Token that enables callers to cancel the request.</param>
/// <returns>A Task containing ApiResponse</returns>
public Task<ApiResponse<T>> DeleteAsync<T>(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
var config = configuration ?? GlobalConfiguration.Instance;
return ExecAsync<T>(NewRequest(HttpMethod.Delete, path, options, config), options, config, cancellationToken);
}
/// <summary>
/// Make a HTTP HEAD request (async).
/// </summary>
/// <param name="path">The target path (or resource).</param>
/// <param name="options">The additional request options.</param>
/// <param name="configuration">A per-request configuration object. It is assumed that any merge with
/// GlobalConfiguration has been done before calling this method.</param>
/// <param name="cancellationToken">Token that enables callers to cancel the request.</param>
/// <returns>A Task containing ApiResponse</returns>
public Task<ApiResponse<T>> HeadAsync<T>(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
var config = configuration ?? GlobalConfiguration.Instance;
return ExecAsync<T>(NewRequest(HttpMethod.Head, path, options, config), options, config, cancellationToken);
}
/// <summary>
/// Make a HTTP OPTION request (async).
/// </summary>
/// <param name="path">The target path (or resource).</param>
/// <param name="options">The additional request options.</param>
/// <param name="configuration">A per-request configuration object. It is assumed that any merge with
/// GlobalConfiguration has been done before calling this method.</param>
/// <param name="cancellationToken">Token that enables callers to cancel the request.</param>
/// <returns>A Task containing ApiResponse</returns>
public Task<ApiResponse<T>> OptionsAsync<T>(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
var config = configuration ?? GlobalConfiguration.Instance;
return ExecAsync<T>(NewRequest(HttpMethod.Options, path, options, config), options, config, cancellationToken);
}
/// <summary>
/// Make a HTTP PATCH request (async).
/// </summary>
/// <param name="path">The target path (or resource).</param>
/// <param name="options">The additional request options.</param>
/// <param name="configuration">A per-request configuration object. It is assumed that any merge with
/// GlobalConfiguration has been done before calling this method.</param>
/// <param name="cancellationToken">Token that enables callers to cancel the request.</param>
/// <returns>A Task containing ApiResponse</returns>
public Task<ApiResponse<T>> PatchAsync<T>(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
var config = configuration ?? GlobalConfiguration.Instance;
return ExecAsync<T>(NewRequest(HttpMethod.Patch, path, options, config), options, config, cancellationToken);
}
#endregion IAsynchronousClient
#region ISynchronousClient
/// <summary>
/// Make a HTTP GET request (synchronous).
/// </summary>
/// <param name="path">The target path (or resource).</param>
/// <param name="options">The additional request options.</param>
/// <param name="configuration">A per-request configuration object. It is assumed that any merge with
/// GlobalConfiguration has been done before calling this method.</param>
/// <returns>A Task containing ApiResponse</returns>
public ApiResponse<T> Get<T>(string path, RequestOptions options, IReadableConfiguration configuration = null)
{
var config = configuration ?? GlobalConfiguration.Instance;
return Exec<T>(NewRequest(HttpMethod.Get, path, options, config), options, config);
}
/// <summary>
/// Make a HTTP POST request (synchronous).
/// </summary>
/// <param name="path">The target path (or resource).</param>
/// <param name="options">The additional request options.</param>
/// <param name="configuration">A per-request configuration object. It is assumed that any merge with
/// GlobalConfiguration has been done before calling this method.</param>
/// <returns>A Task containing ApiResponse</returns>
public ApiResponse<T> Post<T>(string path, RequestOptions options, IReadableConfiguration configuration = null)
{
var config = configuration ?? GlobalConfiguration.Instance;
return Exec<T>(NewRequest(HttpMethod.Post, path, options, config), options, config);
}
/// <summary>
/// Make a HTTP PUT request (synchronous).
/// </summary>
/// <param name="path">The target path (or resource).</param>
/// <param name="options">The additional request options.</param>
/// <param name="configuration">A per-request configuration object. It is assumed that any merge with
/// GlobalConfiguration has been done before calling this method.</param>
/// <returns>A Task containing ApiResponse</returns>
public ApiResponse<T> Put<T>(string path, RequestOptions options, IReadableConfiguration configuration = null)
{
var config = configuration ?? GlobalConfiguration.Instance;
return Exec<T>(NewRequest(HttpMethod.Put, path, options, config), options, config);
}
/// <summary>
/// Make a HTTP DELETE request (synchronous).
/// </summary>
/// <param name="path">The target path (or resource).</param>
/// <param name="options">The additional request options.</param>
/// <param name="configuration">A per-request configuration object. It is assumed that any merge with
/// GlobalConfiguration has been done before calling this method.</param>
/// <returns>A Task containing ApiResponse</returns>
public ApiResponse<T> Delete<T>(string path, RequestOptions options, IReadableConfiguration configuration = null)
{
var config = configuration ?? GlobalConfiguration.Instance;
return Exec<T>(NewRequest(HttpMethod.Delete, path, options, config), options, config);
}
/// <summary>
/// Make a HTTP HEAD request (synchronous).
/// </summary>
/// <param name="path">The target path (or resource).</param>
/// <param name="options">The additional request options.</param>
/// <param name="configuration">A per-request configuration object. It is assumed that any merge with
/// GlobalConfiguration has been done before calling this method.</param>
/// <returns>A Task containing ApiResponse</returns>
public ApiResponse<T> Head<T>(string path, RequestOptions options, IReadableConfiguration configuration = null)
{
var config = configuration ?? GlobalConfiguration.Instance;
return Exec<T>(NewRequest(HttpMethod.Head, path, options, config), options, config);
}
/// <summary>
/// Make a HTTP OPTION request (synchronous).
/// </summary>
/// <param name="path">The target path (or resource).</param>
/// <param name="options">The additional request options.</param>
/// <param name="configuration">A per-request configuration object. It is assumed that any merge with
/// GlobalConfiguration has been done before calling this method.</param>
/// <returns>A Task containing ApiResponse</returns>
public ApiResponse<T> Options<T>(string path, RequestOptions options, IReadableConfiguration configuration = null)
{
var config = configuration ?? GlobalConfiguration.Instance;
return Exec<T>(NewRequest(HttpMethod.Options, path, options, config), options, config);
}
/// <summary>
/// Make a HTTP PATCH request (synchronous).
/// </summary>
/// <param name="path">The target path (or resource).</param>
/// <param name="options">The additional request options.</param>
/// <param name="configuration">A per-request configuration object. It is assumed that any merge with
/// GlobalConfiguration has been done before calling this method.</param>
/// <returns>A Task containing ApiResponse</returns>
public ApiResponse<T> Patch<T>(string path, RequestOptions options, IReadableConfiguration configuration = null)
{
var config = configuration ?? GlobalConfiguration.Instance;
return Exec<T>(NewRequest(HttpMethod.Patch, path, options, config), options, config);
}
#endregion ISynchronousClient
}
}
| 45.52381 | 234 | 0.576833 | [
"MIT"
] | gridly-spreadsheet-CMS/gridly-netcore-sdk | src/Com.Gridly/Client/ApiClient.cs | 40,152 | C# |
using Microsoft.AspNetCore.Html;
namespace AgileDotNetHtml.Models
{
public class HtmlNodeElementText
{
public HtmlNodeElementText(HtmlString htmlString)
{
HtmlString = htmlString;
}
public HtmlNodeElementText(HtmlString htmlString, string afterElementUId)
{
HtmlString = htmlString;
AfterElementUId = afterElementUId;
}
public HtmlString HtmlString { get; set; }
public string AfterElementUId { get; set; }
}
}
| 21.047619 | 75 | 0.755656 | [
"MIT"
] | atanasgalchov/AgileDotNetHtml | src/Models/HtmlNodeElementText.cs | 444 | 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 health-2016-08-04.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using System.Xml.Serialization;
using Amazon.AWSHealth.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.AWSHealth.Model.Internal.MarshallTransformations
{
/// <summary>
/// Response Unmarshaller for DescribeEvents operation
/// </summary>
public class DescribeEventsResponseUnmarshaller : JsonResponseUnmarshaller
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context)
{
DescribeEventsResponse response = new DescribeEventsResponse();
context.Read();
int targetDepth = context.CurrentDepth;
while (context.ReadAtDepth(targetDepth))
{
if (context.TestExpression("events", targetDepth))
{
var unmarshaller = new ListUnmarshaller<Event, EventUnmarshaller>(EventUnmarshaller.Instance);
response.Events = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("nextToken", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
response.NextToken = unmarshaller.Unmarshall(context);
continue;
}
}
return response;
}
/// <summary>
/// Unmarshaller error response to exception.
/// </summary>
/// <param name="context"></param>
/// <param name="innerException"></param>
/// <param name="statusCode"></param>
/// <returns></returns>
public override AmazonServiceException UnmarshallException(JsonUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode)
{
var errorResponse = JsonErrorResponseUnmarshaller.GetInstance().Unmarshall(context);
errorResponse.InnerException = innerException;
errorResponse.StatusCode = statusCode;
var responseBodyBytes = context.GetResponseBodyBytes();
using (var streamCopy = new MemoryStream(responseBodyBytes))
using (var contextCopy = new JsonUnmarshallerContext(streamCopy, false, null))
{
if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidPaginationToken"))
{
return InvalidPaginationTokenExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("UnsupportedLocale"))
{
return UnsupportedLocaleExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
}
return new AmazonAWSHealthException(errorResponse.Message, errorResponse.InnerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, errorResponse.StatusCode);
}
private static DescribeEventsResponseUnmarshaller _instance = new DescribeEventsResponseUnmarshaller();
internal static DescribeEventsResponseUnmarshaller GetInstance()
{
return _instance;
}
/// <summary>
/// Gets the singleton.
/// </summary>
public static DescribeEventsResponseUnmarshaller Instance
{
get
{
return _instance;
}
}
}
} | 39.241667 | 193 | 0.623487 | [
"Apache-2.0"
] | philasmar/aws-sdk-net | sdk/src/Services/AWSHealth/Generated/Model/Internal/MarshallTransformations/DescribeEventsResponseUnmarshaller.cs | 4,709 | C# |
using CIE.MRTD.SDK.Crypto;
using CIE.MRTD.SDK.Util;
using System;
using System.Numerics;
namespace CIE.MRTD.SDK.EAC
{
internal class DHKey
{
public ByteArray Public;
public ByteArray Private;
}
internal interface IPACEMapping
{
IPACEAlgo Map(byte[] secret, byte[] nonce);
}
internal interface IPACEAlgo : ICloneable
{
DHKey GenerateKeyPair();
byte[] GetSharedSecret(byte[] otherPubKey);
byte[] Encrypt(byte[] data);
}
internal class PACEAlgo
{
public ASN1Tag DG14Tag;
public IPACEMapping mapping;
public IPACEAlgo algo1;
public IPACEAlgo algo2;
public byte[] GetSharedSecret1(byte[] otherPubKey)
{
return algo1.GetSharedSecret(otherPubKey);
}
public byte[] GetSharedSecret2(byte[] otherPubKey)
{
return algo2.GetSharedSecret(otherPubKey);
}
public void DoMapping(byte[] secret, byte[] nonce) {
algo2 = mapping.Map(secret, nonce);
}
public PACEAlgo(ASN1Tag tag)
{
// dovrei inizializzare i vari componenti in base all'OID del tag.
// per adesso mi limito a DH_GM
DG14Tag = tag;
algo1 = new DHAlgo(DG14Tag);
mapping = new GenericMapping(algo1);
}
public DHKey GenerateEphimeralKey1()
{
return algo1.GenerateKeyPair();
}
public DHKey GenerateEphimeralKey2()
{
return algo2.GenerateKeyPair();
}
}
internal class GenericMapping : IPACEMapping
{
public IPACEAlgo algo;
public GenericMapping(IPACEAlgo algo)
{
this.algo = algo;
}
public IPACEAlgo Map(byte[] secret, byte[] nonce) {
IPACEAlgo newAlgo=algo.Clone() as IPACEAlgo;
if (newAlgo is DHAlgo) {
var dhNewAlgo = newAlgo as DHAlgo;
var temp = BigInteger.ModPow(dhNewAlgo.Group, new ByteArray(nonce), dhNewAlgo.Prime);
var temp2 = BigInteger.Multiply(temp, new ByteArray(secret));
dhNewAlgo.Group = BigInteger.Remainder(temp2, dhNewAlgo.Prime);
}
return newAlgo;
}
}
internal class DHAlgo : IPACEAlgo
{
public object Clone() {
return new DHAlgo(DG14Tag)
{
Group = Group,
Order = Order,
Prime = Prime,
Key = Key
};
}
public byte[] Encrypt(byte[] data) {
return null;
}
public byte[] GetSharedSecret(byte[] otherPubKey) {
return DiffieHellmann.ComputeKey(Group, Prime, Key.Private, otherPubKey);
}
public static ByteArray StandardDHParam2Prime = new ByteArray("87A8E61D B4B6663C FFBBD19C 65195999 8CEEF608 660DD0F2 5D2CEED4 435E3B00 E00DF8F1 D61957D4 FAF7DF45 61B2AA30 16C3D911 34096FAA 3BF4296D 830E9A7C 209E0C64 97517ABD 5A8A9D30 6BCF67ED 91F9E672 5B4758C0 22E0B1EF 4275BF7B 6C5BFC11 D45F9088 B941F54E B1E59BB8 BC39A0BF 12307F5C 4FDB70C5 81B23F76 B63ACAE1 CAA6B790 2D525267 35488A0E F13C6D9A 51BFA4AB 3AD83477 96524D8E F6A167B5 A41825D9 67E144E5 14056425 1CCACB83 E6B486F6 B3CA3F79 71506026 C0B857F6 89962856 DED4010A BD0BE621 C3A3960A 54E710C3 75F26375 D7014103 A4B54330 C198AF12 6116D227 6E11715F 693877FA D7EF09CA DB094AE9 1E1A1597");
public static ByteArray StandardDHParam2Group = new ByteArray("3FB32C9B 73134D0B 2E775066 60EDBD48 4CA7B18F 21EF2054 07F4793A 1A0BA125 10DBC150 77BE463F FF4FED4A AC0BB555 BE3A6C1B 0C6B47B1 BC3773BF 7E8C6F62 901228F8 C28CBB18 A55AE313 41000A65 0196F931 C77A57F2 DDF463E5 E9EC144B 777DE62A AAB8A862 8AC376D2 82D6ED38 64E67982 428EBC83 1D14348F 6F2F9193 B5045AF2 767164E1 DFC967C1 FB3F2E55 A4BD1BFF E83B9C80 D052B985 D182EA0A DB2A3B73 13D3FE14 C8484B1E 052588B9 B7D2BBD2 DF016199 ECD06E15 57CD0915 B3353BBB 64E0EC37 7FD02837 0DF92B52 C7891428 CDC67EB6 184B523D 1DB246C3 2F630784 90F00EF8 D647D148 D4795451 5E2327CF EF98C582 664B4C0F 6CC41659");
public static ByteArray StandardDHParam2Order = new ByteArray("8CF83642 A709A097 B4479976 40129DA2 99B1A47D 1EB3750B A308B0FE 64F5FBD3");
public ByteArray Prime;
public ByteArray Group;
public ByteArray Order;
public DHKey Key;
public DHKey GenerateKeyPair() {
Key = new DHKey();
DiffieHellmann.GenerateKey(Group, Prime, ref Key.Private, ref Key.Public);
return Key;
}
public ASN1Tag DG14Tag;
public DHAlgo(ASN1Tag tag)
{
var paramId = new ByteArray(tag.CheckTag(0x30).Child(2, 0x02).Data).ToUInt;
if (paramId != 2)
throw new Exception("Parametri di default : " + paramId.ToString() + " non supportati");
Prime = StandardDHParam2Prime;
Group = StandardDHParam2Group;
Order = StandardDHParam2Order;
DG14Tag = tag;
}
}
}
| 38.992481 | 650 | 0.627266 | [
"BSD-3-Clause"
] | italia/cie-mrtd-dotnet-sdk | CIE.MRTD.SDK/EAC/PACE.cs | 5,188 | C# |
using System.Collections.Generic;
using System.Linq;
using Andover.Domain.Components.Content.Provider;
using Andover.Domain.Components.Content.Results;
using Andover.Domain.Components.Database.Results;
using Andover.Domain.Core;
using Andover.Domain.Core.Results;
namespace Andover.Domain.Components.Content
{
public class ItemChildrenComponent : ComponentBase, IComponent
{
private IContentProvider _contentProvider;
public ItemChildrenComponent(IContentProvider contentProvider)
{
_contentProvider = contentProvider;
}
public override IEnumerable<IComponentResult> Analyze()
{
// analysis done in provider via Sitecore.Kernel
return _contentProvider.GetChildItemsList();
}
public bool IsCompliant
{
get
{
bool isCompliant = !Results<ItemCounter>().Any(ci => ci.IsCountPastThreshold);
return isCompliant;
}
}
}
}
| 24.361111 | 82 | 0.766249 | [
"MIT"
] | PetersonDave/Andover | Source/Andover.Domain/Components/Content/ItemChildrenComponent.cs | 879 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace ByYsmn.Application.Shared
{
public interface IBaseService<TPKey, TCreateInput, TUpdateInput, TModel>
{
Task <List<TModel>> GetAll();
Task <List<TModel>> GetAllByUserId(Guid userId);
Task <List<TModel>> GetAllByKeyWord(string input);
Task <TModel> Get(EntityInput<TPKey> input);
Task <TModel> Create(TCreateInput input);
Task <TModel> Update(TUpdateInput input);
Task <TModel> Delete(EntityInput<TPKey> input);
}
}
| 31.105263 | 76 | 0.692047 | [
"MIT"
] | yasemenclik/ByYasemen | src/ByYsmn.Application/Shared/IBaseService.cs | 593 | C# |
namespace SeleniumScript.Implementation
{
using Antlr4.Runtime;
using Grammar;
using Exceptions;
using Interfaces;
using System;
using global::SeleniumScript.Factories;
using global::SeleniumScript.Enums;
using System.Collections.Generic;
public class SeleniumScript : ISeleniumScript, IDisposable
{
private readonly ISeleniumScriptLogger seleniumScriptLogger;
private readonly ISeleniumScriptWebDriver seleniumScriptWebDriver;
private readonly ISeleniumScriptInterpreter seleniumScriptVisitor;
private readonly Dictionary<string, Action> callbackHandlers = new Dictionary<string, Action>();
public event LogEventHandler OnLogEntryWritten;
private Dictionary<string, SeleniumScriptLogLevel> exceptionLogLevels = new Dictionary<string, SeleniumScriptLogLevel>()
{
{ typeof(SeleniumScriptException).Name, SeleniumScriptLogLevel.SeleniumScriptError },
{ typeof(SeleniumScriptSyntaxException).Name, SeleniumScriptLogLevel.SyntaxError },
{ typeof(SeleniumScriptVisitorException).Name, SeleniumScriptLogLevel.VisitorError },
{ typeof(SeleniumScriptWebDriverException).Name, SeleniumScriptLogLevel.WebDriverError },
{ typeof(Exception).Name, SeleniumScriptLogLevel.RuntimeError }
};
public SeleniumScript(OpenQA.Selenium.IWebDriver webDriver)
{
this.seleniumScriptLogger = new SeleniumScriptLogger();
seleniumScriptLogger.OnLogEntryWritten += (log) => OnLogEntryWritten(log);
this.seleniumScriptWebDriver = new SeleniumScriptWebDriver(webDriver, seleniumScriptLogger);
var callStack = new CallStack(new StackFrameHandlerFactory(), seleniumScriptLogger);
this.seleniumScriptVisitor = new SeleniumScriptInterpreter(seleniumScriptWebDriver, callStack, seleniumScriptLogger);
this.seleniumScriptVisitor.OnCallback += (callback) => HandleCallback(callback);
this.OnLogEntryWritten += (log) => { };
}
public void Run(string script)
{
var seleniumScriptLexer = new SeleniumScriptLexer(new AntlrInputStream(script));
var seleniumScriptParser = new SeleniumScriptParser(new CommonTokenStream(seleniumScriptLexer));
seleniumScriptParser.AddErrorListener(new SeleniumScriptSyntaxErrorListener());
try
{
seleniumScriptVisitor.Run(seleniumScriptParser.executionUnit());
}
catch (Exception e)
{
seleniumScriptLogger.Log(e.Message, exceptionLogLevels.ContainsKey(e.getType().Name) ? exceptionLogLevels[e.GetType().Name] : SeleniumScriptLogLevel.Undefined);
Dispose();
throw e;
}
}
public void RegisterCallbackHandler(string callBackName, Action action)
{
callbackHandlers.Add(callBackName, action);
}
private void HandleCallback(string callback)
{
if (!callbackHandlers.ContainsKey(callback))
{
throw new SeleniumScriptException($"Callback with name {callback} has not been registered");
}
callbackHandlers[callback]();
}
public void Dispose()
{
seleniumScriptWebDriver.Close();
}
}
}
| 37.349398 | 168 | 0.744194 | [
"MIT"
] | karisigurd4/SeleniumScript | SeleniumScript/Implementation/SeleniumScript.cs | 3,102 | 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("PhotoOfTheDay.WebApp")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("PhotoOfTheDay.WebApp")]
[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("3cb6fc9c-1006-4a47-b20d-cc083541d9b2")]
// 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 Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 38 | 84 | 0.752924 | [
"MIT"
] | AzureUserGroupBulgaria/Meetups2017 | 04-April/source/PhotoOfTheDay/PhotoOfTheDay.WebApp/Properties/AssemblyInfo.cs | 1,371 | C# |
using System;
using Android.Content;
using Android.Text;
using Android.Widget;
namespace Comet.Android.Handlers
{
public class SecureFieldHandler : AbstractControlHandler<SecureField, EditText>
{
public static readonly PropertyMapper<SecureField> Mapper = new PropertyMapper<SecureField>(ViewHandler.Mapper)
{
[nameof(TextField.Text)] = MapTextProperty,
[EnvironmentKeys.Colors.Color] = MapColorProperty,
};
public SecureFieldHandler() : base(Mapper)
{
}
static Color DefaultColor;
protected override EditText CreateView(Context context)
{
var editText = new EditText(context);
editText.InputType = InputTypes.TextVariationPassword;
if (DefaultColor == null)
{
DefaultColor = editText.CurrentTextColor.ToColor();
}
editText.TextChanged += HandleTextChanged;
return editText;
}
protected override void DisposeView(EditText nativeView)
{
nativeView.TextChanged -= HandleTextChanged;
}
private void HandleTextChanged(object sender, EventArgs e)
{
VirtualView?.OnCommit?.Invoke(TypedNativeView.Text);
}
public static void MapTextProperty(IViewHandler viewHandler, SecureField virtualView)
{
var nativeView = (EditText)viewHandler.NativeView;
nativeView.Text = virtualView.Text?.CurrentValue ?? string.Empty;
}
public static void MapColorProperty(IViewHandler viewHandler, SecureField virtualView)
{
var textView = (EditText)viewHandler.NativeView;
var color = virtualView.GetColor(DefaultColor).ToColor();
textView.SetTextColor(color);
}
public static void MapTextAlignmentProperty(IViewHandler viewHandler, SecureField virtualView)
{
var nativeView = (EditText)viewHandler.NativeView;
var textAlignment = virtualView.GetTextAlignment();
nativeView.TextAlignment = textAlignment.ToAndroidTextAlignment();
virtualView.InvalidateMeasurement();
}
}
}
| 29.203125 | 113 | 0.76458 | [
"MIT"
] | VincentH-Net/Comet | src/Comet.Android/Handlers/SecureFieldHandler.cs | 1,871 | C# |
using System.Threading.Tasks;
namespace Communication.Types.Interfaces
{
public interface IUserPreferencesProvider
{
string UserType { get; }
Task<CommunicationUserPreference> GetUserPreferenceAsync(string requestType, CommunicationUser user);
}
} | 27.6 | 109 | 0.757246 | [
"MIT"
] | SkillsFundingAgency/das-recru | src/Communication/Communication.Types/Interfaces/IUserPreferencesProvider.cs | 276 | C# |
#if USE_UNI_LUA
using LuaAPI = UniLua.Lua;
using RealStatePtr = UniLua.ILuaState;
using LuaCSFunction = UniLua.CSharpFunctionDelegate;
#else
using LuaAPI = XLua.LuaDLL.Lua;
using RealStatePtr = System.IntPtr;
using LuaCSFunction = XLua.LuaDLL.lua_CSFunction;
#endif
using XLua;
using System.Collections.Generic;
namespace XLua.CSObjectWrap
{
using Utils = XLua.Utils;
public class XLuaCSObjectWrapXLuaCSObjectWrapMongoDBBsonSerializationConventionsDelegateClassMapConventionWrapWrapWrap
{
public static void __Register(RealStatePtr L)
{
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
System.Type type = typeof(XLua.CSObjectWrap.XLuaCSObjectWrapMongoDBBsonSerializationConventionsDelegateClassMapConventionWrapWrap);
Utils.BeginObjectRegister(type, L, translator, 0, 0, 0, 0);
Utils.EndObjectRegister(type, L, translator, null, null,
null, null, null);
Utils.BeginClassRegister(type, L, __CreateInstance, 2, 0, 0);
Utils.RegisterFunc(L, Utils.CLS_IDX, "__Register", _m___Register_xlua_st_);
Utils.EndClassRegister(type, L, translator);
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int __CreateInstance(RealStatePtr L)
{
try {
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
if(LuaAPI.lua_gettop(L) == 1)
{
XLua.CSObjectWrap.XLuaCSObjectWrapMongoDBBsonSerializationConventionsDelegateClassMapConventionWrapWrap gen_ret = new XLua.CSObjectWrap.XLuaCSObjectWrapMongoDBBsonSerializationConventionsDelegateClassMapConventionWrapWrap();
translator.Push(L, gen_ret);
return 1;
}
}
catch(System.Exception gen_e) {
return LuaAPI.luaL_error(L, "c# exception:" + gen_e);
}
return LuaAPI.luaL_error(L, "invalid arguments to XLua.CSObjectWrap.XLuaCSObjectWrapMongoDBBsonSerializationConventionsDelegateClassMapConventionWrapWrap constructor!");
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int _m___Register_xlua_st_(RealStatePtr L)
{
try {
{
System.IntPtr _L = LuaAPI.lua_touserdata(L, 1);
XLua.CSObjectWrap.XLuaCSObjectWrapMongoDBBsonSerializationConventionsDelegateClassMapConventionWrapWrap.__Register( _L );
return 0;
}
} catch(System.Exception gen_e) {
return LuaAPI.luaL_error(L, "c# exception:" + gen_e);
}
}
}
}
| 26.954545 | 229 | 0.611804 | [
"MIT"
] | zxsean/DCET | Unity/Assets/Model/XLua/Gen/XLuaCSObjectWrapXLuaCSObjectWrapMongoDBBsonSerializationConventionsDelegateClassMapConventionWrapWrapWrap.cs | 2,967 | C# |
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information.
// Ported from um/Windows.Devices.Display.Core.Interop.h in the Windows SDK for Windows 10.0.22000.0
// Original source is Copyright © Microsoft. All rights reserved.
using System;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace TerraFX.Interop.Windows;
public static partial class IID
{
public static ref readonly Guid IID_IDisplayDeviceInterop
{
get
{
ReadOnlySpan<byte> data = new byte[] {
0x58, 0x83, 0x33, 0x64,
0x6A, 0x36,
0x1B, 0x47,
0xBD,
0x56,
0xDD,
0x8E,
0xF4,
0x8E,
0x43,
0x9B
};
Debug.Assert(data.Length == Unsafe.SizeOf<Guid>());
return ref Unsafe.As<byte, Guid>(ref MemoryMarshal.GetReference(data));
}
}
public static ref readonly Guid IID_IDisplayPathInterop
{
get
{
ReadOnlySpan<byte> data = new byte[] {
0x05, 0x42, 0xBA, 0xA6,
0x9E, 0xE5,
0x71, 0x4E,
0xB2,
0x5B,
0x4E,
0x43,
0x6D,
0x21,
0xEE,
0x3D
};
Debug.Assert(data.Length == Unsafe.SizeOf<Guid>());
return ref Unsafe.As<byte, Guid>(ref MemoryMarshal.GetReference(data));
}
}
}
| 27.672131 | 145 | 0.521327 | [
"MIT"
] | reflectronic/terrafx.interop.windows | sources/Interop/Windows/WinRT/um/Windows.Devices.Display.Core.Interop/IID.cs | 1,690 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Text;
namespace System.Reflection
{
public class CustomAttributeData
{
#region Public Static Members
public static IList<CustomAttributeData> GetCustomAttributes(MemberInfo target)
{
ArgumentNullException.ThrowIfNull(target);
return target.GetCustomAttributesData();
}
public static IList<CustomAttributeData> GetCustomAttributes(Module target)
{
ArgumentNullException.ThrowIfNull(target);
return target.GetCustomAttributesData();
}
public static IList<CustomAttributeData> GetCustomAttributes(Assembly target)
{
ArgumentNullException.ThrowIfNull(target);
return target.GetCustomAttributesData();
}
public static IList<CustomAttributeData> GetCustomAttributes(ParameterInfo target)
{
ArgumentNullException.ThrowIfNull(target);
return target.GetCustomAttributesData();
}
#endregion
protected CustomAttributeData()
{
}
#region Object Override
public override string ToString()
{
var vsb = new ValueStringBuilder(stackalloc char[256]);
vsb.Append('[');
vsb.Append(Constructor.DeclaringType!.FullName);
vsb.Append('(');
bool first = true;
IList<CustomAttributeTypedArgument> constructorArguments = ConstructorArguments;
int constructorArgumentsCount = constructorArguments.Count;
for (int i = 0; i < constructorArgumentsCount; i++)
{
if (!first) vsb.Append(", ");
vsb.Append(constructorArguments[i].ToString());
first = false;
}
IList<CustomAttributeNamedArgument> namedArguments = NamedArguments;
int namedArgumentsCount = namedArguments.Count;
for (int i = 0; i < namedArgumentsCount; i++)
{
if (!first) vsb.Append(", ");
vsb.Append(namedArguments[i].ToString());
first = false;
}
vsb.Append(")]");
return vsb.ToString();
}
public override int GetHashCode() => base.GetHashCode();
public override bool Equals(object? obj) => obj == (object)this;
#endregion
#region Public Members
public virtual Type AttributeType => Constructor.DeclaringType!;
// Expected to be overriden
public virtual ConstructorInfo Constructor => null!;
public virtual IList<CustomAttributeTypedArgument> ConstructorArguments => null!;
public virtual IList<CustomAttributeNamedArgument> NamedArguments => null!;
#endregion
}
}
| 32.204301 | 92 | 0.619366 | [
"MIT"
] | Ali-YousefiTelori/runtime | src/libraries/System.Private.CoreLib/src/System/Reflection/CustomAttributeData.cs | 2,995 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data;
using System.Data.Common;
using System.IO;
using System.Runtime.ExceptionServices;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using AdoNetCore.AseClient.Enum;
using AdoNetCore.AseClient.Interface;
using AdoNetCore.AseClient.Internal.Handler;
using AdoNetCore.AseClient.Packet;
using AdoNetCore.AseClient.Token;
namespace AdoNetCore.AseClient.Internal
{
internal class InternalConnection : IInternalConnection
{
private readonly IConnectionParameters _parameters;
private readonly Stream _networkStream;
private readonly ITokenReader _reader;
private readonly DbEnvironment _environment;
private readonly object _sendMutex;
private bool _statisticsEnabled;
#if ENABLE_ARRAY_POOL
/// <summary>
/// The <see cref="System.Buffers.ArrayPool{T}"/> to use for efficient buffer allocation.
/// </summary>
private readonly System.Buffers.ArrayPool<byte> _arrayPool;
#endif
private enum InternalConnectionState
{
// ReSharper disable InconsistentNaming
None,
Ready,
Active,
Canceled,
Broken
// ReSharper restore InconsistentNaming
}
private InternalConnectionState _state = InternalConnectionState.None;
private readonly object _stateMutex = new object();
private void SetState(InternalConnectionState newState)
{
lock (_stateMutex)
{
//if the connection's state is broken, it can't get any more broken!
if (_state == newState)
{
return;
}
if (_state == InternalConnectionState.Broken)
{
throw new ArgumentException("Cannot change internal connection state as it is Broken");
}
_state = newState;
}
}
private bool TrySetState(InternalConnectionState newState, Func<InternalConnectionState, bool> predicate)
{
lock (_stateMutex)
{
if (_state == InternalConnectionState.Broken || !predicate(_state))
{
return false;
}
_state = newState;
return true;
}
}
#if ENABLE_ARRAY_POOL
public InternalConnection(IConnectionParameters parameters, Stream networkStream, ITokenReader reader, DbEnvironment environment, System.Buffers.ArrayPool<byte> arrayPool)
#else
public InternalConnection(IConnectionParameters parameters, Stream networkStream, ITokenReader reader, DbEnvironment environment)
#endif
{
_parameters = parameters;
_networkStream = networkStream;
_reader = reader;
_environment = environment;
_environment.PacketSize = parameters.PacketSize; //server might decide to change the packet size later anyway
_environment.UseAseDecimal = parameters.UseAseDecimal;
_sendMutex = new object();
#if ENABLE_ARRAY_POOL
_arrayPool = arrayPool;
#endif
}
private void SendPacket(IPacket packet)
{
Logger.Instance?.WriteLine();
Logger.Instance?.WriteLine("---------- Send packet ----------");
try
{
lock (_sendMutex)
{
#if ENABLE_ARRAY_POOL
using (var tokenStream = new TokenSendStream(_networkStream, _environment, _arrayPool))
#else
using (var tokenStream = new TokenSendStream(_networkStream, _environment))
#endif
{
// ReSharper disable once InconsistentlySynchronizedField
tokenStream.SetBufferType(packet.Type, packet.Status);
packet.Write(tokenStream, _environment);
tokenStream.Flush();
}
}
}
catch
{
IsDoomed = true;
throw;
}
finally
{
LastActive = DateTime.UtcNow;
}
}
private void ReceiveTokens(params ITokenHandler[] handlers)
{
Logger.Instance?.WriteLine();
Logger.Instance?.WriteLine("---------- Receive Tokens ----------");
try
{
#if ENABLE_ARRAY_POOL
using (var tokenStream = new TokenReceiveStream(_networkStream, _environment, _arrayPool))
#else
using (var tokenStream = new TokenReceiveStream(_networkStream, _environment))
#endif
{
foreach (var receivedToken in _reader.Read(tokenStream, _environment))
{
foreach (var handler in handlers)
{
if (handler != null && handler.CanHandle(receivedToken.Type))
{
handler.Handle(receivedToken);
}
}
}
}
}
finally
{
LastActive = DateTime.UtcNow;
}
}
public void Login()
{
//socket is established already
//login
SendPacket(
new LoginPacket(
_parameters.ClientHostName,
_parameters.Username,
_parameters.Password,
_parameters.ProcessId,
_parameters.ApplicationName,
_parameters.Server,
"us_english",
_parameters.Charset,
"ADO.NET",
_environment.PacketSize,
new ClientCapabilityToken(_parameters.EnableServerPacketSize),
_parameters.EncryptPassword));
var ackHandler = new LoginTokenHandler();
var envChangeTokenHandler = new EnvChangeTokenHandler(_environment, _parameters.Charset);
var messageHandler = new MessageTokenHandler(EventNotifier);
ReceiveTokens(
ackHandler,
envChangeTokenHandler,
messageHandler);
messageHandler.AssertNoErrors();
if (!ackHandler.ReceivedAck)
{
IsDoomed = true;
throw new InvalidOperationException("No login ack found");
}
if (ackHandler.LoginStatus == LoginAckToken.LoginStatus.TDS_LOG_NEGOTIATE)
{
NegotiatePassword(ackHandler.Message.MessageId, ackHandler.Parameters.Parameters, _parameters.Password);
}
else if (ackHandler.LoginStatus != LoginAckToken.LoginStatus.TDS_LOG_SUCCEED)
{
throw new AseException("Login failed.\n", 4002); //just in case the server doesn't respond with an appropriate EED token
}
ServerVersion = ackHandler.Token.ProgramVersion;
Created = DateTime.UtcNow;
SetState(InternalConnectionState.Ready);
}
private void NegotiatePassword(MessageToken.MsgId scheme, ParametersToken.Parameter[] parameters, string password)
{
try
{
switch (scheme)
{
case MessageToken.MsgId.TDS_MSG_SEC_ENCRYPT3:
DoEncrypt3Scheme(parameters, password);
break;
default:
throw new NotSupportedException("Server requested unsupported password encryption scheme");
}
}
catch (CryptographicException ex)
{
//todo: expand on exception cases
Logger.Instance?.WriteLine($"{nameof(CryptographicException)} - {ex}");
throw new AseException("Password encryption failed");
}
}
private void DoEncrypt3Scheme(ParametersToken.Parameter[] parameters, string password)
{
var encryptedPassword = Encryption.EncryptPassword3((int) parameters[0].Value, (byte[]) parameters[1].Value, (byte[]) parameters[2].Value, Encoding.ASCII.GetBytes(password));
SendPacket(new NormalPacket(Encryption.BuildEncrypt3Tokens(encryptedPassword)));
// 5. Expect an ack
var ackHandler = new LoginTokenHandler();
var envChangeTokenHandler = new EnvChangeTokenHandler(_environment, _parameters.Charset);
var messageHandler = new MessageTokenHandler(EventNotifier);
ReceiveTokens(
ackHandler,
envChangeTokenHandler,
messageHandler);
messageHandler.AssertNoErrors();
if (ackHandler.LoginStatus != LoginAckToken.LoginStatus.TDS_LOG_SUCCEED)
{
throw new AseException("Login failed.\n", 4002); //just in case the server doesn't respond with an appropriate EED token
}
}
public DateTime Created { get; private set; }
public DateTime LastActive { get; private set; }
public bool Ping()
{
try
{
AssertExecutionStart();
SendPacket(new NormalPacket(OptionCommandToken.CreateGet(OptionCommandToken.OptionType.TDS_OPT_STAT_TIME)));
var messageHandler = new MessageTokenHandler();
ReceiveTokens(messageHandler);
AssertExecutionCompletion();
messageHandler.AssertNoErrors();
return true;
}
catch (Exception ex)
{
Logger.Instance?.WriteLine($"Internal ping resulted in exception: {ex}");
IsDoomed = true;
return false;
}
}
public void ChangeDatabase(string databaseName)
{
if (string.IsNullOrWhiteSpace(databaseName) || string.Equals(databaseName, Database, StringComparison.OrdinalIgnoreCase))
{
return;
}
AssertExecutionStart();
//turns out, you can't issue an env change token to change the database, it responds saying it doesn't know how to process such a token
SendPacket(new NormalPacket(new LanguageToken
{
HasParameters = false,
CommandText = $"USE {databaseName}"
}));
var messageHandler = new MessageTokenHandler(EventNotifier);
var envChangeTokenHandler = new EnvChangeTokenHandler(_environment, _parameters.Charset);
ReceiveTokens(envChangeTokenHandler, messageHandler);
AssertExecutionCompletion();
messageHandler.AssertNoErrors();
}
public string Database => _environment.Database;
public string DataSource => $"{_parameters.Server},{_parameters.Port}";
public string ServerVersion { get; private set; }
private void InternalExecuteQueryAsync(AseCommand command, AseTransaction transaction, TaskCompletionSource<DbDataReader> readerSource, CommandBehavior behavior)
{
AssertExecutionStart();
#if ENABLE_SYSTEM_DATA_COMMON_EXTENSIONS
var dataReader = new AseDataReader(command, behavior, EventNotifier);
#else
var dataReader = new AseDataReader(behavior, EventNotifier);
#endif
try
{
SendPacket(new NormalPacket(BuildCommandTokens(command, behavior)));
var envChangeTokenHandler = new EnvChangeTokenHandler(_environment, _parameters.Charset);
var doneHandler = new DoneTokenHandler();
var dataReaderHandler = new StreamingDataReaderTokenHandler(readerSource, dataReader, EventNotifier);
var responseParameterTokenHandler = new ResponseParameterTokenHandler(command.AseParameters);
Logger.Instance?.WriteLine();
Logger.Instance?.WriteLine("---------- Receive Tokens ----------");
try
{
#if ENABLE_ARRAY_POOL
using (var tokenStream = new TokenReceiveStream(_networkStream, _environment, _arrayPool))
#else
using (var tokenStream = new TokenReceiveStream(_networkStream, _environment))
#endif
{
foreach (var receivedToken in _reader.Read(tokenStream, _environment))
{
if (envChangeTokenHandler.CanHandle(receivedToken.Type))
{
envChangeTokenHandler.Handle(receivedToken);
}
if (doneHandler.CanHandle(receivedToken.Type))
{
doneHandler.Handle(receivedToken);
}
if (dataReaderHandler.CanHandle(receivedToken.Type))
{
dataReaderHandler.Handle(receivedToken);
}
if (responseParameterTokenHandler.CanHandle(receivedToken.Type))
{
responseParameterTokenHandler.Handle(receivedToken);
}
}
}
}
finally
{
LastActive = DateTime.UtcNow;
}
// This tells the data reader to stop waiting for more results.
dataReader.CompleteAdding();
AssertExecutionCompletion(doneHandler);
if (transaction != null && doneHandler.TransactionState == TranState.TDS_TRAN_ABORT)
{
transaction.MarkAborted();
}
dataReaderHandler.AssertNoErrors();
if (doneHandler.Canceled)
{
readerSource.TrySetCanceled(); // If we have already begun returning data, then this will get lost.
}
else
{
readerSource.TrySetResult(dataReader); // Catchall - covers cases where no data is returned by the server.
}
}
catch (Exception ex)
{
// If we have already begun returning data, then this will get lost.
if (!readerSource.TrySetException(ex)) throw;
}
}
private void InternalExecuteNonQueryAsync(AseCommand command, AseTransaction transaction, TaskCompletionSource<int> rowsAffectedSource)
{
AssertExecutionStart();
try
{
SendPacket(new NormalPacket(BuildCommandTokens(command, CommandBehavior.Default)));
var envChangeTokenHandler = new EnvChangeTokenHandler(_environment, _parameters.Charset);
var messageHandler = new MessageTokenHandler(EventNotifier);
var responseParameterTokenHandler = new ResponseParameterTokenHandler(command.AseParameters);
var doneHandler = new DoneTokenHandler();
ReceiveTokens(
envChangeTokenHandler,
messageHandler,
responseParameterTokenHandler,
doneHandler);
AssertExecutionCompletion(doneHandler);
if (transaction != null && doneHandler.TransactionState == TranState.TDS_TRAN_ABORT)
{
transaction.MarkAborted();
}
messageHandler.AssertNoErrors();
if (doneHandler.Canceled)
{
rowsAffectedSource.TrySetCanceled();
}
else
{
rowsAffectedSource.TrySetResult(doneHandler.RowsAffected);
}
}
catch (Exception ex)
{
if (!rowsAffectedSource.TrySetException(ex)) throw;
}
}
public int ExecuteNonQuery(AseCommand command, AseTransaction transaction)
{
try
{
var execTask = ExecuteNonQueryTaskRunnable(command, transaction);
execTask.Wait();
return execTask.Result;
}
catch (AggregateException ae)
{
ExceptionDispatchInfo.Capture(ae.InnerException ?? ae).Throw();
throw;
}
}
public Task<int> ExecuteNonQueryTaskRunnable(AseCommand command, AseTransaction transaction)
{
var rowsAffectedSource = new TaskCompletionSource<int>();
InternalExecuteNonQueryAsync(command, transaction, rowsAffectedSource);
return rowsAffectedSource.Task;
}
public DbDataReader ExecuteReader(CommandBehavior behavior, AseCommand command, AseTransaction transaction)
{
try
{
var readerTask = ExecuteReaderTaskRunnable(behavior, command, transaction);
readerTask.Wait();
return readerTask.Result;
}
catch (AggregateException ae)
{
ExceptionDispatchInfo.Capture(ae.InnerException ?? ae).Throw();
throw;
}
}
public Task<DbDataReader> ExecuteReaderTaskRunnable(CommandBehavior behavior, AseCommand command, AseTransaction transaction)
{
var readerSource = new TaskCompletionSource<DbDataReader>();
InternalExecuteQueryAsync(command, transaction, readerSource, behavior);
return readerSource.Task;
}
public object ExecuteScalar(AseCommand command, AseTransaction transaction)
{
using (var reader = (IDataReader)ExecuteReader(CommandBehavior.SingleRow, command, transaction))
{
if (reader.Read())
{
return reader[0];
}
}
return null;
}
public void Cancel()
{
if (TrySetState(InternalConnectionState.Canceled, s => s == InternalConnectionState.Active))
{
Logger.Instance?.WriteLine("Canceling...");
SendPacket(new AttentionPacket());
}
else
{
Logger.Instance?.WriteLine("Did not issue cancel packet as connection is not in the Active state");
}
}
private void AssertExecutionStart()
{
if (!TrySetState(InternalConnectionState.Active, s => s == InternalConnectionState.Ready))
{
IsDoomed = true;
throw new AseException("Connection entered broken state");
}
}
private void AssertExecutionCompletion(DoneTokenHandler doneHandler = null)
{
if (doneHandler?.Canceled == true)
{
TrySetState(InternalConnectionState.Ready, s => s == InternalConnectionState.Canceled);
}
if (_state == InternalConnectionState.Canceled)
{
//we're in a broken state
IsDoomed = true;
throw new AseException("Connection entered broken state");
}
TrySetState(InternalConnectionState.Ready, s => s == InternalConnectionState.Active);
}
public void SetTextSize(int textSize)
{
//todo: may need to remove this, user scripts could change the textsize value
if (_environment.TextSize == textSize)
{
return;
}
SendPacket(new NormalPacket(OptionCommandToken.CreateSetTextSize(textSize)));
var envChangeTokenHandler = new EnvChangeTokenHandler(_environment, _parameters.Charset);
var messageHandler = new MessageTokenHandler(EventNotifier);
var dataReaderHandler = new DataReaderTokenHandler();
var doneHandler = new DoneTokenHandler();
ReceiveTokens(
envChangeTokenHandler,
messageHandler,
dataReaderHandler,
doneHandler);
messageHandler.AssertNoErrors();
_environment.TextSize = textSize;
}
public void SetAnsiNull(bool enabled)
{
SendPacket(new NormalPacket(OptionCommandToken.CreateSetAnsiNull(enabled)));
var envChangeTokenHandler = new EnvChangeTokenHandler(_environment, _parameters.Charset);
var messageHandler = new MessageTokenHandler(EventNotifier);
var doneHandler = new DoneTokenHandler();
ReceiveTokens(
envChangeTokenHandler,
messageHandler,
doneHandler);
messageHandler.AssertNoErrors();
}
public bool NamedParameters
{
get;
set;
}
private bool _isDoomed;
public bool IsDoomed
{
get => _isDoomed;
set
{
if (value)
{
SetState(InternalConnectionState.Broken);
}
_isDoomed = _isDoomed || value;
}
}
public bool IsDisposed { get; private set; }
private IEnumerable<IToken> BuildCommandTokens(AseCommand command, CommandBehavior behavior)
{
if (command.CommandType == CommandType.TableDirect)
{
throw new NotImplementedException($"{command.CommandType} is not implemented");
}
yield return command.CommandType == CommandType.StoredProcedure
? BuildRpcToken(command, behavior)
: BuildLanguageToken(command, behavior);
foreach (var token in BuildParameterTokens(command))
{
yield return token;
}
}
private IToken BuildLanguageToken(AseCommand command, CommandBehavior behavior)
{
return new LanguageToken
{
CommandText = MakeCommand(command.CommandText, behavior, command.NamedParameters),
HasParameters = command.HasSendableParameters
};
}
private IToken BuildRpcToken(AseCommand command, CommandBehavior behavior)
{
return new DbRpcToken
{
ProcedureName = MakeCommand(command.CommandText, behavior),
HasParameters = command.HasSendableParameters
};
}
private string MakeCommand(string commandText, CommandBehavior behavior, bool namedParameters = true)
{
var result = commandText;
if (!namedParameters)
{
try
{
result = result.ToNamedParameters();
}
catch (ArgumentException)
{
throw new AseException("Incorrect syntax. Possible mismatched quotes on string literal, or identifier delimiter.");
}
}
if ((behavior & CommandBehavior.SchemaOnly) == CommandBehavior.SchemaOnly)
{
result =
$@"SET FMTONLY ON
{result}
SET FMTONLY OFF";
}
return result;
}
private IToken[] BuildParameterTokens(AseCommand command)
{
var formatItems = new List<FormatItem>();
var parameterItems = new List<ParametersToken.Parameter>();
foreach (var parameter in command.Parameters.SendableParameters)
{
var parameterName = parameter.ParameterName ?? command.Parameters.IndexOf(parameter).ToString();
if (!(command.FormatItem != null && command.FormatItem.ParameterName == parameterName && command.FormatItem.AseDbType == parameter.AseDbType))
{
command.FormatItem = FormatItem.CreateForParameter(parameter, _environment, command.CommandType);
}
formatItems.Add(command.FormatItem);
parameterItems.Add(new ParametersToken.Parameter
{
Format = command.FormatItem,
Value = parameter.SendableValue
});
}
if (formatItems.Count == 0)
{
return new IToken[0];
}
return new IToken[]
{
new ParameterFormat2Token
{
Formats = formatItems.ToArray()
},
new ParametersToken
{
Parameters = parameterItems.ToArray()
}
};
}
public void Dispose()
{
if (IsDisposed)
{
return;
}
IsDisposed = true;
_networkStream.Dispose();
}
public static readonly IDictionary EmptyStatistics = new ReadOnlyDictionary<string, long>(new Dictionary<string, long>());
public bool StatisticsEnabled
{
get => _statisticsEnabled;
set => _statisticsEnabled = value;
}
public IDictionary RetrieveStatistics()
{
if (!_statisticsEnabled)
{
return EmptyStatistics;
}
//todo: implement
/*"BuffersReceived"
"BuffersSent"
"BytesReceived"
"BytesSent"
"ConnectionTime"
"CursorOpens"
"ExecutionTime"
"IduCount"
"IduRows"
"NetworkServerTime"
"PreparedExecs"
"Prepares"
"SelectCount"
"SelectRows"
"ServerRoundtrips"
"SumResultSets"
"Transactions"
"UnpreparedExecs"*/
return EmptyStatistics;
}
public IInfoMessageEventNotifier EventNotifier { get; set; }
}
}
| 35.252646 | 186 | 0.548948 | [
"Apache-2.0"
] | Kaltalen/AdoNetCore.AseClient | src/AdoNetCore.AseClient/Internal/InternalConnection.cs | 26,651 | 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 elasticache-2015-02-02.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Xml.Serialization;
using Amazon.ElastiCache.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
namespace Amazon.ElastiCache.Model.Internal.MarshallTransformations
{
/// <summary>
/// DescribeCacheSecurityGroups Request Marshaller
/// </summary>
public class DescribeCacheSecurityGroupsRequestMarshaller : IMarshaller<IRequest, DescribeCacheSecurityGroupsRequest> , IMarshaller<IRequest,AmazonWebServiceRequest>
{
/// <summary>
/// Marshaller the request object to the HTTP request.
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public IRequest Marshall(AmazonWebServiceRequest input)
{
return this.Marshall((DescribeCacheSecurityGroupsRequest)input);
}
/// <summary>
/// Marshaller the request object to the HTTP request.
/// </summary>
/// <param name="publicRequest"></param>
/// <returns></returns>
public IRequest Marshall(DescribeCacheSecurityGroupsRequest publicRequest)
{
IRequest request = new DefaultRequest(publicRequest, "Amazon.ElastiCache");
request.Parameters.Add("Action", "DescribeCacheSecurityGroups");
request.Parameters.Add("Version", "2015-02-02");
if(publicRequest != null)
{
if(publicRequest.IsSetCacheSecurityGroupName())
{
request.Parameters.Add("CacheSecurityGroupName", StringUtils.FromString(publicRequest.CacheSecurityGroupName));
}
if(publicRequest.IsSetMarker())
{
request.Parameters.Add("Marker", StringUtils.FromString(publicRequest.Marker));
}
if(publicRequest.IsSetMaxRecords())
{
request.Parameters.Add("MaxRecords", StringUtils.FromInt(publicRequest.MaxRecords));
}
}
return request;
}
private static DescribeCacheSecurityGroupsRequestMarshaller _instance = new DescribeCacheSecurityGroupsRequestMarshaller();
internal static DescribeCacheSecurityGroupsRequestMarshaller GetInstance()
{
return _instance;
}
/// <summary>
/// Gets the singleton.
/// </summary>
public static DescribeCacheSecurityGroupsRequestMarshaller Instance
{
get
{
return _instance;
}
}
}
} | 37.505263 | 170 | 0.622509 | [
"Apache-2.0"
] | philasmar/aws-sdk-net | sdk/src/Services/ElastiCache/Generated/Model/Internal/MarshallTransformations/DescribeCacheSecurityGroupsRequestMarshaller.cs | 3,563 | 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 System.Linq;
using Xunit;
using static NuGet.Frameworks.FrameworkConstants;
using PackagesLockFileBuilder = NuGet.ProjectModel.Test.Builders.PackagesLockFileBuilder;
namespace NuGet.ProjectModel.Test.ProjectLockFile
{
public class LockFileUtilitiesTests
{
[Fact]
public void IsLockFileStillValid_DifferentVersions_AreNotEqual()
{
var x = new PackagesLockFileBuilder().Build();
var y = new PackagesLockFileBuilder()
.WithVersion(2)
.Build();
var actual = PackagesLockFileUtilities.IsLockFileStillValid(x, y);
Assert.False(actual.IsValid);
actual = PackagesLockFileUtilities.IsLockFileStillValid(y, x);
Assert.False(actual.IsValid);
}
[Fact]
public void IsLockFileStillValid_DifferentTargetCounts_AreNotEqual()
{
var x = new PackagesLockFileBuilder()
.WithTarget(target => target.WithFramework(CommonFrameworks.NetStandard20))
.WithTarget(target => target.WithFramework(CommonFrameworks.NetCoreApp22))
.Build();
var y = new PackagesLockFileBuilder()
.WithTarget(target => target.WithFramework(CommonFrameworks.NetStandard20))
.Build();
var actual = PackagesLockFileUtilities.IsLockFileStillValid(x, y);
Assert.False(actual.IsValid);
actual = PackagesLockFileUtilities.IsLockFileStillValid(y, x);
Assert.False(actual.IsValid);
}
[Fact]
public void IsLockFileStillValid_DifferentTargets_AreNotEqual()
{
var x = new PackagesLockFileBuilder()
.WithTarget(target => target.WithFramework(CommonFrameworks.NetStandard20))
.Build();
var y = new PackagesLockFileBuilder()
.WithTarget(target => target.WithFramework(CommonFrameworks.NetCoreApp22))
.Build();
var actual = PackagesLockFileUtilities.IsLockFileStillValid(x, y);
Assert.False(actual.IsValid);
actual = PackagesLockFileUtilities.IsLockFileStillValid(y, x);
Assert.False(actual.IsValid);
}
[Fact]
public void IsLockFileStillValid_DifferentDependencyCounts_AreNotEqual()
{
var x = new PackagesLockFileBuilder()
.WithTarget(target => target
.WithFramework(CommonFrameworks.NetStandard20)
.WithDependency(dep => dep.WithId("PackageA")))
.Build();
var y = new PackagesLockFileBuilder()
.WithTarget(target => target
.WithFramework(CommonFrameworks.NetStandard20)
.WithDependency(dep => dep.WithId("PackageA"))
.WithDependency(dep => dep.WithId("PackageB")))
.Build();
var actual = PackagesLockFileUtilities.IsLockFileStillValid(x, y);
Assert.False(actual.IsValid);
actual = PackagesLockFileUtilities.IsLockFileStillValid(y, x);
Assert.False(actual.IsValid);
}
[Fact]
public void IsLockFileStillValid_DifferentDependency_AreNotEqual()
{
var x = new PackagesLockFileBuilder()
.WithTarget(target => target
.WithFramework(CommonFrameworks.NetStandard20)
.WithDependency(dep => dep.WithId("PackageA")))
.Build();
var y = new PackagesLockFileBuilder()
.WithTarget(target => target
.WithFramework(CommonFrameworks.NetStandard20)
.WithDependency(dep => dep.WithId("PackageB")))
.Build();
var actual = PackagesLockFileUtilities.IsLockFileStillValid(x, y);
Assert.False(actual.IsValid);
actual = PackagesLockFileUtilities.IsLockFileStillValid(y, x);
Assert.False(actual.IsValid);
}
[Fact]
public void IsLockFileStillValid_MatchesDependencies_AreEqual()
{
var x = new PackagesLockFileBuilder()
.WithTarget(target => target
.WithFramework(CommonFrameworks.NetStandard20)
.WithDependency(dep => dep
.WithId("PackageA")
.WithContentHash("ABC"))
.WithDependency(dep => dep
.WithId("PackageB")
.WithContentHash("123")))
.Build();
var y = new PackagesLockFileBuilder()
.WithTarget(target => target
.WithFramework(CommonFrameworks.NetStandard20)
.WithDependency(dep => dep
.WithId("PackageA")
.WithContentHash("XYZ"))
.WithDependency(dep => dep
.WithId("PackageB")
.WithContentHash("890")))
.Build();
var actual = PackagesLockFileUtilities.IsLockFileStillValid(x, y);
Assert.True(actual.IsValid);
Assert.NotNull(actual.MatchedDependencies);
Assert.Equal(2, actual.MatchedDependencies.Count);
var depKvp = actual.MatchedDependencies.Single(d => d.Key.Id == "PackageA");
Assert.Equal("ABC", depKvp.Key.ContentHash);
Assert.Equal("XYZ", depKvp.Value.ContentHash);
depKvp = actual.MatchedDependencies.Single(d => d.Key.Id == "PackageB");
Assert.Equal("123", depKvp.Key.ContentHash);
Assert.Equal("890", depKvp.Value.ContentHash);
actual = PackagesLockFileUtilities.IsLockFileStillValid(y, x);
Assert.True(actual.IsValid);
Assert.NotNull(actual.MatchedDependencies);
Assert.Equal(2, actual.MatchedDependencies.Count);
depKvp = actual.MatchedDependencies.Single(d => d.Key.Id == "PackageA");
Assert.Equal("ABC", depKvp.Value.ContentHash);
Assert.Equal("XYZ", depKvp.Key.ContentHash);
depKvp = actual.MatchedDependencies.Single(d => d.Key.Id == "PackageB");
Assert.Equal("123", depKvp.Value.ContentHash);
Assert.Equal("890", depKvp.Key.ContentHash);
}
}
}
| 42.558442 | 111 | 0.588038 | [
"Apache-2.0"
] | JetBrains/NuGet.Client | test/NuGet.Core.Tests/NuGet.ProjectModel.Test/ProjectLockFile/LockFileUtilitiesTests.cs | 6,554 | C# |
/*
*
* (c) Copyright Ascensio System Limited 2010-2021
*
* 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;
namespace ASC.Mail.Data.Contracts
{
public class CrmContactData
{
public int Id { get; set; }
public EntityTypes Type { get; set; }
public string EntityTypeName
{
get
{
switch (Type)
{
case EntityTypes.Contact:
return CrmEntityTypeNames.CONTACT;
case EntityTypes.Case:
return CrmEntityTypeNames.CASE;
case EntityTypes.Opportunity:
return CrmEntityTypeNames.OPPORTUNITY;
default:
throw new ArgumentException(string.Format("Invalid CrmEntityType: {0}", Type));
}
}
}
public enum EntityTypes
{
Contact = 1,
Case = 2,
Opportunity = 3
}
public static class CrmEntityTypeNames
{
public const string CONTACT = "contact";
public const string CASE = "case";
public const string OPPORTUNITY = "opportunity";
}
}
} | 29.949153 | 103 | 0.571024 | [
"ECL-2.0",
"Apache-2.0",
"MIT"
] | ONLYOFFICE/CommunityServer | module/ASC.Mail/ASC.Mail/Data/Contracts/CrmContactData.cs | 1,767 | C# |
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
using Microsoft.SqlTools.Hosting.Protocol.Contracts;
namespace Microsoft.SqlTools.ServiceLayer.Admin.Contracts
{
public class CreateLoginParams
{
public string OwnerUri { get; set; }
public LoginInfo DatabaseInfo { get; set; }
}
public class CreateLoginResponse
{
public bool Result { get; set; }
public int TaskId { get; set; }
}
public class CreateLoginRequest
{
public static readonly
RequestType<CreateLoginParams, CreateLoginResponse> Type =
RequestType<CreateLoginParams, CreateLoginResponse>.Create("admin/createlogin");
}
}
| 25.806452 | 101 | 0.68 | [
"MIT"
] | Bhaskers-Blu-Org2/sqltoolsservice | src/Microsoft.SqlTools.ServiceLayer/Admin/Contracts/CreateLoginRequest.cs | 802 | C# |
/*
* Copyright 2010-2014 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 pinpoint-email-2018-07-26.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using System.Xml.Serialization;
using Amazon.PinpointEmail.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.PinpointEmail.Model.Internal.MarshallTransformations
{
/// <summary>
/// Response Unmarshaller for PutDedicatedIpInPool operation
/// </summary>
public class PutDedicatedIpInPoolResponseUnmarshaller : JsonResponseUnmarshaller
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context)
{
PutDedicatedIpInPoolResponse response = new PutDedicatedIpInPoolResponse();
return response;
}
/// <summary>
/// Unmarshaller error response to exception.
/// </summary>
/// <param name="context"></param>
/// <param name="innerException"></param>
/// <param name="statusCode"></param>
/// <returns></returns>
public override AmazonServiceException UnmarshallException(JsonUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode)
{
ErrorResponse errorResponse = JsonErrorResponseUnmarshaller.GetInstance().Unmarshall(context);
if (errorResponse.Code != null && errorResponse.Code.Equals("BadRequestException"))
{
return new BadRequestException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("NotFoundException"))
{
return new NotFoundException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("TooManyRequestsException"))
{
return new TooManyRequestsException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
return new AmazonPinpointEmailException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
private static PutDedicatedIpInPoolResponseUnmarshaller _instance = new PutDedicatedIpInPoolResponseUnmarshaller();
internal static PutDedicatedIpInPoolResponseUnmarshaller GetInstance()
{
return _instance;
}
/// <summary>
/// Gets the singleton.
/// </summary>
public static PutDedicatedIpInPoolResponseUnmarshaller Instance
{
get
{
return _instance;
}
}
}
} | 39.591837 | 168 | 0.682732 | [
"Apache-2.0"
] | Bio2hazard/aws-sdk-net | sdk/src/Services/PinpointEmail/Generated/Model/Internal/MarshallTransformations/PutDedicatedIpInPoolResponseUnmarshaller.cs | 3,880 | C# |
//-----------------------------------------------------------------------
// <copyright file="JetGetThreadStats2Tests.cs" company="Microsoft Corporation">
// Copyright (c) Microsoft Corporation.
// </copyright>
//-----------------------------------------------------------------------
namespace InteropApiTests
{
using System;
using System.Diagnostics;
using System.IO;
using Microsoft.Isam.Esent.Interop;
using Microsoft.Isam.Esent.Interop.Windows10;
using Microsoft.VisualStudio.TestTools.UnitTesting;
/// <summary>
/// Tests for JetGetThreadStats
/// </summary>
public partial class JetGetThreadStatsTests
{
/// <summary>
/// Call JetGetThreadStats on JET_THREADSTATS2.
/// </summary>
[TestMethod]
[Priority(2)]
[Description("Call JetGetThreadStats on JET_THREADSTATS2")]
public void JetGetThreadStats2()
{
Api.JetBeginTransaction(this.sesid);
Api.JetPrepareUpdate(this.sesid, this.tableid, JET_prep.Insert);
byte[] data = new byte[65536];
Api.JetSetColumn(this.sesid, this.tableid, this.columnid, data, data.Length, SetColumnGrbit.None, null);
Api.JetUpdate(this.sesid, this.tableid);
Api.JetCommitTransaction(this.sesid, CommitTransactionGrbit.LazyFlush);
this.ResetCache();
JET_THREADSTATS2 threadstatsBefore;
Windows10Api.JetGetThreadStats(out threadstatsBefore);
Api.JetBeginTransaction(this.sesid);
Api.JetMove(this.sesid, this.tableid, JET_Move.First, MoveGrbit.None);
byte[] actual = Api.RetrieveColumn(this.sesid, this.tableid, this.columnid);
Api.JetCommitTransaction(this.sesid, CommitTransactionGrbit.LazyFlush);
Api.JetBeginTransaction(this.sesid);
Api.JetPrepareUpdate(this.sesid, this.tableid, JET_prep.Insert);
data = new byte[65536];
Api.JetSetColumn(this.sesid, this.tableid, this.columnid, data, data.Length, SetColumnGrbit.None, null);
Api.JetUpdate(this.sesid, this.tableid);
Api.JetMove(this.sesid, this.tableid, JET_Move.Last, MoveGrbit.None);
Api.JetPrepareUpdate(this.sesid, this.tableid, JET_prep.Replace);
Api.JetSetColumn(this.sesid, this.tableid, this.columnid, data, data.Length, SetColumnGrbit.None, null);
Api.JetUpdate(this.sesid, this.tableid);
Api.JetCommitTransaction(this.sesid, CommitTransactionGrbit.LazyFlush);
JET_THREADSTATS2 threadstatsAfter;
Windows10Api.JetGetThreadStats(out threadstatsAfter);
JET_THREADSTATS2 threadstats = threadstatsAfter - threadstatsBefore;
Assert.AreNotEqual(0, threadstats.cPageReferenced);
Assert.AreNotEqual(0, threadstats.cPageRead);
////Assert.AreNotEqual(0, threadstats.cPagePreread);
Assert.AreNotEqual(0, threadstats.cPageDirtied);
Assert.AreNotEqual(0, threadstats.cPageRedirtied);
Assert.AreNotEqual(0, threadstats.cLogRecord);
Assert.AreNotEqual(0, threadstats.cbLogRecord);
if (EsentVersion.SupportsWindows10Features)
{
Assert.AreNotEqual(0, threadstats.cusecPageCacheMiss);
Assert.AreNotEqual(0, threadstats.cPageCacheMiss);
}
}
}
} | 45.907895 | 117 | 0.619662 | [
"MIT"
] | Bhaskers-Blu-Org2/ManagedEsent | EsentInteropTests/JetGetThreadStats2Tests.cs | 3,489 | C# |
using UnityEngine;
public class GroundTrigger : MonoBehaviour
{
private void Start()
{
}
private void Update()
{
}
private void OnTriggerEnter(Collider other)
{
if (other.tag == "Ground")
{
//Movement.inAir = false;
}
}
private void OnTriggerExit(Collider other)
{
if (other.tag == "Ground")
{
// Movement.inAir = true;
}
}
} | 16.107143 | 47 | 0.505543 | [
"MIT"
] | Chillu1/GottaGoFust | Assets/Scripts/MapBased/GroundTrigger.cs | 453 | C# |
using Microsoft.AspNetCore.Components;
using PeterPedia.Shared;
using PeterPedia.Client.Services;
namespace PeterPedia.Client.Pages.Books;
public partial class Reading : ComponentBase
{
[Inject]
BookService BookService { get; set; } = null!;
private List<Book> BookList = new();
protected override async Task OnInitializedAsync()
{
await BookService.FetchData();
BookList = BookService.Books.Where(b => b.State == BookState.Reading).OrderBy(b => b.Title).ToList();
}
} | 25.7 | 109 | 0.70428 | [
"MIT"
] | peter-andersson/peterpedia | src/Client/Pages/Books/Reading.razor.cs | 516 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Aspen.DailyUpdates.DBModel.Models
{
public class TopField : Field
{
public ICollection<Field> SubFields { get; set; }
public new DateTime? TurnOver {
get
{
return null;
}
}
}
}
| 18.761905 | 57 | 0.591371 | [
"MIT"
] | thundernet8/DailyUpdates | DBModel/Models/TopField.cs | 396 | C# |
// dnlib: See LICENSE.txt for more info
using dnlib.DotNet.Emit;
using System;
using System.Collections.Generic;
namespace dnlib.DotNet.Writer
{
/// <summary>
/// Calculates max stack usage by using a simple pass over all instructions. This value
/// can be placed in the fat method header's MaxStack field.
/// </summary>
public struct MaxStackCalculator
{
readonly IList<Instruction> instructions;
readonly IList<ExceptionHandler> exceptionHandlers;
readonly Dictionary<Instruction, int> stackHeights;
int errors;
/// <summary>
/// Gets max stack value
/// </summary>
/// <param name="instructions">All instructions</param>
/// <param name="exceptionHandlers">All exception handlers</param>
/// <returns>Max stack value</returns>
public static uint GetMaxStack(IList<Instruction> instructions, IList<ExceptionHandler> exceptionHandlers)
{
uint maxStack;
new MaxStackCalculator(instructions, exceptionHandlers).Calculate(out maxStack);
return maxStack;
}
/// <summary>
/// Gets max stack value
/// </summary>
/// <param name="instructions">All instructions</param>
/// <param name="exceptionHandlers">All exception handlers</param>
/// <param name="maxStack">Updated with max stack value</param>
/// <returns><c>true</c> if no errors were detected, <c>false</c> otherwise</returns>
public static bool GetMaxStack(IList<Instruction> instructions, IList<ExceptionHandler> exceptionHandlers, out uint maxStack)
{
return new MaxStackCalculator(instructions, exceptionHandlers).Calculate(out maxStack);
}
MaxStackCalculator(IList<Instruction> instructions, IList<ExceptionHandler> exceptionHandlers)
{
this.instructions = instructions;
this.exceptionHandlers = exceptionHandlers;
this.stackHeights = new Dictionary<Instruction, int>();
this.errors = 0;
}
bool Calculate(out uint maxStack)
{
foreach (var eh in exceptionHandlers)
{
if (eh == null)
continue;
if (eh.TryStart != null)
stackHeights[eh.TryStart] = 0;
if (eh.FilterStart != null)
stackHeights[eh.FilterStart] = 1;
if (eh.HandlerStart != null)
{
bool pushed = eh.HandlerType == ExceptionHandlerType.Catch || eh.HandlerType == ExceptionHandlerType.Filter;
stackHeights[eh.HandlerStart] = pushed ? 1 : 0;
}
}
int stack = 0;
bool resetStack = false;
foreach (var instr in instructions)
{
if (instr == null)
continue;
if (resetStack)
{
stackHeights.TryGetValue(instr, out stack);
resetStack = false;
}
stack = WriteStack(instr, stack);
if (instr.OpCode.Code == Code.Jmp)
{
if (stack != 0)
errors++;
}
else
{
int pushes, pops;
instr.CalculateStackUsage(out pushes, out pops);
if (pops == -1)
stack = 0;
else
{
stack -= pops;
if (stack < 0)
{
errors++;
stack = 0;
}
stack += pushes;
}
}
if (stack < 0)
{
errors++;
stack = 0;
}
switch (instr.OpCode.FlowControl)
{
case FlowControl.Branch:
WriteStack(instr.Operand as Instruction, stack);
resetStack = true;
break;
case FlowControl.Call:
if (instr.OpCode.Code == Code.Jmp)
resetStack = true;
break;
case FlowControl.Cond_Branch:
if (instr.OpCode.Code == Code.Switch)
{
var targets = instr.Operand as IList<Instruction>;
if (targets != null)
{
foreach (var target in targets)
WriteStack(target, stack);
}
}
else
WriteStack(instr.Operand as Instruction, stack);
break;
case FlowControl.Return:
case FlowControl.Throw:
resetStack = true;
break;
}
}
stack = 0;
foreach (var v in stackHeights.Values)
stack = Math.Max(stack, v);
maxStack = (uint)stack;
return errors == 0;
}
int WriteStack(Instruction instr, int stack)
{
if (instr == null)
{
errors++;
return stack;
}
int stack2;
if (stackHeights.TryGetValue(instr, out stack2))
{
if (stack != stack2)
errors++;
return stack2;
}
stackHeights[instr] = stack;
return stack;
}
}
}
| 34.649123 | 133 | 0.454177 | [
"MIT"
] | Owen0225/ConfuserEx-Plus | dnlib/src/DotNet/Writer/MaxStackCalculator.cs | 5,925 | 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("_07.Primes_in_Given_Range")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("_07.Primes_in_Given_Range")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[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("edba59ef-55f0-4bc4-ad60-fc2a8466455b")]
// 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")]
| 38.459459 | 84 | 0.748419 | [
"MIT"
] | spzvtbg/02-Tech-modul | Fundamental task solutions/08.Methods. Debugging and Troubleshooting Code - Exercises/07. Primes in Given Range/Properties/AssemblyInfo.cs | 1,426 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using SeniorBlockchain.Consensus;
using SeniorBlockchain.Networks;
using NBitcoin;
namespace SeniorBlockchain.Networks.City.Networks.Consensus
{
public class CityPosConsensusOptions : PosConsensusOptions
{
/// <summary>Coinstake minimal confirmations softfork activation height for mainnet.</summary>
public const int CityCoinstakeMinConfirmationActivationHeightMainnet = 500000;
/// <summary>Coinstake minimal confirmations softfork activation height for testnet.</summary>
public const int CityCoinstakeMinConfirmationActivationHeightTestnet = 15000;
public override int GetStakeMinConfirmations(int height, Network network)
{
if (network.Name.ToLowerInvariant().Contains("test"))
{
return height < CityCoinstakeMinConfirmationActivationHeightTestnet ? 10 : 20;
}
// The coinstake confirmation minimum should be 50 until activation at height 500K (~347 days).
return height < CityCoinstakeMinConfirmationActivationHeightMainnet ? 50 : 500;
}
}
} | 40.068966 | 107 | 0.726334 | [
"MIT"
] | seniorblockchain/blockchain | src/Networks/SeniorBlockchain.Networks.City/Networks/Consensus/CityPosConsensusOptions.cs | 1,162 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TeleSharp.TL;
namespace TeleSharp.TL.Photos
{
[TLObject(-1916114267)]
public class TLPhotos : TLAbsPhotos
{
public override int Constructor
{
get
{
return -1916114267;
}
}
public TLVector<TLAbsPhoto> Photos { get; set; }
public TLVector<TLAbsUser> Users { get; set; }
public void ComputeFlags()
{
}
public override void DeserializeBody(BinaryReader br)
{
this.Photos = (TLVector<TLAbsPhoto>)ObjectUtils.DeserializeVector<TLAbsPhoto>(br);
this.Users = (TLVector<TLAbsUser>)ObjectUtils.DeserializeVector<TLAbsUser>(br);
}
public override void SerializeBody(BinaryWriter bw)
{
bw.Write(this.Constructor);
ObjectUtils.SerializeObject(this.Photos, bw);
ObjectUtils.SerializeObject(this.Users, bw);
}
}
}
| 23.608696 | 94 | 0.606814 | [
"MIT"
] | slctr/Men.Telegram.ClientApi | Men.Telegram.ClientApi/TL/TL/Photos/TLPhotos.cs | 1,086 | 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 ecs-2014-11-13.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Xml.Serialization;
using Amazon.ECS.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.ECS.Model.Internal.MarshallTransformations
{
/// <summary>
/// HostEntry Marshaller
/// </summary>
public class HostEntryMarshaller : IRequestMarshaller<HostEntry, JsonMarshallerContext>
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="requestObject"></param>
/// <param name="context"></param>
/// <returns></returns>
public void Marshall(HostEntry requestObject, JsonMarshallerContext context)
{
if(requestObject.IsSetHostname())
{
context.Writer.WritePropertyName("hostname");
context.Writer.Write(requestObject.Hostname);
}
if(requestObject.IsSetIpAddress())
{
context.Writer.WritePropertyName("ipAddress");
context.Writer.Write(requestObject.IpAddress);
}
}
/// <summary>
/// Singleton Marshaller.
/// </summary>
public readonly static HostEntryMarshaller Instance = new HostEntryMarshaller();
}
} | 33.147059 | 102 | 0.643744 | [
"Apache-2.0"
] | philasmar/aws-sdk-net | sdk/src/Services/ECS/Generated/Model/Internal/MarshallTransformations/HostEntryMarshaller.cs | 2,254 | C# |
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Data.SqlClient;
using System.Linq;
using System.Threading.Tasks;
namespace FishTechWebManager._infra
{
public class MSSQL : IDB
{
private SqlConnection _connection;
private IConfiguration _configuration;
public MSSQL(IConfiguration configuration)
{
_configuration = configuration;
}
public void Dispose()
{
_connection.Close();
_connection.Dispose();
}
public DbConnection GetConnection()
{
return _connection = new SqlConnection(_configuration.GetConnectionString("SQLDB"));
}
}
}
| 23.151515 | 96 | 0.651832 | [
"MIT"
] | andrewBezerra/FishTech | FishTechWebManager/_infra/MSSQL.cs | 766 | C# |
#if UNITY_EDITOR
namespace Unity.Views
{
using System;
using System.Windows.Forms.Design;
using System.Windows.Forms;
using UnityEngine;
using UnityEditor;
public class ControlInspector : EditorWindow
{
private static ControlInspector _self;
public static ControlInspector Self
{
get
{
if (_self == null)
{
_self = (ControlInspector)EditorMenu.ShowInspector();
}
return _self;
}
}
private IObjectDesigner designer;
private float repaintWait;
private Vector2 scrollPosition;
internal object DesignerObject;
void Awake()
{
var iDisposable = DesignerObject as IDisposable;
if (iDisposable != null)
iDisposable.Dispose();
DesignerObject = null;
}
void Update()
{
if (repaintWait < 1f)
repaintWait += Time.deltaTime;
else
{
Repaint();
repaintWait = 0;
}
}
void OnGUI()
{
if (DesignerObject == null) return;
var control = DesignerObject as Control;
if (control != null && (control.Disposing || control.IsDisposed) || !UnityEngine.Application.isPlaying)
{
DesignerObject = null;
return;
}
scrollPosition = GUILayout.BeginScrollView(scrollPosition);
if (designer == null || designer.Value != DesignerObject)
designer = new ObjectDesigner(DesignerObject);
var newObject = designer.Draw((int)position.width - 8, int.MaxValue);
if (newObject != null)
DesignerObject = newObject;
GUILayout.EndScrollView();
}
}
}
#endif | 26.186667 | 115 | 0.511202 | [
"MIT"
] | superowner/Unity-WinForms | Unity/Views/ControlInspector.cs | 1,966 | C# |
namespace OnlyM.Windows
{
using System.Windows.Controls;
/// <summary>
/// Interaction logic for SettingsPage.xaml
/// </summary>
public partial class SettingsPage : UserControl
{
public SettingsPage()
{
InitializeComponent();
}
}
}
| 18.6875 | 51 | 0.58194 | [
"MIT"
] | JDigitalInk/OnlyM | OnlyM/Windows/SettingsPage.xaml.cs | 301 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using System.Windows.Forms;
using System.ComponentModel;
using System.Runtime.InteropServices;
namespace Jk {
/// <summary>
/// 長押し用ボタン
/// </summary>
public class LongPressButton : Button {
#region PInvoke
[DllImport("winmm.dll", EntryPoint = "timeGetTime")]
public static extern uint MM_GetTime();
#endregion
uint _StartTime; // 押下開始時のシステム時間(ms)
bool _IsPressed; // ボタンが押されているかどうか、制御処理のループの中で参照する
bool _Captured; // ボタン押されてマウスイベントキャプチャ状態かどうか
/// <summary>
/// 押下状態変更イベント引数クラス
/// </summary>
public class PressingChangedEventArgs : EventArgs {
/// <summary>
/// 新しい押下状態
/// </summary>
public readonly bool IsPressed;
/// <summary>
/// コンストラクタ
/// </summary>
/// <param name="isPressed">新しい押下状態</param>
public PressingChangedEventArgs(bool isPressed) {
this.IsPressed = isPressed;
}
}
/// <summary>
/// 押下状態変更デリゲート
/// </summary>
/// <param name="sender">送り主</param>
/// <param name="e">イベント引数</param>
public delegate void PressingChanged(object sender, PressingChangedEventArgs e);
/// <summary>
/// 押下状態変更イベント
/// </summary>
public event PressingChanged AfterPressingChanged;
/// <summary>
/// コンストラクタ
/// </summary>
public LongPressButton() {
// ダブルクリックを禁止する
SetStyle(ControlStyles.StandardDoubleClick, false);
}
/// <summary>
/// 押下開始時のシステム時間(ms)
/// </summary>
[Category("LongPressButton")]
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public uint StartTime {
get { return _StartTime; }
set { _StartTime = value; }
}
/// <summary>
/// 押下開始からの経過時間(ms)、ボタン押されていない場合には無意味な値が返る
/// </summary>
[Category("LongPressButton")]
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public uint ElapsedTime {
get { return MM_GetTime() - _StartTime; }
}
/// <summary>
/// ボタンが押されているかどうか、制御処理のループの中で参照する
/// </summary>
[Category("LongPressButton")]
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool IsPressed {
get { return _IsPressed; }
private set {
if (value == _IsPressed)
return;
_IsPressed = value;
if (AfterPressingChanged != null)
AfterPressingChanged(this, new PressingChangedEventArgs(value));
}
}
protected override void OnMouseDown(MouseEventArgs mevent) {
base.OnMouseDown(mevent);
_Captured = true;
if (!IsPressed)
_StartTime = MM_GetTime(); // 押下開始時のシステム時間セット
IsPressed = true;
}
protected override void OnMouseUp(MouseEventArgs mevent) {
base.OnMouseUp(mevent);
IsPressed = false;
_Captured = false;
}
protected override void OnMouseLeave(EventArgs e) {
base.OnMouseLeave(e);
IsPressed = false;
_Captured = false;
}
protected override void OnLeave(EventArgs e) {
base.OnLeave(e);
IsPressed = false;
_Captured = false;
}
void LongPressButton_LostFocus(object sender, EventArgs e) {
base.OnLeave(e);
IsPressed = false;
_Captured = false;
}
protected override void OnMouseMove(MouseEventArgs mevent) {
base.OnMouseMove(mevent);
Rectangle rc = this.ClientRectangle;
Point pt = new Point(mevent.X, mevent.Y);
if (rc.Contains(pt)) {
if (_Captured) {
if (!_IsPressed)
_StartTime = MM_GetTime(); // 押下開始時のシステム時間セット
IsPressed = true; // キャプチャされた状態で再度クライアント領域内に入ったら押された状態にする
}
} else {
IsPressed = false; // クライアント領域外に出たら放された状態にする
}
}
}
}
| 23.834437 | 82 | 0.684912 | [
"MIT"
] | nQuantums/tips | windows/cs/JunkCs/LongPressButton.cs | 4,247 | C# |
using System;
using System.Collections.Generic;
using System.Diagnostics;
namespace Microsoft.Cci
{
internal sealed class DummyUnit : IUnit
{
#region IUnit Members
public string Name
{
get { return Dummy.Name; }
}
#endregion
#region IDoubleDispatcher Members
public void Dispatch(IMetadataVisitor visitor)
{
}
#endregion
#region IUnitReference Members
#endregion
#region IReference Members
public IEnumerable<ICustomAttribute> Attributes
{
get { return IteratorHelper.GetEmptyEnumerable<ICustomAttribute>(); }
}
public IEnumerable<ILocation> Locations
{
get { return IteratorHelper.GetEmptyEnumerable<ILocation>(); }
}
#endregion
}
} | 19.409091 | 81 | 0.59719 | [
"Apache-2.0"
] | enginekit/copy_of_roslyn | Src/Compilers/Core/Source/PEWriter/Dummies/DummyUnit.cs | 856 | C# |
namespace FakeItEasy.Tests.IoC
{
using FakeItEasy.IoC;
using NUnit.Framework;
[TestFixture]
public class DictionaryContainerTests
{
[Test]
public void Register_registers_resolver_to_resolve_each_time_resolve_is_called()
{
int calledNumberOfTimes = 0;
var container = this.CreateContainer();
container.Register<IFoo>(x =>
{
calledNumberOfTimes++;
return A.Fake<IFoo>();
});
container.Resolve<IFoo>();
container.Resolve<IFoo>();
Assert.That(calledNumberOfTimes, Is.EqualTo(2));
}
[Test]
public void RegisterSingleton_registers_resolver_to_be_invoked_once_only()
{
int calledNumberOfTimes = 0;
var container = this.CreateContainer();
container.RegisterSingleton<IFoo>(x =>
{
calledNumberOfTimes++;
return A.Fake<IFoo>();
});
container.Resolve<IFoo>();
container.Resolve<IFoo>();
Assert.That(calledNumberOfTimes, Is.EqualTo(1));
}
private DictionaryContainer CreateContainer()
{
return new DictionaryContainer();
}
}
}
| 27.196078 | 89 | 0.519106 | [
"MIT"
] | bondsbw/FakeItEasy | Source/FakeItEasy.Tests/IoC/DictionaryContainerTests.cs | 1,389 | C# |
/*
* Copyright 2010-2014 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 s3control-2018-08-20.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.S3Control.Model
{
/// <summary>
/// Container for the parameters to the DeletePublicAccessBlock operation.
/// Removes the Public Access Block configuration for an Amazon Web Services account.
/// </summary>
public partial class DeletePublicAccessBlockRequest : AmazonS3ControlRequest
{
private string _accountId;
/// <summary>
/// Gets and sets the property AccountId.
/// <para>
/// The Account ID for the Amazon Web Services account whose Public Access Block configuration
/// you want to remove.
/// </para>
/// </summary>
public string AccountId
{
get { return this._accountId; }
set { this._accountId = value; }
}
// Check to see if AccountId property is set
internal bool IsSetAccountId()
{
return this._accountId != null;
}
}
} | 31.293103 | 107 | 0.668871 | [
"Apache-2.0"
] | Bio2hazard/aws-sdk-net | sdk/src/Services/S3Control/Generated/Model/DeletePublicAccessBlockRequest.cs | 1,815 | C# |
using Parse.Abstractions.Infrastructure.Data;
using Parse.Abstractions.Infrastructure.Execution;
using Parse.Abstractions.Platform.Analytics;
using Parse.Abstractions.Platform.Cloud;
using Parse.Abstractions.Platform.Configuration;
using Parse.Abstractions.Platform.Files;
using Parse.Abstractions.Platform.Installations;
using Parse.Abstractions.Platform.Objects;
using Parse.Abstractions.Platform.Push;
using Parse.Abstractions.Platform.Queries;
using Parse.Abstractions.Platform.Sessions;
using Parse.Abstractions.Platform.Users;
namespace Parse.Abstractions.Infrastructure
{
public abstract class CustomServiceHub : ICustomServiceHub
{
public virtual IServiceHub Services { get; internal set; }
public virtual IServiceHubCloner Cloner => Services.Cloner;
public virtual IMetadataController MetadataController => Services.MetadataController;
public virtual IWebClient WebClient => Services.WebClient;
public virtual ICacheController CacheController => Services.CacheController;
public virtual IParseObjectClassController ClassController => Services.ClassController;
public virtual IParseInstallationController InstallationController => Services.InstallationController;
public virtual IParseCommandRunner CommandRunner => Services.CommandRunner;
public virtual IParseCloudCodeController CloudCodeController => Services.CloudCodeController;
public virtual IParseConfigurationController ConfigurationController => Services.ConfigurationController;
public virtual IParseFileController FileController => Services.FileController;
public virtual IParseObjectController ObjectController => Services.ObjectController;
public virtual IParseQueryController QueryController => Services.QueryController;
public virtual IParseSessionController SessionController => Services.SessionController;
public virtual IParseUserController UserController => Services.UserController;
public virtual IParseCurrentUserController CurrentUserController => Services.CurrentUserController;
public virtual IParseAnalyticsController AnalyticsController => Services.AnalyticsController;
public virtual IParseInstallationCoder InstallationCoder => Services.InstallationCoder;
public virtual IParsePushChannelsController PushChannelsController => Services.PushChannelsController;
public virtual IParsePushController PushController => Services.PushController;
public virtual IParseCurrentInstallationController CurrentInstallationController => Services.CurrentInstallationController;
public virtual IServerConnectionData ServerConnectionData => Services.ServerConnectionData;
public virtual IParseDataDecoder Decoder => Services.Decoder;
public virtual IParseInstallationDataFinalizer InstallationDataFinalizer => Services.InstallationDataFinalizer;
}
}
| 43.985075 | 131 | 0.809298 | [
"BSD-3-Clause"
] | MoralisWeb3/MoralisCSharp | Parse/Abstractions/Infrastructure/CustomServiceHub.cs | 2,947 | 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.
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.PooledObjects;
namespace Microsoft.CodeAnalysis.CSharp.Simplification
{
internal partial class CSharpVarReducer : AbstractCSharpReducer
{
private static readonly ObjectPool<IReductionRewriter> s_pool = new(
() => new Rewriter(s_pool));
public CSharpVarReducer() : base(s_pool)
{
}
public override bool IsApplicable(OptionSet optionSet)
=> optionSet.GetOption(CSharpCodeStyleOptions.VarForBuiltInTypes).Value ||
optionSet.GetOption(CSharpCodeStyleOptions.VarWhenTypeIsApparent).Value ||
optionSet.GetOption(CSharpCodeStyleOptions.VarElsewhere).Value;
}
}
| 37.769231 | 89 | 0.730143 | [
"Apache-2.0"
] | cshung/roslyn | src/Workspaces/CSharp/Portable/Simplification/Reducers/CSharpVarReducer.cs | 984 | C# |
using System;
using System.Linq;
using LinqToDB;
using LinqToDB.Data;
using LinqToDB.Mapping;
using NUnit.Framework;
namespace Tests.UserTests
{
[TestFixture]
public class CompareNullableChars : TestBase
{
class Table1
{
[PrimaryKey(1)]
[Identity] public Int64 Field1 { get; set; }
[Nullable] public Char? Foeld2 { get; set; }
}
class Repository : DataConnection
{
public Repository(string configurationString) : base(configurationString)
{
}
public ITable<Table1> Table1 { get { return this.GetTable<Table1>(); } }
}
[Test]
public void Test()
{
using (var db = new Repository(ProviderName.Access))
{
var q =
from current in db.Table1
from previous in db.Table1
where current.Foeld2 == previous.Foeld2
select new { current.Field1, Field2 = previous.Field1 };
var sql = q.ToString();
}
}
}
}
| 19.744681 | 77 | 0.635776 | [
"MIT"
] | Vclcl/linq2db | Tests/Linq/UserTests/CompareNullableChars.cs | 930 | C# |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using System.Web.Mvc;
using DeviceManagement.Infrustructure.Connectivity.Exceptions;
using DeviceManagement.Infrustructure.Connectivity.Models.TerminalDevice;
using GlobalResources;
using Microsoft.Azure.Devices.Applications.RemoteMonitoring.Common.Configurations;
using Microsoft.Azure.Devices.Applications.RemoteMonitoring.Common.Exceptions;
using Microsoft.Azure.Devices.Applications.RemoteMonitoring.Common.Helpers;
using Microsoft.Azure.Devices.Applications.RemoteMonitoring.Common.Models;
using Microsoft.Azure.Devices.Applications.RemoteMonitoring.DeviceAdmin.Infrastructure.BusinessLogic;
using Microsoft.Azure.Devices.Applications.RemoteMonitoring.DeviceAdmin.Infrastructure.Exceptions;
using Microsoft.Azure.Devices.Applications.RemoteMonitoring.DeviceAdmin.Infrastructure.Models;
using Microsoft.Azure.Devices.Applications.RemoteMonitoring.DeviceAdmin.Infrastructure.Repository;
using Microsoft.Azure.Devices.Applications.RemoteMonitoring.DeviceAdmin.Web.Helpers;
using Microsoft.Azure.Devices.Applications.RemoteMonitoring.DeviceAdmin.Web.Models;
using Microsoft.Azure.Devices.Applications.RemoteMonitoring.DeviceAdmin.Web.Security;
namespace Microsoft.Azure.Devices.Applications.RemoteMonitoring.DeviceAdmin.Web.Controllers
{
[Authorize]
[OutputCache(CacheProfile = "NoCacheProfile")]
public class DeviceController : Controller
{
private readonly IApiRegistrationRepository _apiRegistrationRepository;
private readonly IDeviceLogic _deviceLogic;
private readonly IDeviceTypeLogic _deviceTypeLogic;
private readonly ICellularExtensions _cellularExtensions;
private readonly string _iotHubName;
public DeviceController(IDeviceLogic deviceLogic, IDeviceTypeLogic deviceTypeLogic,
IConfigurationProvider configProvider,
IApiRegistrationRepository apiRegistrationRepository,
ICellularExtensions cellularExtensions)
{
_deviceLogic = deviceLogic;
_deviceTypeLogic = deviceTypeLogic;
_apiRegistrationRepository = apiRegistrationRepository;
_cellularExtensions = cellularExtensions;
_iotHubName = configProvider.GetConfigurationSettingValue("iotHub.HostName");
}
[RequirePermission(Permission.ViewDevices)]
public ActionResult Index()
{
return View();
}
[RequirePermission(Permission.AddDevices)]
public async Task<ActionResult> AddDevice()
{
var deviceTypes = await _deviceTypeLogic.GetAllDeviceTypesAsync();
return View(deviceTypes);
}
[RequirePermission(Permission.AddDevices)]
public async Task<ActionResult> SelectType(DeviceType deviceType)
{
if (_apiRegistrationRepository.IsApiRegisteredInAzure())
{
try
{
List<DeviceModel> devices = await GetDevices();
ViewBag.AvailableIccids = _cellularExtensions.GetListOfAvailableIccids(devices);
ViewBag.CanHaveIccid = true;
}
catch (CellularConnectivityException)
{
ViewBag.CanHaveIccid = false;
}
}
else
{
ViewBag.CanHaveIccid = false;
}
// device type logic getdevicetypeasync
var device = new UnregisteredDeviceModel
{
DeviceType = deviceType,
IsDeviceIdSystemGenerated = true
};
return PartialView("_AddDeviceCreate", device);
}
[HttpPost]
[RequirePermission(Permission.AddDevices)]
[ValidateAntiForgeryToken]
public async Task<ActionResult> AddDeviceCreate(string button, UnregisteredDeviceModel model)
{
bool isModelValid = ModelState.IsValid;
bool onlyValidating = (button != null && button.ToLower().Trim() == "check");
if (ReferenceEquals(null, model) ||
(model.GetType() == typeof (object)))
{
model = new UnregisteredDeviceModel();
}
if (_apiRegistrationRepository.IsApiRegisteredInAzure())
{
try
{
List<DeviceModel> devices = await GetDevices();
ViewBag.AvailableIccids = _cellularExtensions.GetListOfAvailableIccids(devices);
ViewBag.CanHaveIccid = true;
}
catch (CellularConnectivityException)
{
ViewBag.CanHaveIccid = false;
}
}
else
{
ViewBag.CanHaveIccid = false;
}
//reset flag
model.IsDeviceIdUnique = false;
if (model.IsDeviceIdSystemGenerated)
{
//clear the model state of errors prior to modifying the model
ModelState.Clear();
//assign a system generated device Id
model.DeviceId = Guid.NewGuid().ToString();
//validate the model
isModelValid = TryValidateModel(model);
}
if (isModelValid)
{
bool deviceExists = await GetDeviceExistsAsync(model.DeviceId);
model.IsDeviceIdUnique = !deviceExists;
if (model.IsDeviceIdUnique)
{
if (!onlyValidating)
{
return await Add(model);
}
}
else
{
ModelState.AddModelError("DeviceId", Strings.DeviceIdInUse);
}
}
return PartialView("_AddDeviceCreate", model);
}
[HttpPost]
[RequirePermission(Permission.AddDevices)]
[ValidateAntiForgeryToken]
public async Task<ActionResult> EditDeviceProperties(EditDevicePropertiesModel model)
{
if (ModelState.IsValid)
{
try
{
return await Edit(model);
}
catch (ValidationException exception)
{
if (exception.Errors != null && exception.Errors.Any())
{
exception.Errors.ToList<string>().ForEach(error => ModelState.AddModelError(string.Empty, error));
}
}
catch (Exception)
{
ModelState.AddModelError(string.Empty, Strings.DeviceUpdateError);
}
}
return View("EditDeviceProperties", model);
}
private async Task<ActionResult> Add(UnregisteredDeviceModel model)
{
var deviceWithKeys = await AddDeviceAsync(model);
var newDevice = new RegisteredDeviceModel
{
HostName = _iotHubName,
DeviceType = model.DeviceType,
DeviceId = deviceWithKeys.Device.DeviceProperties.DeviceID,
PrimaryKey = deviceWithKeys.SecurityKeys.PrimaryKey,
SecondaryKey = deviceWithKeys.SecurityKeys.SecondaryKey,
InstructionsUrl = model.DeviceType.InstructionsUrl
};
return PartialView("_AddDeviceCopy", newDevice);
}
[RequirePermission(Permission.EditDeviceMetadata)]
public async Task<ActionResult> EditDeviceProperties(string deviceId)
{
EditDevicePropertiesModel model;
IEnumerable<DevicePropertyValueModel> propValModels;
model = new EditDevicePropertiesModel
{
DevicePropertyValueModels = new List<DevicePropertyValueModel>()
};
var device = await _deviceLogic.GetDeviceAsync(deviceId);
if (device != null)
{
if (device.DeviceProperties == null)
{
throw new DeviceRequiredPropertyNotFoundException("Required DeviceProperties not found");
}
model.DeviceId = device.DeviceProperties.DeviceID;
propValModels = _deviceLogic.ExtractDevicePropertyValuesModels(device);
propValModels = ApplyDevicePropertyOrdering(propValModels);
model.DevicePropertyValueModels.AddRange(propValModels);
}
return View("EditDeviceProperties", model);
}
private async Task<ActionResult> Edit(EditDevicePropertiesModel model)
{
if (model != null)
{
var device = await _deviceLogic.GetDeviceAsync(model.DeviceId);
if (device != null)
{
_deviceLogic.ApplyDevicePropertyValueModels(device, model.DevicePropertyValueModels);
await _deviceLogic.UpdateDeviceAsync(device);
}
}
return RedirectToAction("Index");
}
[RequirePermission(Permission.ViewDevices)]
public async Task<ActionResult> GetDeviceDetails(string deviceId)
{
IEnumerable<DevicePropertyValueModel> propModels;
var device = await _deviceLogic.GetDeviceAsync(deviceId);
if (device == null)
{
throw new InvalidOperationException("Unable to load device with deviceId " + deviceId);
}
if (device.DeviceProperties == null)
{
throw new DeviceRequiredPropertyNotFoundException("'DeviceProperties' property is missing");
}
DeviceDetailModel deviceModel = new DeviceDetailModel
{
DeviceID = deviceId,
HubEnabledState = device.DeviceProperties.GetHubEnabledState(),
DevicePropertyValueModels = new List<DevicePropertyValueModel>()
};
propModels = _deviceLogic.ExtractDevicePropertyValuesModels(device);
propModels = ApplyDevicePropertyOrdering(propModels);
deviceModel.DevicePropertyValueModels.AddRange(propModels);
// check if value is cellular by checking iccid property
deviceModel.IsCellular = device.SystemProperties.ICCID != null;
deviceModel.Iccid = device.SystemProperties.ICCID; // todo: try get rid of null checks
return PartialView("_DeviceDetails", deviceModel);
}
[RequirePermission(Permission.ViewDevices)]
public ActionResult GetDeviceCellularDetails(string iccid)
{
var viewModel = new SimInformationViewModel();
viewModel.TerminalDevice = this._cellularExtensions.GetSingleTerminalDetails(new Iccid(iccid));
viewModel.SessionInfo = this._cellularExtensions.GetSingleSessionInfo(new Iccid(iccid)).LastOrDefault() ??
new SessionInfo();
return PartialView("_CellularInformation", viewModel);
}
[RequirePermission(Permission.ViewDeviceSecurityKeys)]
public async Task<ActionResult> GetDeviceKeys(string deviceId)
{
var keys = await _deviceLogic.GetIoTHubKeysAsync(deviceId);
var keysModel = new SecurityKeysModel
{
PrimaryKey = keys != null ? keys.PrimaryKey : Strings.DeviceNotRegisteredInIoTHub,
SecondaryKey = keys != null ? keys.SecondaryKey : Strings.DeviceNotRegisteredInIoTHub
};
return PartialView("_DeviceDetailsKeys", keysModel);
}
[RequirePermission(Permission.RemoveDevices)]
public ActionResult RemoveDevice(string deviceId)
{
var device = new RegisteredDeviceModel
{
HostName = _iotHubName,
DeviceId = deviceId
};
return View("RemoveDevice", device);
}
[HttpPost]
[RequirePermission(Permission.RemoveDevices)]
[ValidateAntiForgeryToken]
public async Task<ActionResult> DeleteDevice(string deviceId)
{
await _deviceLogic.RemoveDeviceAsync(deviceId);
return View("Index");
}
private static IEnumerable<DevicePropertyValueModel> ApplyDevicePropertyOrdering(IEnumerable<DevicePropertyValueModel> devicePropertyModels)
{
Debug.Assert(
devicePropertyModels != null,
"devicePropertyModels is a null reference.");
return devicePropertyModels.OrderByDescending(
t => DeviceDisplayHelper.GetIsCopyControlPropertyName(
t.Name)).ThenBy(u => u.DisplayOrder).ThenBy(
v => v.Name);
}
private async Task<DeviceWithKeys> AddDeviceAsync(UnregisteredDeviceModel unregisteredDeviceModel)
{
Debug.Assert(
unregisteredDeviceModel != null,
"unregisteredDeviceModel is a null reference.");
Debug.Assert(
unregisteredDeviceModel.DeviceType != null,
"unregisteredDeviceModel.DeviceType is a null reference.");
DeviceModel device = DeviceCreatorHelper.BuildDeviceStructure(unregisteredDeviceModel.DeviceId,
unregisteredDeviceModel.DeviceType.IsSimulatedDevice, unregisteredDeviceModel.Iccid);
DeviceWithKeys addedDevice = await this._deviceLogic.AddDeviceAsync(device);
return addedDevice;
}
private async Task<bool> GetDeviceExistsAsync(string deviceId)
{
DeviceModel existingDevice = await _deviceLogic.GetDeviceAsync(deviceId);
return (existingDevice != null);
}
private async Task<List<DeviceModel>> GetDevices()
{
var query = new DeviceListQuery
{
Take = 1000
};
var devices = await _deviceLogic.GetDevices(query);
return devices.Results;
}
}
}
| 38.074468 | 148 | 0.608759 | [
"MIT"
] | Anchinga/TechnicalCommunityContent | IoT/Azure IoT Suite/Session 3 - Building Practical IoT Solutions/Solutions/Demo 3.2/DeviceAdministration/Web/Controllers/DeviceController.cs | 14,316 | C# |
namespace Evolutionary
{
abstract class NodeBaseType<T,S> where S : new()
{
// everybody has a parent
public NodeBaseType<T,S> Parent { get; set; }
// everyone needs to implement these
public abstract T Evaluate();
public abstract NodeBaseType<T,S> Clone(NodeBaseType<T, S> parentNode);
public abstract NodeBaseType<T, S> SelectRandom(ref int numNodesConsidered);
public abstract void SetCandidateRef(CandidateSolution<T, S> candidate);
public abstract override string ToString();
}
}
| 35.1875 | 84 | 0.671403 | [
"Apache-2.0"
] | monado3/Evolutionary.Net | Engine/NodeBaseType.cs | 565 | C# |
using System.Collections.Generic;
namespace Mendz.Matrix
{
/// <summary>
/// Provides methods to create and initialize a matrix,
/// which is basically T[,] -- a two-dimensional array of type T.
/// </summary>
/// <typeparam name="T">The type of the elements/entries.</typeparam>
public static class Matrix<T>
{
/// <summary>
/// Creates and initializes a matrix.
/// </summary>
/// <param name="rows">The number of rows in the matrix.</param>
/// <param name="columns">The number of columns in the matrix.</param>
/// <param name="entry">The default entry values.</param>
/// <param name="diagonal">The default values of the main diagonal.</param>
/// <returns>Returns the matrix.</returns>
public static T[,] Create(int rows, int columns,
T entry = default, T diagonal = default)
{
T[,] matrix = new T[rows, columns];
Initialize(matrix, rows, columns, entry, diagonal, false);
return matrix;
}
/// <summary>
/// Creates and initializes a matrix.
/// </summary>
/// <param name="size">The size of the matrix.</param>
/// <param name="entry">The default entry values.</param>
/// <param name="diagonal">The default values of the main diagonal.</param>
/// <returns>Returns the matrix.</returns>
public static T[,] Create((int rows, int columns) size,
T entry = default, T diagonal = default) => Create(size.rows, size.columns, entry, diagonal);
/// <summary>
/// Initializes a matrix.
/// </summary>
/// <param name="matrix">The matrix to initialize.</param>
/// <param name="rows">The number of rows in the matrix.</param>
/// <param name="columns">The number of columns in the matrix.</param>
/// <param name="entry">The default entry values.</param>
/// <param name="diagonal">The default values of the main diagonal.</param>
/// <param name="force">To force initialization even if entry or diagonal is default(T). Default is true.</param>
/// <remarks>
/// The entries are initialized only when the entry is not equal to default(T).
/// The diagonal values are initialized only when the diagonal is not equal to default(T).
/// </remarks>
private static void Initialize(T[,] matrix, int rows, int columns,
T entry = default, T diagonal = default, bool force = true)
{
bool isSetEntry = !EqualityComparer<T>.Default.Equals(entry, default);
bool isSetDiagonal = !EqualityComparer<T>.Default.Equals(diagonal, default);
if ((!isSetEntry && isSetDiagonal) || force)
{
for (int i = 0; i < rows; i++)
{
matrix[i, i] = diagonal;
}
}
else if (isSetEntry || isSetDiagonal || force)
{
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < columns; j++)
{
if (i == j)
{
matrix[i, j] = diagonal;
}
else
{
matrix[i, j] = entry;
}
}
}
}
}
/// <summary>
/// Initializes a matrix.
/// </summary>
/// <param name="matrix">The matrix to initialize.</param>
/// <param name="entry">The default entry values.</param>
/// <param name="diagonal">The default values of the main diagonal.</param>
/// <param name="force">To force initialization even if entry or diagonal is default(T). Default is true.</param>
public static void Initialize(T[,] matrix,
T entry = default, T diagonal = default, bool force = true) => Initialize(matrix, matrix.GetLength(0), matrix.GetLength(1), entry, diagonal, force);
}
}
| 44.365591 | 160 | 0.531992 | [
"Apache-2.0"
] | etmendz/Mendz.Matrix | Mendz.Matrix/Matrix.cs | 4,128 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
/// ******************************************************************************************************************
/// * Copyright (c) 2011 Dialect Software LLC *
/// * This software is distributed under the terms of the Apache License http://www.apache.org/licenses/LICENSE-2.0 *
/// * *
/// ******************************************************************************************************************
namespace DialectSoftware.Registration
{
//[Serializable]
[XmlRoot("phone")]
public class Phone
{
#region Primitive Properties
public virtual int id
{
get;
set;
}
public virtual string formattedPhoneNumber
{
get;
set;
}
public virtual string countryCode
{
get;
set;
}
public virtual string areaCode
{
get;
set;
}
public virtual string phoneNumber
{
get;
set;
}
public virtual string extension
{
get;
set;
}
public virtual string countryName
{
get;
set;
}
public virtual string isoCountryCode
{
get;
set;
}
public int phoneType
{
get;
set;
}
public override bool Equals(object obj)
{
return obj is Phone && ((Phone)obj).ToString() == ToString();
}
public override int GetHashCode()
{
return ToString().GetHashCode();
}
public override string ToString()
{
var util = PhoneNumbers.PhoneNumberUtil.GetInstance();
var number = PhoneNumbers.PhoneNumberUtil.GetInstance().Parse(String.Format("+{0} {1} {2}", countryCode??"", areaCode??"", phoneNumber??""),isoCountryCode);
return util.Format(number, PhoneNumbers.PhoneNumberFormat.INTERNATIONAL);
}
#endregion
}
}
| 25.382979 | 169 | 0.422883 | [
"Apache-2.0"
] | dialectsoftware/DialectSoftware.Registration | DialectSoftware.Registration.Documents/Entities/Contacts/Phone.cs | 2,388 | C# |
namespace Cineaste.Data.Services;
public interface IListService
{
DataList GetList(IEnumerable<Kind> kinds, IEnumerable<Tag> tags);
}
| 19.857143 | 69 | 0.784173 | [
"MIT"
] | TolikPylypchuk/Cineaste | Cineaste.Data/Services/IListService.cs | 139 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
namespace Dsp.Web.Chat
{
[Authorize]
[RoutePrefix("api/Chat")]
public class ChatController : ApiController
{
private DspContext _context;
public ChatController()
{
_context = new DspContext();
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
if (_context != null)
{
_context.Dispose();
_context = null;
}
}
[Route("Linkshells/{name}")]
public Task<HttpResponseMessage> GetLinkshell(string name, [FromUri]PageSettings pageSettings)
{
var action = new GetLinkshellChatMessages(_context);
action.LinkshellName = name;
action.OwnerAccountId = User.Identity.GetAccountId();
action.PageSettings = pageSettings;
action.RequestUri = Request.RequestUri;
return action.Execute();
}
[Route("Tells/{id}")]
public Task<HttpResponseMessage> GetTells(long id, [FromUri]PageSettings pageSettings)
{
var action = new GetTellChatMessages(_context);
action.CharacterId = id;
action.OwnerAccountId = User.Identity.GetAccountId();
action.PageSettings = pageSettings;
action.RequestUri = Request.RequestUri;
return action.Execute();
}
}
}
| 28.375 | 102 | 0.595343 | [
"MIT"
] | joncloud/darkstarweb | src/Dsp.Web/Chat/ChatController.cs | 1,591 | C# |
using System;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Data;
using Avalonia.Input;
namespace Zafiro.Avalonia.Design
{
public class DeltaContentControl : ContentControl
{
public static readonly AvaloniaProperty AngleProperty = AvaloniaProperty.Register<DeltaContentControl, double>(
"Angle", default, false, BindingMode.TwoWay);
public static readonly AvaloniaProperty AllowVerticalProperty =
AvaloniaProperty.Register<DeltaContentControl, bool>(
"AllowVertical", true, false, BindingMode.TwoWay);
public static readonly AvaloniaProperty AllowHorizontalProperty =
AvaloniaProperty.Register<DeltaContentControl, bool>(
"AllowHorizontal", true, false, BindingMode.TwoWay);
public static readonly AvaloniaProperty HorizontalProperty =
AvaloniaProperty.Register<DeltaContentControl, double>(
"Horizontal", default, false, BindingMode.TwoWay);
public static readonly AvaloniaProperty VerticalProperty =
AvaloniaProperty.Register<DeltaContentControl, double>(
"Vertical", default, false, BindingMode.TwoWay);
private MyThumb thumb;
public double Horizontal
{
get => (double) GetValue(HorizontalProperty);
set => SetValue(HorizontalProperty, value);
}
public double Vertical
{
get => (double) GetValue(VerticalProperty);
set => SetValue(VerticalProperty, value);
}
public bool AllowVertical
{
get => (bool) GetValue(AllowVerticalProperty);
set => SetValue(AllowVerticalProperty, value);
}
public bool AllowHorizontal
{
get => (bool) GetValue(AllowHorizontalProperty);
set => SetValue(AllowHorizontalProperty, value);
}
public double Angle
{
get => (double) GetValue(AngleProperty);
set => SetValue(AngleProperty, value);
}
public MyThumb Thumb
{
get => thumb;
private set
{
thumb = value;
if (thumb != null)
{
thumb.DragDelta += ThumbOnDragDelta;
}
}
}
private void ThumbOnDragDelta(object sender, VectorEventArgs e)
{
var vector = e.Vector;
var result = ProjectVector(Angle, vector);
var horzDelta = result.X;
var vertDelta = result.Y;
if (AllowHorizontal)
{
Horizontal += horzDelta;
}
if (AllowVertical)
{
Vertical += vertDelta;
}
}
protected override void OnTemplateApplied(TemplateAppliedEventArgs e)
{
Thumb = e.NameScope.Find<MyThumb>("Thumb");
base.OnTemplateApplied(e);
}
private static Vector ProjectVector(double angle, Vector vector)
{
var angleRad = angle * Math.PI * 2 / 360;
var x = new Vector((float) Math.Cos(angleRad), -(float) Math.Sin(angleRad));
var y = new Vector((float) Math.Sin(angleRad), (float) Math.Cos(angleRad));
var xProj = Vector.Dot(vector, x);
var yProj = Vector.Dot(vector, y);
var result = new Vector(xProj, yProj);
return result;
}
}
} | 30.852174 | 119 | 0.575817 | [
"MIT"
] | SuperJMN-Zafiro/Zafiro | Source/Zafiro.Avalonia.Design/DeltaContentControl.cs | 3,550 | C# |
using ToDoListApp.Models;
namespace ToDoListApp.Repositories
{
public interface IToDoListRepository : IRepository<ToDoList, int>
{
}
} | 17.333333 | 69 | 0.705128 | [
"MIT"
] | beardeddev/tutos | ToDoListApp/Repositories/IToDoListRepository.cs | 156 | C# |
using System.Runtime.Serialization;
namespace PlanGrid.Api
{
public enum Status
{
[EnumMember(Value = "incomplete")]
Incomplete,
[EnumMember(Value = "complete")]
Complete,
[EnumMember(Value = "errored")]
Errored
}
}
| 16.470588 | 42 | 0.578571 | [
"MIT"
] | BartokW/plangrid-api-net | PlanGrid.Api/Status.cs | 282 | C# |
namespace Course_Project.Data.Models
{
/// <summary>
/// Film role.
/// </summary>
public class FilmActor
{
/// <summary>
/// Identification.
/// </summary>
public int Id { get; set; }
/// <summary>
/// Actor identification.
/// </summary>
public int ActorId { get; set; }
/// <summary>
/// Navigation property for actor.
/// </summary>
public Actor Actor { get; set; }
/// <summary>
/// Film identification.
/// </summary>
public int FilmId { get; set; }
/// <summary>
/// Navigation property for Film.
/// </summary>
public Film Film { get; set; }
}
} | 22.484848 | 42 | 0.47035 | [
"MIT"
] | AKS2044/TMS-DotNet02-Online-Aksenchik | src/CourseProject.Data/Models/FilmActor.cs | 744 | C# |
#region License
/*********************************************************************************
* UIActionBinding.cs
*
* Copyright (c) 2004-2021 Henk Nicolai
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
**********************************************************************************/
#endregion
using System;
using System.Collections.Specialized;
namespace Eutherion.UIActions
{
/// <summary>
/// Defines a set of <see cref="IUIActionInterface"/>s and a <see cref="UIActionHandlerFunc"/> for a given <see cref="UIAction"/>,
/// which completely determines how a <see cref="UIAction"/> is exposed and implemented by a <see cref="UIActionHandler"/>.
/// </summary>
public sealed class UIActionBinding
{
/// <summary>
/// Gets the bound <see cref="UIAction"/>.
/// </summary>
public UIAction Action { get; }
/// <summary>
/// Gets the <see cref="IUIActionInterface"/> set which defines how the action is exposed to the user interface.
/// </summary>
public ImplementationSet<IUIActionInterface> Interfaces { get; }
/// <summary>
/// Gets the handler function used to invoke the <see cref="UIAction"/> and determine its <see cref="UIActionState"/>.
/// </summary>
public UIActionHandlerFunc Handler { get; }
/// <summary>
/// Initializes a new instance of <see cref="UIActionBinding"/>.
/// </summary>
/// <param name="binding">
/// A set of default suggested interfaces for a <see cref="UIAction"/>.
/// </param>
/// <param name="handler">
/// The handler function used to invoke the <see cref="UIAction"/> and determine its <see cref="UIActionState"/>.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="binding"/> and/or <paramref name="handler"/> are null.
/// </exception>
public UIActionBinding(DefaultUIActionBinding binding, UIActionHandlerFunc handler)
{
if (binding == null) throw new ArgumentNullException(nameof(binding));
Action = binding.Action;
Interfaces = binding.DefaultInterfaces;
Handler = handler ?? throw new ArgumentNullException(nameof(handler));
}
/// <summary>
/// Initializes a new instance of <see cref="UIActionBinding"/>.
/// </summary>
/// <param name="action">
/// The <see cref="UIAction"/> to bind to a <see cref="UIActionHandler"/>.
/// </param>
/// <param name="interfaces">
/// The <see cref="IUIActionInterface"/> set which defines how the action is exposed to the user interface.
/// </param>
/// <param name="handler">
/// The handler function used to invoke the <see cref="UIAction"/> and determine its <see cref="UIActionState"/>.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="action"/> and/or <paramref name="interfaces"/> and/or <paramref name="handler"/> are null.
/// </exception>
public UIActionBinding(UIAction action, ImplementationSet<IUIActionInterface> interfaces, UIActionHandlerFunc handler)
{
Action = action ?? throw new ArgumentNullException(nameof(action));
Interfaces = interfaces ?? throw new ArgumentNullException(nameof(interfaces));
Handler = handler ?? throw new ArgumentNullException(nameof(handler));
}
}
}
| 44.593407 | 134 | 0.603499 | [
"Apache-2.0"
] | PenguinF/sandra-three | Eutherion/Shared/UIActions/UIActionBinding.cs | 4,058 | C# |
namespace Gimnasio.Usuarios
{
partial class frmUsuario
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.txtNombre = new System.Windows.Forms.TextBox();
this.txtPassword = new System.Windows.Forms.TextBox();
this.txtUsuario = new System.Windows.Forms.TextBox();
this.label3 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.label1 = new System.Windows.Forms.Label();
this.button1 = new System.Windows.Forms.Button();
this.txtPasswordConfirm = new System.Windows.Forms.TextBox();
this.label4 = new System.Windows.Forms.Label();
this.button2 = new System.Windows.Forms.Button();
this.shapeContainer1 = new Microsoft.VisualBasic.PowerPacks.ShapeContainer();
this.lineShape1 = new Microsoft.VisualBasic.PowerPacks.LineShape();
this.SuspendLayout();
//
// txtNombre
//
this.txtNombre.Anchor = System.Windows.Forms.AnchorStyles.None;
this.txtNombre.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.txtNombre.Location = new System.Drawing.Point(247, 31);
this.txtNombre.Margin = new System.Windows.Forms.Padding(4);
this.txtNombre.MaxLength = 45;
this.txtNombre.Name = "txtNombre";
this.txtNombre.Size = new System.Drawing.Size(226, 24);
this.txtNombre.TabIndex = 1;
//
// txtPassword
//
this.txtPassword.Anchor = System.Windows.Forms.AnchorStyles.None;
this.txtPassword.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.txtPassword.Location = new System.Drawing.Point(13, 81);
this.txtPassword.Margin = new System.Windows.Forms.Padding(4);
this.txtPassword.MaxLength = 45;
this.txtPassword.Name = "txtPassword";
this.txtPassword.PasswordChar = '*';
this.txtPassword.Size = new System.Drawing.Size(226, 24);
this.txtPassword.TabIndex = 2;
//
// txtUsuario
//
this.txtUsuario.Anchor = System.Windows.Forms.AnchorStyles.None;
this.txtUsuario.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.txtUsuario.Location = new System.Drawing.Point(13, 31);
this.txtUsuario.Margin = new System.Windows.Forms.Padding(4);
this.txtUsuario.MaxLength = 45;
this.txtUsuario.Name = "txtUsuario";
this.txtUsuario.Size = new System.Drawing.Size(226, 24);
this.txtUsuario.TabIndex = 0;
//
// label3
//
this.label3.Anchor = System.Windows.Forms.AnchorStyles.None;
this.label3.AutoSize = true;
this.label3.Font = new System.Drawing.Font("Microsoft Sans Serif", 11.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label3.Location = new System.Drawing.Point(244, 9);
this.label3.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(68, 18);
this.label3.TabIndex = 8;
this.label3.Text = "Nombre";
//
// label2
//
this.label2.Anchor = System.Windows.Forms.AnchorStyles.None;
this.label2.AutoSize = true;
this.label2.Font = new System.Drawing.Font("Microsoft Sans Serif", 11.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label2.Location = new System.Drawing.Point(13, 59);
this.label2.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(95, 18);
this.label2.TabIndex = 7;
this.label2.Text = "Contraseña";
//
// label1
//
this.label1.Anchor = System.Windows.Forms.AnchorStyles.None;
this.label1.AutoSize = true;
this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 11.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label1.Location = new System.Drawing.Point(10, 9);
this.label1.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(67, 18);
this.label1.TabIndex = 6;
this.label1.Text = "Usuario";
//
// button1
//
this.button1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.button1.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.button1.Location = new System.Drawing.Point(261, 125);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(103, 30);
this.button1.TabIndex = 4;
this.button1.Text = "Guardar";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// txtPasswordConfirm
//
this.txtPasswordConfirm.Anchor = System.Windows.Forms.AnchorStyles.None;
this.txtPasswordConfirm.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.txtPasswordConfirm.Location = new System.Drawing.Point(247, 81);
this.txtPasswordConfirm.Margin = new System.Windows.Forms.Padding(4);
this.txtPasswordConfirm.MaxLength = 45;
this.txtPasswordConfirm.Name = "txtPasswordConfirm";
this.txtPasswordConfirm.PasswordChar = '*';
this.txtPasswordConfirm.Size = new System.Drawing.Size(226, 24);
this.txtPasswordConfirm.TabIndex = 3;
//
// label4
//
this.label4.Anchor = System.Windows.Forms.AnchorStyles.None;
this.label4.AutoSize = true;
this.label4.Font = new System.Drawing.Font("Microsoft Sans Serif", 11.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label4.Location = new System.Drawing.Point(244, 59);
this.label4.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(172, 18);
this.label4.TabIndex = 13;
this.label4.Text = "Confirmar contraseña";
//
// button2
//
this.button2.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.button2.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.button2.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.button2.Location = new System.Drawing.Point(370, 125);
this.button2.Name = "button2";
this.button2.Size = new System.Drawing.Size(103, 30);
this.button2.TabIndex = 5;
this.button2.Text = "Cancelar";
this.button2.UseVisualStyleBackColor = true;
this.button2.Click += new System.EventHandler(this.button2_Click);
//
// shapeContainer1
//
this.shapeContainer1.Location = new System.Drawing.Point(0, 0);
this.shapeContainer1.Margin = new System.Windows.Forms.Padding(0);
this.shapeContainer1.Name = "shapeContainer1";
this.shapeContainer1.Shapes.AddRange(new Microsoft.VisualBasic.PowerPacks.Shape[] {
this.lineShape1});
this.shapeContainer1.Size = new System.Drawing.Size(487, 158);
this.shapeContainer1.TabIndex = 14;
this.shapeContainer1.TabStop = false;
//
// lineShape1
//
this.lineShape1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.lineShape1.Name = "lineShape1";
this.lineShape1.X1 = 138;
this.lineShape1.X2 = 488;
this.lineShape1.Y1 = 115;
this.lineShape1.Y2 = 115;
//
// frmUsuario
//
this.AcceptButton = this.button1;
this.AutoScaleDimensions = new System.Drawing.SizeF(9F, 18F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(214)))), ((int)(((byte)(214)))), ((int)(((byte)(214)))));
this.CancelButton = this.button2;
this.ClientSize = new System.Drawing.Size(487, 158);
this.Controls.Add(this.button2);
this.Controls.Add(this.txtPasswordConfirm);
this.Controls.Add(this.label4);
this.Controls.Add(this.button1);
this.Controls.Add(this.txtNombre);
this.Controls.Add(this.txtPassword);
this.Controls.Add(this.txtUsuario);
this.Controls.Add(this.label3);
this.Controls.Add(this.label2);
this.Controls.Add(this.label1);
this.Controls.Add(this.shapeContainer1);
this.Font = new System.Drawing.Font("Microsoft Sans Serif", 11.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
this.Margin = new System.Windows.Forms.Padding(4);
this.MaximizeBox = false;
this.MaximumSize = new System.Drawing.Size(503, 197);
this.MinimizeBox = false;
this.MinimumSize = new System.Drawing.Size(503, 197);
this.Name = "frmUsuario";
this.ShowIcon = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "Datos de Usuario";
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.frmUsuario_FormClosing);
this.Load += new System.EventHandler(this.frmUsuario_Load);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
public System.Windows.Forms.TextBox txtNombre;
public System.Windows.Forms.TextBox txtPassword;
public System.Windows.Forms.TextBox txtUsuario;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Button button1;
public System.Windows.Forms.TextBox txtPasswordConfirm;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.Button button2;
private Microsoft.VisualBasic.PowerPacks.ShapeContainer shapeContainer1;
private Microsoft.VisualBasic.PowerPacks.LineShape lineShape1;
}
} | 51.360169 | 166 | 0.606468 | [
"Apache-2.0"
] | xmalmorthen/gym | Gimnasio/Usuarios/frmUsuario.Designer.cs | 12,125 | C# |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
using System;
using System.Collections.Generic;
using Aliyun.Acs.Core.Transform;
using Aliyun.Acs.aegis.Model.V20161111;
namespace Aliyun.Acs.aegis.Transform.V20161111
{
public class CreateLogQueryResponseUnmarshaller
{
public static CreateLogQueryResponse Unmarshall(UnmarshallerContext context)
{
CreateLogQueryResponse createLogQueryResponse = new CreateLogQueryResponse();
createLogQueryResponse.HttpResponse = context.HttpResponse;
createLogQueryResponse.RequestId = context.StringValue("CreateLogQuery.RequestId");
return createLogQueryResponse;
}
}
}
| 35.8 | 86 | 0.757682 | [
"Apache-2.0"
] | AxiosCros/aliyun-openapi-net-sdk | aliyun-net-sdk-aegis/Aegis/Transform/V20161111/CreateLogQueryResponseUnmarshaller.cs | 1,432 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace CodeDuo.ManagementWebApp.Transactions {
public partial class ViewTransactions {
/// <summary>
/// gridTransactions control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.GridView gridTransactions;
/// <summary>
/// TransactionsData control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.SqlDataSource TransactionsData;
}
}
| 33.735294 | 84 | 0.517001 | [
"Apache-2.0"
] | CodeDuoFintech/CodeDuoSoln | CodeDuo.ManagementWebApp/Transactions/ViewTransactions.aspx.designer.cs | 1,149 | C# |
// *** WARNING: this file was generated by crd2pulumi. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.Kubernetes.Types.Inputs.Certmanager.V1
{
/// <summary>
/// PrivateKey is the name of a Kubernetes Secret resource that will be used to store the automatically generated ACME account private key. Optionally, a `key` may be specified to select a specific entry within the named Secret resource. If `key` is not specified, a default of `tls.key` will be used.
/// </summary>
public class ClusterIssuerSpecAcmePrivateKeySecretRefArgs : Pulumi.ResourceArgs
{
/// <summary>
/// The key of the entry in the Secret resource's `data` field to be used. Some instances of this field may be defaulted, in others it may be required.
/// </summary>
[Input("key")]
public Input<string>? Key { get; set; }
/// <summary>
/// Name of the resource being referred to. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names
/// </summary>
[Input("name", required: true)]
public Input<string> Name { get; set; } = null!;
public ClusterIssuerSpecAcmePrivateKeySecretRefArgs()
{
}
}
}
| 40.828571 | 305 | 0.678097 | [
"MIT"
] | WhereIsMyTransport/Pulumi.Crds.CertManager | crd/dotnet/Certmanager/V1/Inputs/ClusterIssuerSpecAcmePrivateKeySecretRefArgs.cs | 1,429 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AngieDashVFX : PlayerHit
{
protected Rigidbody rb;
public float vel;
public float destructionTime;
protected virtual void Start()
{
rb = GetComponent<Rigidbody>();
rb.velocity = transform.TransformDirection(Vector3.back).normalized * vel;
Destroy(gameObject, destructionTime);
}
//protected override void DamageInteraction()
//{
//}
}
| 19.038462 | 82 | 0.682828 | [
"Apache-2.0"
] | bruno-pLima/PandoraPlayers | Players/Angie/Ataques/AngieDashVFX.cs | 497 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace Bright.Forms.Main.Docks
{
public partial class PictureView : WeifenLuo.WinFormsUI.Docking.DockContent
{
protected override string GetPersistString()
{
return "pictureview";
}
public event Action<bool> ImageLoadingChanged;
public event Action<string> FileChanged;
public bool ZoomPicture
{
get { return renderer.ZoomPicture; }
set
{
renderer.ZoomPicture = value;
renderer.Refresh();
}
}
public bool KeepProportion
{
get { return renderer.KeepProportion; }
set
{
renderer.KeepProportion = value;
renderer.Refresh();
}
}
public bool ZoomSmallPicture
{
get { return renderer.ZoomSmallPicture; }
set
{
renderer.ZoomSmallPicture = value;
renderer.Refresh();
}
}
public string AdditionalString
{
get { return renderer.AdditionalString; }
set
{
renderer.AdditionalString = value;
renderer.Refresh();
}
}
public PictureView()
{
InitializeComponent();
horzScroll.GotFocus += new EventHandler(restoreFocus);
vertScroll.GotFocus += new EventHandler(restoreFocus);
renderer.ChangeShowScroll += new Action<bool>(renderer_ChangeShowScroll);
renderer.UpdateImageSize += new Action(renderer_UpdateImageSize);
renderer.ImageLoadingChanged += new Action<bool>((b) => { if (ImageLoadingChanged != null)ImageLoadingChanged.Invoke(b); });
renderer.FileChanged += new Action<string>((s) => { if (FileChanged != null) FileChanged.Invoke(s); });
renderer.PositionUpdateRequired += new Action<Point>(renderer_PositionUpdateRequired);
}
bool silentScrollUpdate = false;
void renderer_PositionUpdateRequired(Point obj)
{
silentScrollUpdate = true;
Point nv = new Point();
if (horzScroll.Enabled)
{
int npos = horzScroll.Value + obj.X;
if (npos > horzScroll.Maximum)
npos = horzScroll.Maximum;
else if (npos < 0)
npos = 0;
horzScroll.Value = npos;
nv.X = npos;
}
if (vertScroll.Enabled)
{
int npos = vertScroll.Value + obj.Y;
if (npos > vertScroll.Maximum)
npos = vertScroll.Maximum;
else if (npos < 0)
npos = 0;
vertScroll.Value = npos;
nv.Y = npos;
}
renderer.SetPoint(nv.X, nv.Y);
silentScrollUpdate = false;
}
void restoreFocus(object sender, EventArgs e)
{
if (!this.renderer.Focus())
System.Diagnostics.Debug.WriteLine("focus set failed!");
}
void renderer_UpdateImageSize()
{
horzScroll.Value = 0;
vertScroll.Value = 0;
RecalcuateScroll();
}
void RecalcuateScroll()
{
horzScroll.Enabled = renderer.ImageSize.Width > renderer.Width;
if (horzScroll.Enabled)
{
horzScroll.Maximum = renderer.ImageSize.Width - renderer.Width;
horzScroll.LargeChange = renderer.Width;
if (horzScroll.Value > horzScroll.Maximum)
horzScroll.Value = horzScroll.Maximum;
}
vertScroll.Enabled = renderer.ImageSize.Height > renderer.Height;
if (vertScroll.Enabled)
{
vertScroll.Maximum = renderer.ImageSize.Height - renderer.Height;
vertScroll.LargeChange = renderer.Height;
if (vertScroll.Value > vertScroll.Maximum)
vertScroll.Value = vertScroll.Maximum;
}
}
protected override void OnResize(EventArgs e)
{
renderer.ClientAreaSize = this.ClientSize;
base.OnResize(e);
Refresh();
RecalcuateScroll();
}
void renderer_ChangeShowScroll(bool obj)
{
horzScroll.Visible = obj;
vscPanel.Visible = obj;
RecalcuateScroll();
}
private void vertScroll_Scroll(object sender, ScrollEventArgs e)
{
renderer.YPosition = vertScroll.Value;
}
private void vertScroll_ValueChanged(object sender, EventArgs e)
{
if (silentScrollUpdate) return;
renderer.YPosition = vertScroll.Value;
}
private void horzScroll_Scroll(object sender, ScrollEventArgs e)
{
renderer.XPosition = horzScroll.Value;
}
private void horzScroll_ValueChanged(object sender, EventArgs e)
{
if (silentScrollUpdate) return;
renderer.XPosition = horzScroll.Value;
}
protected override void OnPreviewKeyDown(PreviewKeyDownEventArgs e)
{
switch (e.KeyCode)
{
case Keys.Up:
case Keys.Down:
case Keys.Left:
case Keys.Right:
case Keys.Tab:
case Keys.Enter:
case Keys.Escape:
e.IsInputKey = true;
break;
}
base.OnPreviewKeyDown(e);
}
}
}
| 31.57754 | 136 | 0.527688 | [
"MIT"
] | karno/Typict | Bright/Forms/Main/Docks/PictureView.cs | 5,907 | C# |
using UnityEngine.Experimental.GlobalIllumination;
using Unity.Collections;
namespace UnityEngine.Rendering.HighDefinition
{
class GlobalIlluminationUtils
{
// Return true if the light must be added to the baking
public static bool LightDataGIExtract(Light light, ref LightDataGI lightDataGI)
{
var add = light.GetComponent<HDAdditionalLightData>();
if (add == null)
{
add = HDUtils.s_DefaultHDAdditionalLightData;
}
Cookie cookie;
LightmapperUtils.Extract(light, out cookie);
lightDataGI.cookieID = cookie.instanceID;
lightDataGI.cookieScale = cookie.scale;
// TODO: Currently color temperature is not handled at runtime, need to expose useColorTemperature publicly
Color cct = new Color(1.0f, 1.0f, 1.0f);
#if UNITY_EDITOR
if (add.useColorTemperature)
cct = Mathf.CorrelatedColorTemperatureToRGB(light.colorTemperature);
#endif
// TODO: Only take into account the light dimmer when we have real time GI.
lightDataGI.instanceID = light.GetInstanceID();
LinearColor directColor, indirectColor;
directColor = add.affectDiffuse ? LinearColor.Convert(light.color, light.intensity) : LinearColor.Black();
directColor.red *= cct.r;
directColor.green *= cct.g;
directColor.blue *= cct.b;
indirectColor = add.affectDiffuse ? LightmapperUtils.ExtractIndirect(light) : LinearColor.Black();
indirectColor.red *= cct.r;
indirectColor.green *= cct.g;
indirectColor.blue *= cct.b;
#if UNITY_EDITOR
LightMode lightMode = LightmapperUtils.Extract(light.lightmapBakeType);
#else
LightMode lightMode = LightmapperUtils.Extract(light.bakingOutput.lightmapBakeType);
#endif
lightDataGI.color = directColor;
lightDataGI.indirectColor = indirectColor;
// Note that the HDRI is correctly integrated in the GlobalIllumination system, we don't need to do anything regarding it.
// The difference is that `l.lightmapBakeType` is the intent, e.g.you want a mixed light with shadowmask. But then the overlap test might detect more than 4 overlapping volumes and force a light to fallback to baked.
// In that case `l.bakingOutput.lightmapBakeType` would be baked, instead of mixed, whereas `l.lightmapBakeType` would still be mixed. But this difference is only relevant in editor builds
#if UNITY_EDITOR
lightDataGI.mode = LightmapperUtils.Extract(light.lightmapBakeType);
#else
lightDataGI.mode = LightmapperUtils.Extract(light.bakingOutput.lightmapBakeType);
#endif
lightDataGI.shadow = (byte)(light.shadows != LightShadows.None ? 1 : 0);
HDLightType lightType = add.ComputeLightType(light);
if (lightType != HDLightType.Area)
{
// For HDRP we need to divide the analytic light color by PI (HDRP do explicit PI division for Lambert, but built in Unity and the GI don't for punctual lights)
// We apply it on both direct and indirect are they are separated, seems that direct is no used if we used mixed mode with indirect or shadowmask bake.
lightDataGI.color.intensity /= Mathf.PI;
lightDataGI.indirectColor.intensity /= Mathf.PI;
directColor.intensity /= Mathf.PI;
indirectColor.intensity /= Mathf.PI;
}
switch (lightType)
{
case HDLightType.Directional:
lightDataGI.orientation = light.transform.rotation;
lightDataGI.position = light.transform.position;
lightDataGI.range = 0.0f;
lightDataGI.coneAngle = add.shapeWidth;
lightDataGI.innerConeAngle = add.shapeHeight;
#if UNITY_EDITOR
lightDataGI.shape0 = light.shadows != LightShadows.None ? (Mathf.Deg2Rad * light.shadowAngle) : 0.0f;
#else
lightDataGI.shape0 = 0.0f;
#endif
lightDataGI.shape1 = 0.0f;
lightDataGI.type = UnityEngine.Experimental.GlobalIllumination.LightType.Directional;
lightDataGI.falloff = FalloffType.Undefined;
lightDataGI.coneAngle = add.shapeWidth;
lightDataGI.innerConeAngle = add.shapeHeight;
break;
case HDLightType.Spot:
switch (add.spotLightShape)
{
case SpotLightShape.Cone:
{
SpotLight spot;
spot.instanceID = light.GetInstanceID();
spot.shadow = light.shadows != LightShadows.None;
spot.mode = lightMode;
#if UNITY_EDITOR
spot.sphereRadius = light.shadows != LightShadows.None ? light.shadowRadius : 0.0f;
#else
spot.sphereRadius = 0.0f;
#endif
spot.position = light.transform.position;
spot.orientation = light.transform.rotation;
spot.color = directColor;
spot.indirectColor = indirectColor;
spot.range = light.range;
spot.coneAngle = light.spotAngle * Mathf.Deg2Rad;
spot.innerConeAngle = light.spotAngle * Mathf.Deg2Rad * add.innerSpotPercent01;
spot.falloff = add.applyRangeAttenuation ? FalloffType.InverseSquared : FalloffType.InverseSquaredNoRangeAttenuation;
spot.angularFalloff = AngularFalloffType.AnalyticAndInnerAngle;
lightDataGI.Init(ref spot, ref cookie);
lightDataGI.shape1 = (float)AngularFalloffType.AnalyticAndInnerAngle;
}
break;
case SpotLightShape.Pyramid:
{
SpotLightPyramidShape pyramid;
pyramid.instanceID = light.GetInstanceID();
pyramid.shadow = light.shadows != LightShadows.None;
pyramid.mode = lightMode;
pyramid.position = light.transform.position;
pyramid.orientation = light.transform.rotation;
pyramid.color = directColor;
pyramid.indirectColor = indirectColor;
pyramid.range = light.range;
pyramid.angle = light.spotAngle * Mathf.Deg2Rad;
pyramid.aspectRatio = add.aspectRatio;
pyramid.falloff = add.applyRangeAttenuation ? FalloffType.InverseSquared : FalloffType.InverseSquaredNoRangeAttenuation;
lightDataGI.Init(ref pyramid, ref cookie);
}
break;
case SpotLightShape.Box:
{
SpotLightBoxShape box;
box.instanceID = light.GetInstanceID();
box.shadow = light.shadows != LightShadows.None;
box.mode = lightMode;
box.position = light.transform.position;
box.orientation = light.transform.rotation;
box.color = directColor;
box.indirectColor = indirectColor;
box.range = light.range;
box.width = add.shapeWidth;
box.height = add.shapeHeight;
lightDataGI.Init(ref box, ref cookie);
}
break;
default:
Debug.Assert(false, "Encountered an unknown SpotLightShape.");
break;
}
break;
case HDLightType.Point:
lightDataGI.orientation = light.transform.rotation;
lightDataGI.position = light.transform.position;
lightDataGI.range = light.range;
lightDataGI.coneAngle = 0.0f;
lightDataGI.innerConeAngle = 0.0f;
#if UNITY_EDITOR
lightDataGI.shape0 = light.shadows != LightShadows.None ? light.shadowRadius : 0.0f;
#else
lightDataGI.shape0 = 0.0f;
#endif
lightDataGI.shape1 = 0.0f;
lightDataGI.type = UnityEngine.Experimental.GlobalIllumination.LightType.Point;
lightDataGI.falloff = add.applyRangeAttenuation ? FalloffType.InverseSquared : FalloffType.InverseSquaredNoRangeAttenuation;
break;
case HDLightType.Area:
switch (add.areaLightShape)
{
case AreaLightShape.Rectangle:
lightDataGI.orientation = light.transform.rotation;
lightDataGI.position = light.transform.position;
lightDataGI.range = light.range;
lightDataGI.coneAngle = 0.0f;
lightDataGI.innerConeAngle = 0.0f;
#if UNITY_EDITOR
lightDataGI.shape0 = light.areaSize.x;
lightDataGI.shape1 = light.areaSize.y;
#else
lightDataGI.shape0 = 0.0f;
lightDataGI.shape1 = 0.0f;
#endif
// TEMP: for now, if we bake a rectangle type this will disable the light for runtime, need to speak with GI team about it!
lightDataGI.type = UnityEngine.Experimental.GlobalIllumination.LightType.Rectangle;
lightDataGI.falloff = add.applyRangeAttenuation ? FalloffType.InverseSquared : FalloffType.InverseSquaredNoRangeAttenuation;
lightDataGI.cookieID = add.areaLightCookie ? add.areaLightCookie.GetInstanceID() : 0;
break;
case AreaLightShape.Tube:
lightDataGI.InitNoBake(lightDataGI.instanceID);
break;
case AreaLightShape.Disc:
lightDataGI.orientation = light.transform.rotation;
lightDataGI.position = light.transform.position;
lightDataGI.range = light.range;
lightDataGI.coneAngle = 0.0f;
lightDataGI.innerConeAngle = 0.0f;
#if UNITY_EDITOR
lightDataGI.shape0 = light.areaSize.x;
lightDataGI.shape1 = light.areaSize.y;
#else
lightDataGI.shape0 = 0.0f;
lightDataGI.shape1 = 0.0f;
#endif
// TEMP: for now, if we bake a rectangle type this will disable the light for runtime, need to speak with GI team about it!
lightDataGI.type = UnityEngine.Experimental.GlobalIllumination.LightType.Disc;
lightDataGI.falloff = add.applyRangeAttenuation ? FalloffType.InverseSquared : FalloffType.InverseSquaredNoRangeAttenuation;
lightDataGI.cookieID = add.areaLightCookie ? add.areaLightCookie.GetInstanceID() : 0;
break;
default:
Debug.Assert(false, "Encountered an unknown AreaLightShape.");
break;
}
break;
default:
Debug.Assert(false, "Encountered an unknown LightType.");
break;
}
return true;
}
static public Lightmapping.RequestLightsDelegate hdLightsDelegate = (Light[] requests, NativeArray<LightDataGI> lightsOutput) =>
{
// Get all lights in the scene
LightDataGI lightDataGI = new LightDataGI();
for (int i = 0; i < requests.Length; i++)
{
Light light = requests[i];
// For editor we need to discard realtime light as otherwise we get double contribution
// At runtime for Enlighten we must keep realtime light but we can discard other light as they aren't used.
// The difference is that `l.lightmapBakeType` is the intent, e.g.you want a mixed light with shadowmask. But then the overlap test might detect more than 4 overlapping volumes and force a light to fallback to baked.
// In that case `l.bakingOutput.lightmapBakeType` would be baked, instead of mixed, whereas `l.lightmapBakeType` would still be mixed. But this difference is only relevant in editor builds
#if UNITY_EDITOR
LightDataGIExtract(light, ref lightDataGI);
#else
if (LightmapperUtils.Extract(light.bakingOutput.lightmapBakeType) == LightMode.Realtime)
LightDataGIExtract(light, ref lightDataGI);
else
lightDataGI.InitNoBake(light.GetInstanceID());
#endif
lightsOutput[i] = lightDataGI;
}
};
}
}
| 53.950758 | 233 | 0.534227 | [
"MIT"
] | JesusGarciaValadez/RenderStreamingHDRP | RenderStreamingHDRP/Library/PackageCache/com.unity.render-pipelines.high-definition@8.2.0/Runtime/Lighting/GlobalIlluminationUtils.cs | 14,243 | 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 iotsecuretunneling-2018-10-05.normal.json service model.
*/
using System;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Generic;
using Amazon.Runtime;
using Amazon.IoTSecureTunneling.Model;
namespace Amazon.IoTSecureTunneling
{
/// <summary>
/// Interface for accessing IoTSecureTunneling
///
/// AWS IoT Secure Tunneling
/// <para>
/// AWS IoT Secure Tunnling enables you to create remote connections to devices deployed
/// in the field.
/// </para>
///
/// <para>
/// For more information about how AWS IoT Secure Tunneling works, see <a href="https://docs.aws.amazon.com/iot/latest/developerguide/secure-tunneling.html">AWS
/// IoT Secure Tunneling</a>.
/// </para>
/// </summary>
#if NETSTANDARD13
[Obsolete("Support for .NET Standard 1.3 is in maintenance mode and will only receive critical bug fixes and security patches. Visit https://docs.aws.amazon.com/sdk-for-net/v3/developer-guide/migration-from-net-standard-1-3.html for further details.")]
#endif
public partial interface IAmazonIoTSecureTunneling : IAmazonService, IDisposable
{
#if AWS_ASYNC_ENUMERABLES_API
/// <summary>
/// Paginators for the service
/// </summary>
IIoTSecureTunnelingPaginatorFactory Paginators { get; }
#endif
#region CloseTunnel
/// <summary>
/// Closes a tunnel identified by the unique tunnel id. When a <code>CloseTunnel</code>
/// request is received, we close the WebSocket connections between the client and proxy
/// server so no data can be transmitted.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the CloseTunnel service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the CloseTunnel service method, as returned by IoTSecureTunneling.</returns>
/// <exception cref="Amazon.IoTSecureTunneling.Model.ResourceNotFoundException">
/// Thrown when an operation is attempted on a resource that does not exist.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotsecuretunneling-2018-10-05/CloseTunnel">REST API Reference for CloseTunnel Operation</seealso>
Task<CloseTunnelResponse> CloseTunnelAsync(CloseTunnelRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region DescribeTunnel
/// <summary>
/// Gets information about a tunnel identified by the unique tunnel id.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DescribeTunnel service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the DescribeTunnel service method, as returned by IoTSecureTunneling.</returns>
/// <exception cref="Amazon.IoTSecureTunneling.Model.ResourceNotFoundException">
/// Thrown when an operation is attempted on a resource that does not exist.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotsecuretunneling-2018-10-05/DescribeTunnel">REST API Reference for DescribeTunnel Operation</seealso>
Task<DescribeTunnelResponse> DescribeTunnelAsync(DescribeTunnelRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region ListTagsForResource
/// <summary>
/// Lists the tags for the specified resource.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ListTagsForResource service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the ListTagsForResource service method, as returned by IoTSecureTunneling.</returns>
/// <exception cref="Amazon.IoTSecureTunneling.Model.ResourceNotFoundException">
/// Thrown when an operation is attempted on a resource that does not exist.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotsecuretunneling-2018-10-05/ListTagsForResource">REST API Reference for ListTagsForResource Operation</seealso>
Task<ListTagsForResourceResponse> ListTagsForResourceAsync(ListTagsForResourceRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region ListTunnels
/// <summary>
/// List all tunnels for an AWS account. Tunnels are listed by creation time in descending
/// order, newer tunnels will be listed before older tunnels.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ListTunnels service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the ListTunnels service method, as returned by IoTSecureTunneling.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotsecuretunneling-2018-10-05/ListTunnels">REST API Reference for ListTunnels Operation</seealso>
Task<ListTunnelsResponse> ListTunnelsAsync(ListTunnelsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region OpenTunnel
/// <summary>
/// Creates a new tunnel, and returns two client access tokens for clients to use to connect
/// to the AWS IoT Secure Tunneling proxy server.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the OpenTunnel service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the OpenTunnel service method, as returned by IoTSecureTunneling.</returns>
/// <exception cref="Amazon.IoTSecureTunneling.Model.LimitExceededException">
/// Thrown when a tunnel limit is exceeded.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotsecuretunneling-2018-10-05/OpenTunnel">REST API Reference for OpenTunnel Operation</seealso>
Task<OpenTunnelResponse> OpenTunnelAsync(OpenTunnelRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region TagResource
/// <summary>
/// A resource tag.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the TagResource service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the TagResource service method, as returned by IoTSecureTunneling.</returns>
/// <exception cref="Amazon.IoTSecureTunneling.Model.ResourceNotFoundException">
/// Thrown when an operation is attempted on a resource that does not exist.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotsecuretunneling-2018-10-05/TagResource">REST API Reference for TagResource Operation</seealso>
Task<TagResourceResponse> TagResourceAsync(TagResourceRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region UntagResource
/// <summary>
/// Removes a tag from a resource.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the UntagResource service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the UntagResource service method, as returned by IoTSecureTunneling.</returns>
/// <exception cref="Amazon.IoTSecureTunneling.Model.ResourceNotFoundException">
/// Thrown when an operation is attempted on a resource that does not exist.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotsecuretunneling-2018-10-05/UntagResource">REST API Reference for UntagResource Operation</seealso>
Task<UntagResourceResponse> UntagResourceAsync(UntagResourceRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
}
} | 50.339806 | 256 | 0.670299 | [
"Apache-2.0"
] | philasmar/aws-sdk-net | sdk/src/Services/IoTSecureTunneling/Generated/_netstandard/IAmazonIoTSecureTunneling.cs | 10,370 | 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.
using System;
using System.Linq;
namespace Microsoft.ML.Trainers.FastTree
{
#if USE_SINGLE_PRECISION
using FloatType = System.Single;
#else
using FloatType = System.Double;
#endif
/// <summary>
/// Class to represent statistics of the feature used by LeastSquaresRegressionTreeLearner
/// </summary>
public sealed class FeatureHistogram
{
public readonly FloatType[] SumTargetsByBin;
public readonly double[] SumWeightsByBin;
public readonly int[] CountByBin;
public readonly int NumFeatureValues;
private readonly IntArray _bins;
/// <summary>
/// Make a new FeatureHistogram
/// </summary>
/// <param name="bins">The bins we will be calculating sumups over</param>
/// <param name="numBins">The number of bins, should be at least as large as the number of bins</param>
/// <param name="useWeights">Allocates weights array when true</param>
public FeatureHistogram(IntArray bins, int numBins, bool useWeights)
{
Contracts.AssertValue(bins);
Contracts.Assert(bins.Length == 0 || (0 <= numBins && bins.Max() < numBins));
_bins = bins;
NumFeatureValues = numBins;
SumTargetsByBin = new FloatType[NumFeatureValues];
CountByBin = new int[NumFeatureValues];
if (useWeights)
SumWeightsByBin = new double[NumFeatureValues];
}
/// <summary>
/// This function returns the estimated memory used for a FeatureHistogram object according to given
/// number of bins.
/// </summary>
/// <param name="numBins">number of bins</param>
/// <param name="hasWeights">weights array is counted when true</param>
/// <returns>estimated size of memory used for a feature histogram object</returns>
public static int EstimateMemoryUsedForFeatureHistogram(int numBins, bool hasWeights)
{
return sizeof(int) // NumberFeatureValues
+ sizeof(int) // the IsSplittable boolean value. Although sizeof(bool) is 1,
// but we just estimate it as 4 for alignment
+ 8 // size of reference to _feature in 64 bit machines.
+ sizeof(int) * numBins // CountByBin
+ sizeof(FloatType) * numBins // SumTargetsByBin
+ (hasWeights ? sizeof(double) * numBins : 0); // SumWeightsByBin
}
/// <summary>
/// Subtract from myself the counts of the child histogram
/// </summary>
/// <param name="child">Another histogram to subtract</param>
public unsafe void Subtract(FeatureHistogram child)
{
if (child.NumFeatureValues != NumFeatureValues)
throw Contracts.Except("cannot subtract FeatureHistograms of different lengths");
fixed (FloatType* pSumTargetsByBin = SumTargetsByBin)
fixed (FloatType* pChildSumTargetsByBin = child.SumTargetsByBin)
fixed (double* pSumWeightsByBin = SumWeightsByBin)
fixed (double* pChildSumWeightsByBin = child.SumWeightsByBin)
fixed (int* pTotalCountByBin = CountByBin)
fixed (int* pChildTotalCountByBin = child.CountByBin)
{
if (pSumWeightsByBin == null)
{
for (int i = 0; i < NumFeatureValues; i++)
{
pSumTargetsByBin[i] -= pChildSumTargetsByBin[i];
pTotalCountByBin[i] -= pChildTotalCountByBin[i];
}
}
else
{
Contracts.Assert(pChildSumWeightsByBin != null);
for (int i = 0; i < NumFeatureValues; i++)
{
pSumTargetsByBin[i] -= pChildSumTargetsByBin[i];
pSumWeightsByBin[i] -= pChildSumWeightsByBin[i];
pTotalCountByBin[i] -= pChildTotalCountByBin[i];
}
}
}
}
public void Sumup(int numDocsInLeaf, double sumTargets, FloatType[] outputs, int[] docIndices)
{
SumupWeighted(numDocsInLeaf, sumTargets, 0.0, outputs, null, docIndices);
}
public void SumupWeighted(int numDocsInLeaf, double sumTargets, double sumWeights, FloatType[] outputs, double[] weights, int[] docIndices)
{
using (Timer.Time(TimerEvent.Sumup))
{
#if TLC_REVISION
Array.Clear(SumWeightedTargetsByBin, 0, SumWeightedTargetsByBin.Length);
#else
Array.Clear(SumTargetsByBin, 0, SumTargetsByBin.Length);
#endif
if (SumWeightsByBin != null)
{
Array.Clear(SumWeightsByBin, 0, SumWeightsByBin.Length);
}
Array.Clear(CountByBin, 0, CountByBin.Length);
if (numDocsInLeaf > 0)
{
SumupInputData input = new SumupInputData(
numDocsInLeaf,
sumTargets,
sumWeights,
outputs,
weights,
docIndices);
_bins.Sumup(input, this);
}
}
}
}
public sealed class SumupInputData
{
public int TotalCount;
public double SumTargets;
public readonly FloatType[] Outputs;
public readonly int[] DocIndices;
public double SumWeights;
public readonly double[] Weights;
public SumupInputData(int totalCount, double sumTargets, double sumWeights,
FloatType[] outputs, double[] weights, int[] docIndices)
{
TotalCount = totalCount;
SumTargets = sumTargets;
Outputs = outputs;
DocIndices = docIndices;
SumWeights = sumWeights;
Weights = weights;
}
}
}
| 38.404908 | 147 | 0.572524 | [
"MIT"
] | geffzhang/machinelearning | src/Microsoft.ML.FastTree/Dataset/FeatureHistogram.cs | 6,260 | C# |
//********************************* bs::framework - Copyright 2018-2019 Marko Pintera ************************************//
//*********** Licensed under the MIT license. See LICENSE.md for full terms. This notice is not to be removed. ***********//
using System.Runtime.CompilerServices;
namespace bs
{
/** @addtogroup Utility
* @{
*/
/// <summary>
/// Allows manipulation of the platform cursor.
/// </summary>
public static class Cursor
{
/// <summary>
/// Position of the cursor in screen coordinates.
/// </summary>
public static Vector2I ScreenPosition
{
get
{
Vector2I value;
Internal_GetScreenPosition(out value);
return value;
}
set
{
Internal_SetScreenPosition(ref value);
}
}
/// <summary>
/// Hides the cursor.
/// </summary>
public static void Hide()
{
Internal_Hide();
}
/// <summary>
/// Shows the cursor.
/// </summary>
public static void Show()
{
Internal_Show();
}
/// <summary>
/// Clips the cursor to the specified area. Enabled until <see cref="ClipDisable"/> is called.
/// </summary>
/// <param name="area">Area in screen space to clip the cursor to.</param>
public static void ClipToRect(Rect2I area)
{
Internal_ClipToRect(ref area);
}
/// <summary>
/// Disables cursor clipping previously enabled with <see cref="ClipToRect"/>.
/// </summary>
public static void ClipDisable()
{
Internal_ClipDisable();
}
/// <summary>
/// Changes the active cursor icon.
/// </summary>
/// <param name="name">Name of the cursor icon, previously registered with
/// <see cref="SetCursorIcon(string,PixelData,Vector2I)"/></param>
public static void SetCursor(string name)
{
Internal_SetCursorStr(name);
}
/// <summary>
/// Changes the active cursor icon.
/// </summary>
/// <param name="type">One of the built-in cursor types.</param>
public static void SetCursor(CursorType type)
{
Internal_SetCursor(type);
}
/// <summary>
/// Updates the look of a specific cursor icon.
/// </summary>
/// <param name="name">Name of the cursor.</param>
/// <param name="iconData">Pixel data specifying the new look.</param>
/// <param name="hotspot">Offset into the icon image that determines where the cursor point is.</param>
public static void SetCursorIcon(string name, PixelData iconData, Vector2I hotspot)
{
Internal_SetCursorIconStr(name, iconData, ref hotspot);
}
/// <summary>
/// Updates the look of a specific cursor icon.
/// </summary>
/// <param name="type">One of the built-in cursor types.</param>
/// <param name="iconData">Pixel data specifying the new look.</param>
/// <param name="hotspot">Offset into the icon image that determines where the cursor point is.</param>
public static void SetCursorIcon(CursorType type, PixelData iconData, Vector2I hotspot)
{
Internal_SetCursorIcon(type, iconData, ref hotspot);
}
/// <summary>
/// Removes a cursor icon.
/// </summary>
/// <param name="name">Name of the cursor.</param>
public static void ClearCursorIcon(string name)
{
Internal_ClearCursorIconStr(name);
}
/// <summary>
/// Removes a cursor icon.
/// </summary>
/// <param name="type">One of the built-in cursor types.</param>
public static void ClearCursorIcon(CursorType type)
{
Internal_ClearCursorIcon(type);
}
[MethodImpl(MethodImplOptions.InternalCall)]
private static extern void Internal_GetScreenPosition(out Vector2I value);
[MethodImpl(MethodImplOptions.InternalCall)]
private static extern void Internal_SetScreenPosition(ref Vector2I value);
[MethodImpl(MethodImplOptions.InternalCall)]
private static extern void Internal_Hide();
[MethodImpl(MethodImplOptions.InternalCall)]
private static extern void Internal_Show();
[MethodImpl(MethodImplOptions.InternalCall)]
private static extern void Internal_ClipToRect(ref Rect2I value);
[MethodImpl(MethodImplOptions.InternalCall)]
private static extern void Internal_ClipDisable();
[MethodImpl(MethodImplOptions.InternalCall)]
private static extern void Internal_SetCursorStr(string name);
[MethodImpl(MethodImplOptions.InternalCall)]
private static extern void Internal_SetCursor(CursorType cursor);
[MethodImpl(MethodImplOptions.InternalCall)]
private static extern void Internal_SetCursorIconStr(string name, PixelData iconData, ref Vector2I hotspot);
[MethodImpl(MethodImplOptions.InternalCall)]
private static extern void Internal_SetCursorIcon(CursorType cursor, PixelData iconData, ref Vector2I hotspot);
[MethodImpl(MethodImplOptions.InternalCall)]
private static extern void Internal_ClearCursorIconStr(string name);
[MethodImpl(MethodImplOptions.InternalCall)]
private static extern void Internal_ClearCursorIcon(CursorType cursor);
}
/// <summary>
/// Built-in cursor types.
/// </summary>
public enum CursorType //Note: Must match C++ enum CursorType
{
Arrow,
ArrowDrag,
ArrowLeftRight,
Wait,
IBeam,
SizeNESW,
SizeNS,
SizeNWSE,
SizeWE,
Deny,
// Keep at the end
Count
};
/** @} */
}
| 32.275676 | 125 | 0.592866 | [
"MIT"
] | Alan-love/bsf | Source/Scripting/bsfSharp/Utility/Cursor.cs | 5,973 | 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.DataBoxEdge.Models
{
/// <summary>
/// Defines values for DataPolicy.
/// </summary>
public static class DataPolicy
{
public const string Cloud = "Cloud";
public const string Local = "Local";
}
}
| 27.26087 | 74 | 0.69059 | [
"MIT"
] | 0rland0Wats0n/azure-sdk-for-net | sdk/databoxedge/Microsoft.Azure.Management.DataBoxEdge/src/Generated/Models/DataPolicy.cs | 627 | C# |
using System;
using System.Windows.Controls;
namespace Wpf.Docs
{
public partial class EnumComboBoxControl : UserControl
{
public EnumComboBoxControl()
{
InitializeComponent();
this.DataContext = new FlagEnumComboBoxControlVM();
}
}
}
| 19.8 | 63 | 0.632997 | [
"MIT"
] | jonnypjohnston/Xarial-xtoolk | docs/_src/wpf/FlagEnumComboBoxControl.xaml.cs | 299 | C# |
using Microsoft.Crm.Sdk.Messages;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Messages;
using Microsoft.Xrm.Sdk.Query;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Linq;
using Xrm.Framework.CI.Common.Entities;
using Xrm.Framework.CI.Common.Logging;
namespace Xrm.Framework.CI.Common
{
public class SolutionManager : XrmBase
{
#region Variables
private const string ImportSuccess = "success";
private const string ImportFailure = "failure";
private const string ImportProcessed = "processed";
private const string ImportUnprocessed = "Unprocessed";
#endregion
#region Properties
protected IOrganizationService PollingOrganizationService
{
get;
set;
}
#endregion
#region Constructors
public SolutionManager(ILogger logger,
IOrganizationService organizationService,
IOrganizationService pollingOrganizationService)
:base(logger, organizationService)
{
PollingOrganizationService = pollingOrganizationService;
}
#endregion
#region Methods
public SolutionImportResult ImportSolution(
string solutionFilePath,
bool publishWorkflows,
bool convertToManaged,
bool overwriteUnmanagedCustomizations,
bool skipProductUpdateDependencies,
bool holdingSolution,
bool overrideSameVersion,
bool importAsync,
int sleepInterval,
int asyncWaitTimeout,
Guid? importJobId,
bool downloadFormattedLog,
string logDirectory,
string logFileName
)
{
Logger.LogInformation("Importing Solution: {0}", solutionFilePath);
if (!importJobId.HasValue || importJobId.Value == Guid.Empty)
{
importJobId = Guid.NewGuid();
}
Logger.LogVerbose("ImportJobId {0}", importJobId);
if (asyncWaitTimeout == 0)
{
asyncWaitTimeout = 15 * 60;
}
Logger.LogVerbose("AsyncWaitTimeout: {0}", asyncWaitTimeout);
if (sleepInterval == 0)
{
sleepInterval = 15;
}
Logger.LogVerbose("SleepInterval: {0}", sleepInterval);
if (!File.Exists(solutionFilePath))
{
Logger.LogError("Solution File does not exist: {0}", solutionFilePath);
throw new FileNotFoundException("Solution File does not exist", solutionFilePath);
}
SolutionImportResult result = null;
SolutionXml solutionXml = new SolutionXml(Logger);
XrmSolutionInfo info = solutionXml.GetSolutionInfoFromZip(solutionFilePath);
if (info == null)
{
result = new SolutionImportResult()
{
ErrorMessage = "Invalid Solution File"
};
return result;
}
else
{
Logger.LogInformation("Solution Unique Name: {0}, Version: {1}",
info.UniqueName,
info.Version);
}
bool skipImport = SkipImport(info, holdingSolution, overrideSameVersion);
if (skipImport)
{
Logger.LogInformation("Solution Import Skipped");
result = new SolutionImportResult()
{
Success = true,
ImportSkipped = true
};
result.SolutionName = info.UniqueName;
result.VersionNumber = info.Version;
return result;
}
if (downloadFormattedLog)
{
if (string.IsNullOrEmpty(logFileName))
{
logFileName = $"ImportLog_{Path.GetFileNameWithoutExtension(solutionFilePath)}_{DateTime.Now.ToString("yyyy_MM_dd__HH_mm")}.xml";
Logger.LogVerbose("Setting logFileName to {0}", logFileName);
}
if (string.IsNullOrEmpty(logDirectory))
{
logDirectory = Path.GetDirectoryName(solutionFilePath);
Logger.LogVerbose("Settings logDirectory to {0}", logDirectory);
}
if (!Directory.Exists(logDirectory))
{
Logger.LogError("logDirectory not exist: {0}", logDirectory);
throw new DirectoryNotFoundException("logDirectory does not exist");
}
}
byte[] solutionBytes = File.ReadAllBytes(solutionFilePath);
var importSolutionRequest = new ImportSolutionRequest
{
CustomizationFile = solutionBytes,
PublishWorkflows = publishWorkflows,
ConvertToManaged = convertToManaged,
OverwriteUnmanagedCustomizations = overwriteUnmanagedCustomizations,
SkipProductUpdateDependencies = skipProductUpdateDependencies,
ImportJobId = importJobId.Value,
RequestId = importJobId,
HoldingSolution = holdingSolution
};
if (importAsync)
{
Logger.LogVerbose(string.Format("Importing solution in Async Mode"));
var asyncRequest = new ExecuteAsyncRequest
{
Request = importSolutionRequest
};
var asyncResponse = OrganizationService.Execute(asyncRequest) as ExecuteAsyncResponse;
Guid asyncJobId = asyncResponse.AsyncJobId;
Logger.LogVerbose("Awaiting for Async Operation Completion");
AsyncUpdateHandler updateHandler = new AsyncUpdateHandler(
Logger, PollingOrganizationService, importJobId.Value);
AsyncOperationManager operationManager
= new AsyncOperationManager(Logger, PollingOrganizationService);
AsyncOperation asyncOperation = operationManager.AwaitCompletion(
asyncJobId,
asyncWaitTimeout,
sleepInterval,
updateHandler);
Logger.LogInformation("Async Operation completed with status: {0}",
((AsyncOperation_StatusCode)asyncOperation.StatusCode.Value).ToString());
Logger.LogInformation("Async Operation completed with message: {0}",
asyncOperation.Message);
result = VerifySolutionImport(importAsync,
importJobId.Value,
asyncOperation,
null);
}
else
{
Logger.LogVerbose("Importing solution in Sync Mode");
SyncImportHandler importHandler = new SyncImportHandler(
Logger,
OrganizationService,
importSolutionRequest);
ImportJobHandler jobHandler = new ImportJobHandler(
Logger,
OrganizationService,
importHandler);
Logger.LogVerbose("Creating Import Task");
Action importAction = () => importHandler.ImportSolution();
Task importTask = new Task(importAction);
Logger.LogVerbose("Starting Import Task");
importTask.Start();
Logger.LogVerbose("Thread Started. Starting to Query Import Status");
ImportJobManager jobManager = new ImportJobManager(Logger, PollingOrganizationService);
jobManager.AwaitImportJob(importJobId.Value, asyncWaitTimeout, sleepInterval, true, jobHandler);
importTask.Wait();
result = VerifySolutionImport(importAsync,
importJobId.Value,
null,
importHandler.Error);
}
result.SolutionName = info.UniqueName;
result.VersionNumber = info.Version;
if (result.ImportJobAvailable && downloadFormattedLog)
{
ImportJobManager jobManager = new ImportJobManager(Logger, OrganizationService);
jobManager.SaveFormattedLog(importJobId.Value, logDirectory, logFileName);
}
if (result.Success)
{
Logger.LogInformation("Solution Import Completed Successfully");
}
else
{
Logger.LogInformation("Solution Import Failed");
}
return result;
}
public SolutionImportResult ImportSolution(
string importFolder,
string logsFolder,
SolutionImportOptions options)
{
SolutionImportResult importResult = ImportSolution(
$"{importFolder}\\{options.SolutionFilePath}",
options.PublishWorkflows,
options.ConvertToManaged,
options.OverwriteUnmanagedCustomizations,
options.SkipProductUpdateDependencies,
options.HoldingSolution,
options.OverrideSameVersion,
options.ImportAsync,
options.SleepInterval,
options.AsyncWaitTimeout,
Guid.NewGuid(),
true,
logsFolder,
string.Empty);
if (importResult.Success &&
options.ApplySolution)
{
SolutionApplyResult applyResult = ApplySolution(
importResult.SolutionName,
options.ApplyAsync,
options.SleepInterval,
options.AsyncWaitTimeout);
importResult.Success = applyResult.Success;
importResult.ErrorMessage = applyResult.ErrorMessage;
}
return importResult;
}
public List<SolutionImportResult> ImportSolutions(
string importFolder,
string logsFolder,
SolutionImportConfig config)
{
List<SolutionImportResult> results = new List<SolutionImportResult>();
foreach (SolutionImportOptions option in config.Solutions)
{
results.Add(ImportSolution(
importFolder,
logsFolder,
option));
}
return results;
}
public List<SolutionImportResult> ImportSolutions(
string logsFolder,
string configFilePath)
{
if (!Directory.Exists(logsFolder))
{
throw new Exception($"{logsFolder} does not exist");
}
if (!File.Exists(configFilePath))
{
throw new Exception($"{configFilePath} does not exist");
}
Logger.LogVerbose("Parsing import json file {0}", configFilePath);
SolutionImportConfig config =
Serializers.ParseJson<SolutionImportConfig>(configFilePath);
Logger.LogVerbose("Finished parsing import json file {0}", configFilePath);
Logger.LogVerbose("{0} solution for import found", config.Solutions.Count);
FileInfo configInfo = new FileInfo(configFilePath);
List<SolutionImportResult> results = ImportSolutions(
configInfo.Directory.FullName,
logsFolder,
config);
return results;
}
public SolutionApplyResult ApplySolution(
string solutionName,
bool importAsync,
int sleepInterval,
int asyncWaitTimeout
)
{
Logger.LogVerbose("Upgrading Solution: {0}", solutionName);
if (SkipUpgrade(solutionName))
{
return new SolutionApplyResult()
{
Success = true,
ApplySkipped = true
};
}
Exception syncApplyException = null;
AsyncOperation asyncOperation = null;
var upgradeSolutionRequest = new DeleteAndPromoteRequest
{
UniqueName = solutionName
};
if (importAsync)
{
var asyncRequest = new ExecuteAsyncRequest
{
Request = upgradeSolutionRequest
};
Logger.LogVerbose("Applying using Async Mode");
var asyncResponse = OrganizationService.Execute(asyncRequest) as ExecuteAsyncResponse;
Guid asyncJobId = asyncResponse.AsyncJobId;
Logger.LogInformation(string.Format("Async JobId: {0}", asyncJobId));
Logger.LogVerbose("Awaiting for Async Operation Completion");
AsyncOperationManager asyncOperationManager = new AsyncOperationManager(
Logger, PollingOrganizationService);
asyncOperation = asyncOperationManager.AwaitCompletion(
asyncJobId, asyncWaitTimeout, sleepInterval, null);
Logger.LogInformation("Async Operation completed with status: {0}",
((AsyncOperation_StatusCode)asyncOperation.StatusCode.Value).ToString());
Logger.LogInformation("Async Operation completed with message: {0}",
asyncOperation.Message);
}
else
{
try
{
OrganizationService.Execute(upgradeSolutionRequest);
}
catch (Exception ex)
{
syncApplyException = ex;
}
}
SolutionApplyResult result = VerifyUpgrade(
solutionName,
asyncOperation,
syncApplyException);
if (result.Success)
{
Logger.LogInformation("Solution Apply Completed Successfully");
}
else
{
Logger.LogInformation("Solution Apply Failed");
}
return result;
}
public Solution GetSolution(string uniqueName, ColumnSet columns)
{
Logger.LogVerbose("Retrieving solution '{0}'", uniqueName);
QueryByAttribute queryByAttribute = new QueryByAttribute();
queryByAttribute.EntityName = Solution.EntityLogicalName;
queryByAttribute.ColumnSet = columns;
queryByAttribute.Attributes.Add("uniquename");
queryByAttribute.Values.Add(uniqueName);
EntityCollection results = OrganizationService.RetrieveMultiple(queryByAttribute);
if (results.Entities.Count == 0)
{
return null;
}
else
{
return results.Entities[0].ToEntity<Solution>();
}
}
public Solution GetSolution(Guid Id, ColumnSet columns)
{
if (columns == null)
{
columns = new ColumnSet();
}
Solution solution = OrganizationService.Retrieve(Solution.EntityLogicalName,
Id, columns).ToEntity<Solution>();
return solution;
}
public void DeleteSolution(string uniqueName)
{
Solution solution = GetSolution(uniqueName, new ColumnSet());
if (solution == null)
{
Logger.LogWarning("Solution '{0}' was not found", uniqueName);
}
else
{
Logger.LogVerbose("Deleting solution '{0}'", uniqueName);
OrganizationService.Delete(Solution.EntityLogicalName,
solution.Id);
Logger.LogInformation("Solution '{0}' was deleted", uniqueName);
}
}
public List<Solution> GetSolutionPatches(string uniqueName)
{
Solution parent = GetSolution(uniqueName, new ColumnSet());
if (parent is null)
{
throw new Exception(string.Format("{0} solution can't be found", uniqueName));
}
Logger.LogVerbose("Retrieving patches for solution {0}", uniqueName);
using (var context = new CIContext(OrganizationService))
{
var query = from s in context.SolutionSet
where s.ParentSolutionId.Id == parent.Id
orderby s.Version descending
select s;
List<Solution> solutions = query.ToList<Solution>();
return solutions;
}
}
public Solution CreatePatch(string uniqueName,
string versionNumber,
string displayName)
{
using (var context = new CIContext(OrganizationService))
{
if (string.IsNullOrEmpty(versionNumber))
{
Logger.LogVerbose("VersionNumber not supplied. Generating default VersionNumber");
var solution = (from sol in context.SolutionSet
where sol.UniqueName == uniqueName || sol.UniqueName.StartsWith(uniqueName + "_Patch")
orderby sol.Version descending
select new Solution { Version = sol.Version, FriendlyName = sol.FriendlyName }).FirstOrDefault();
if (solution == null || string.IsNullOrEmpty(solution.Version))
{
throw new Exception(string.Format("Parent solution with unique name {0} not found.", uniqueName));
}
string[] versions = solution.Version.Split('.');
char dot = '.';
versionNumber = string.Concat(versions[0], dot, versions[1], dot, Convert.ToInt32(versions[2]) + 1, dot, 0);
Logger.LogVerbose("New VersionNumber: {0}", versionNumber);
}
if (string.IsNullOrEmpty(displayName))
{
Logger.LogVerbose("displayName not supplied. Generating default DisplayName");
var solution = (from sol in context.SolutionSet
where sol.UniqueName == uniqueName
select new Solution { FriendlyName = sol.FriendlyName }).FirstOrDefault();
if (solution == null || string.IsNullOrEmpty(solution.FriendlyName))
{
throw new Exception(string.Format("Parent solution with unique name {0} not found.", uniqueName));
}
displayName = solution.FriendlyName;
}
var cloneAsPatch = new CloneAsPatchRequest
{
DisplayName = displayName,
ParentSolutionUniqueName = uniqueName,
VersionNumber = versionNumber,
};
CloneAsPatchResponse response = OrganizationService.Execute(cloneAsPatch) as CloneAsPatchResponse;
Logger.LogInformation("Patch solution created with Id {0}", response.SolutionId);
Solution patch = GetSolution(response.SolutionId, new ColumnSet(true));
Logger.LogInformation("Patch solution name: {0}", patch.UniqueName);
return patch;
}
}
public Solution CloneSolution(string uniqueName,
string versionNumber,
string displayName)
{
using (var context = new CIContext(OrganizationService))
{
var solution = (from sol in context.SolutionSet
where sol.UniqueName == uniqueName
select new Solution { Version = sol.Version, FriendlyName = sol.FriendlyName }).FirstOrDefault();
if (solution == null || string.IsNullOrEmpty(solution.Version))
{
throw new Exception(string.Format("Parent solution with unique name {0} not found.", uniqueName));
}
if (string.IsNullOrEmpty(versionNumber))
{
Logger.LogVerbose("VersionNumber not supplied. Generating default VersionNumber");
string[] versions = solution.Version.Split('.');
char dot = '.';
versionNumber = string.Concat(versions[0], dot, Convert.ToInt32(versions[1]) + 1, dot, versions[2], dot, versions[3]);
Logger.LogVerbose("New version number {0}", versionNumber);
}
if (string.IsNullOrEmpty(displayName))
{
Logger.LogVerbose("displayName not supplied. Generating default displayName");
displayName = solution.FriendlyName;
}
var cloneAsPatch = new CloneAsSolutionRequest
{
DisplayName = displayName,
ParentSolutionUniqueName = uniqueName,
VersionNumber = versionNumber,
};
CloneAsSolutionResponse response =
OrganizationService.Execute(cloneAsPatch) as CloneAsSolutionResponse;
Logger.LogInformation("Clone solution created with Id {0}", response.SolutionId);
Solution clone = GetSolution(response.SolutionId, new ColumnSet(true));
Logger.LogInformation("Clone solution name: {0}", clone.UniqueName);
return clone;
}
}
public Solution CreateSolution(string publisherUniqueName,
string uniqueName,
string displayName,
string description,
string versionNumber)
{
Logger.LogVerbose("Searching for Publisher: {0}", publisherUniqueName);
QueryByAttribute queryPublishers = new QueryByAttribute("publisher");
queryPublishers.Attributes.Add("uniquename");
queryPublishers.ColumnSet = new ColumnSet(true);
queryPublishers.Values.Add(publisherUniqueName);
EntityCollection publishers = OrganizationService.RetrieveMultiple(queryPublishers);
Logger.LogVerbose("# of Publishers found: {0}", publishers.Entities.Count);
if (publishers.Entities.Count != 1)
{
throw new Exception(string.Format("Unique Publisher with name '{0}' was not found", publisherUniqueName));
}
Entity publisher = publishers[0];
Logger.LogVerbose("Publisher Located Display Name: {0}, Id: {1}", publisher.Attributes["friendlyname"], publisher.Id);
Logger.LogVerbose("Creating Solution");
Solution newSolution = new Solution();
newSolution.UniqueName = uniqueName;
newSolution.FriendlyName = displayName;
newSolution.Version = versionNumber;
newSolution.Description = description;
newSolution.PublisherId = publisher.ToEntityReference();
Guid solutionId = OrganizationService.Create(newSolution);
Logger.LogVerbose("Solution Created with Id: {0}", solutionId);
return GetSolution(solutionId, new ColumnSet(true));
}
public string ExportSolution(
string outputFolder,
SolutionExportOptions options)
{
Logger.LogVerbose("Exporting Solution: {0}", options.SolutionName);
var solutionFile = new StringBuilder();
Solution solution = GetSolution(options.SolutionName,
new ColumnSet("version"));
solutionFile.Append(options.SolutionName);
if (options.IncludeVersionInName)
{
solutionFile.Append("_");
solutionFile.Append(solution.Version.Replace(".", "_"));
}
if (options.Managed)
{
solutionFile.Append("_managed");
}
solutionFile.Append(".zip");
var exportSolutionRequest = new ExportSolutionRequest
{
Managed = options.Managed,
SolutionName = options.SolutionName,
ExportAutoNumberingSettings = options.ExportAutoNumberingSettings,
ExportCalendarSettings = options.ExportCalendarSettings,
ExportCustomizationSettings = options.ExportCustomizationSettings,
ExportEmailTrackingSettings = options.ExportEmailTrackingSettings,
ExportGeneralSettings = options.ExportGeneralSettings,
ExportIsvConfig = options.ExportIsvConfig,
ExportMarketingSettings = options.ExportMarketingSettings,
ExportOutlookSynchronizationSettings = options.ExportOutlookSynchronizationSettings,
ExportRelationshipRoles = options.ExportRelationshipRoles,
ExportSales = options.ExportSales,
TargetVersion = options.TargetVersion,
ExportExternalApplications = options.ExportExternalApplications
};
var exportSolutionResponse = OrganizationService.Execute(exportSolutionRequest) as ExportSolutionResponse;
string solutionFilePath = Path.Combine(outputFolder, solutionFile.ToString());
File.WriteAllBytes(solutionFilePath, exportSolutionResponse.ExportSolutionFile);
return solutionFilePath;
}
public List<string> ExportSolutions(
string outputFolder,
SolutionExportConfig config)
{
List<string> solutionFilePaths = new List<string>();
foreach (SolutionExportOptions option in config.Solutions)
{
solutionFilePaths.Add(ExportSolution(outputFolder,
option));
}
return solutionFilePaths;
}
public List<string> ExportSolutions(
string outputFolder,
string configFilePath)
{
SolutionExportConfig config =
Serializers.ParseJson<SolutionExportConfig>(configFilePath);
List<string> solutionFilePaths = ExportSolutions(outputFolder,
config);
return solutionFilePaths;
}
public void UpdateVersion(
string solutionName,
string version)
{
Logger.LogVerbose("Updating Solution {0} Version: {1}", solutionName, version);
Solution solution = GetSolution(solutionName, new ColumnSet());
if (solution == null)
{
throw new Exception(string.Format("Solution {0} could not be found", solutionName));
}
var update = new Solution
{
Id = solution.Id,
Version = version
};
OrganizationService.Update(update);
Logger.LogInformation("Solution {0} version updated to : {1}", solutionName, version);
}
#endregion
#region Private Methods
private bool SkipImport(
XrmSolutionInfo info,
bool holdingSolution,
bool overrideSameVersion)
{
bool skip = false;
ColumnSet columns = new ColumnSet("version");
var baseSolution = GetSolution(info.UniqueName, columns);
if (baseSolution == null)
{
Logger.LogInformation("{0} not currently installed.", info.UniqueName);
}
else
{
Logger.LogInformation("{0} currently installed with version: {1}", info.UniqueName, baseSolution.Version);
}
if (baseSolution == null ||
overrideSameVersion ||
(info.Version != baseSolution.Version))
{
skip = false;
}
else
{
return true;
}
if (holdingSolution)
{
string upgradeName = $"{info.UniqueName}_Upgrade";
var upgradeSolution = GetSolution(upgradeName, columns);
if (upgradeSolution == null)
{
Logger.LogInformation("{0} not currently installed.", upgradeName);
skip = false;
}
else
{
Logger.LogInformation("{0} currently installed with version: {1}", upgradeName, info.Version);
skip = true;
}
}
return skip;
}
private bool SkipUpgrade(
string solutionName)
{
string upgradeName = $"{solutionName}_Upgrade";
var upgradeSolution = GetSolution(upgradeName, new ColumnSet("version"));
if (upgradeSolution == null)
{
Logger.LogInformation("Skipping Upgrade. {0} not currently installed.", upgradeName);
return true;
}
else
{
Logger.LogInformation("{0} currently installed with version: {1}", upgradeName, upgradeSolution.Version);
return false;
}
}
private SolutionImportResult VerifySolutionImport(
bool importAsync,
Guid importJobId,
AsyncOperation asyncOperation,
Exception syncImportException)
{
SolutionImportResult result = new SolutionImportResult();
Logger.LogVerbose("Verifying Solution Import");
ImportJobManager jobManager = new ImportJobManager(Logger, OrganizationService);
ImportJob importJob = jobManager.GetImportJob(
importJobId,
new ColumnSet("importjobid", "completedon", "progress", "data"));
if (importJob == null)
{
result.ImportJobAvailable = false;
if (importAsync)
{
result.ErrorMessage = asyncOperation != null ? asyncOperation.Message : "";
}
else
{
result.ErrorMessage = syncImportException != null ? syncImportException.Message : "";
}
Logger.LogError("Can't verify as import job couldn't be found. Error Message: {0}",
result.ErrorMessage);
return result;
}
else
{
result.ImportJobAvailable = true;
}
if (importJob.Progress == 100)
{
Logger.LogInformation("Completed Progress: {0}", importJob.Progress);
}
else
{
Logger.LogWarning("Completed Progress: {0}", importJob.Progress);
}
Logger.LogInformation("Completed On: {0}", importJob.CompletedOn);
XmlDocument doc = new XmlDocument();
doc.LoadXml(importJob.Data);
XmlNode resultNode = doc.SelectSingleNode("//solutionManifest/result/@result");
String solutionImportResult = resultNode != null ? resultNode.Value : null;
Logger.LogInformation("Import Result: {0}", solutionImportResult);
XmlNode errorNode = doc.SelectSingleNode("//solutionManifest/result/@errortext");
String solutionImportError = errorNode != null ? errorNode.Value : null;
Logger.LogInformation("Import Error: {0}", solutionImportError);
result.ErrorMessage = solutionImportError;
XmlNodeList unprocessedNodes = doc.SelectNodes("//*[@processed=\"false\"]");
result.UnprocessedComponents = unprocessedNodes.Count;
if (unprocessedNodes.Count > 0)
{
Logger.LogWarning("Total number of unprocessed components: {0}", unprocessedNodes.Count);
}
else
{
Logger.LogInformation("Total number of unprocessed components: {0}", unprocessedNodes.Count);
}
result.Success = solutionImportResult == ImportSuccess;
if (importAsync)
{
result.Success = result.Success && asyncOperation.StatusCodeEnum == AsyncOperation_StatusCode.Succeeded;
}
return result;
}
private SolutionApplyResult VerifyUpgrade(
string solutionName,
AsyncOperation asyncOperation,
Exception syncApplyException)
{
SolutionApplyResult result = new SolutionApplyResult();
if (asyncOperation != null)
{
if ((AsyncOperation_StatusCode)asyncOperation.StatusCode.Value
!= AsyncOperation_StatusCode.Succeeded)
{
result.Success = false;
result.ErrorMessage = asyncOperation.Message;
return result;
}
}
if (syncApplyException != null)
{
result.Success = false;
result.ErrorMessage = syncApplyException.Message;
return result;
}
string upgradeName = solutionName + "_Upgrade";
Solution solution = GetSolution(upgradeName, new ColumnSet());
Logger.LogVerbose("Retrieving Solution: {0}", upgradeName);
if (solution != null)
{
result.Success = false;
result.ErrorMessage = string.Format("Solution still exists after upgrade: {0}", upgradeName);
return result;
}
else
{
result.Success = true;
Logger.LogVerbose("Apply Upgrade completed: {0}", upgradeName);
return result;
}
}
#endregion
}
#region Helper Classes
public class SolutionImportResult
{
#region Properties
public string SolutionName { get; set; }
public string VersionNumber { get; set; }
public bool Success { get; set; }
public string ErrorMessage { get; set; }
public int UnprocessedComponents { get; set; }
public bool ImportJobAvailable { get; set; }
public bool ImportSkipped { get; set; }
#endregion
#region Constructor
public SolutionImportResult()
{
Success = false;
ErrorMessage = "";
UnprocessedComponents = -1;
ImportJobAvailable = false;
ImportSkipped = false;
}
#endregion
}
public class SolutionApplyResult
{
#region Properties
public bool Success { get; set; }
public string ErrorMessage { get; set; }
public bool ApplySkipped { get; set; }
#endregion
#region Constructor
public SolutionApplyResult()
{
Success = false;
ApplySkipped = false;
ErrorMessage = "";
}
#endregion
}
public class XrmSolutionInfo
{
public string UniqueName { get; set; }
public string Version { get; set; }
}
class SyncImportHandler : XrmBase
{
#region Properties
private ImportSolutionRequest ImportRequest
{
get;
set;
}
public Exception Error
{
get;
set;
}
#endregion
#region Constructors
public SyncImportHandler(
ILogger logger,
IOrganizationService organizationService,
ImportSolutionRequest importRequest)
: base(logger, organizationService)
{
ImportRequest = importRequest;
}
#endregion
#region Methods
public void ImportSolution()
{
try
{
OrganizationService.Execute(ImportRequest);
}
catch (Exception ex)
{
Error = ex;
}
}
#endregion
}
class AsyncUpdateHandler : XrmBase, IAsyncStatusUpdate
{
#region Properties
private Guid ImportJobId
{
get;
set;
}
#endregion
#region Constructors
public AsyncUpdateHandler(
ILogger logger,
IOrganizationService organizationService,
Guid importJobId)
: base(logger, organizationService)
{
ImportJobId = importJobId;
}
#endregion
#region IAsyncStatusUpdate
public void OnProgressUpdate(AsyncOperation asyncOperation)
{
if (asyncOperation.StatusCode.Value == (int)AsyncOperation_StatusCode.InProgress)
{
ImportJobManager jobManager
= new ImportJobManager(Logger, OrganizationService);
ImportJob importJob = jobManager.GetImportJob(ImportJobId,
new ColumnSet("importjobid", "completedon", "progress"));
if (importJob != null)
{
Logger.LogVerbose("Import Job Progress: {0}", importJob.Progress);
}
else
{
Logger.LogVerbose("Import job not found with Id: {0}", ImportJobId);
}
}
}
#endregion
}
class ImportJobHandler : XrmBase, IJobStatusUpdate
{
#region Properties
private SyncImportHandler ImportHandler
{
get;
set;
}
#endregion
#region Constructors
public ImportJobHandler(
ILogger logger,
IOrganizationService organizationService,
SyncImportHandler importHandler)
: base(logger, organizationService)
{
ImportHandler = importHandler;
}
#endregion
#region IJobStatusUpdate
public bool OnProgressUpdate(ImportJob importJob)
{
Logger.LogVerbose("Checking Sync Import Status");
if (importJob == null && ImportHandler.Error != null)
{
Logger.LogVerbose("Execute Failed and Import Job couldn't be found");
Logger.LogVerbose("Execute Request Error: {0}", ImportHandler.Error.Message);
return false;
}
return true;
}
#endregion
}
public class SolutionExportConfig
{
#region Properties
public List<SolutionExportOptions> Solutions { get; set; }
#endregion
#region Constructors
public SolutionExportConfig()
{
Solutions = new List<SolutionExportOptions>();
}
#endregion
}
public class SolutionExportOptions
{
#region Properties
public string SolutionName { get; set; }
public bool Managed { get; set; }
public string TargetVersion { get; set; }
public bool ExportAutoNumberingSettings { get; set; }
public bool ExportCalendarSettings { get; set; }
public bool ExportCustomizationSettings { get; set; }
public bool ExportEmailTrackingSettings { get; set; }
public bool ExportExternalApplications { get; set; }
public bool ExportGeneralSettings { get; set; }
public bool ExportIsvConfig { get; set; }
public bool ExportMarketingSettings { get; set; }
public bool ExportOutlookSynchronizationSettings { get; set; }
public bool ExportRelationshipRoles { get; set; }
public bool ExportSales { get; set; }
public bool IncludeVersionInName { get; set; }
#endregion
#region Constructors
public SolutionExportOptions()
{
}
#endregion
}
public class SolutionImportOptions
{
#region Properties
public string SolutionFilePath { get; set; }
public bool PublishWorkflows { get; set; }
public bool ConvertToManaged { get; set; }
public bool OverwriteUnmanagedCustomizations { get; set; }
public bool SkipProductUpdateDependencies { get; set; }
public bool HoldingSolution { get; set; }
public bool OverrideSameVersion { get; set; }
public bool ImportAsync { get; set; }
public bool ApplySolution { get; set; }
public bool ApplyAsync { get; set; }
public int SleepInterval { get; set; }
public int AsyncWaitTimeout { get; set; }
#endregion
#region Constructors
public SolutionImportOptions()
{
SleepInterval = 15;
AsyncWaitTimeout = 15 * 60;
ImportAsync = true;
}
#endregion
}
public class SolutionImportConfig
{
#region Properties
public List<SolutionImportOptions> Solutions { get; set; }
#endregion
#region Constructors
public SolutionImportConfig()
{
Solutions = new List<SolutionImportOptions>();
}
#endregion
}
#endregion
}
| 32.929017 | 149 | 0.549283 | [
"MIT"
] | broszkiet/xrm-ci-framework | MSDYNV9/Xrm.Framework.CI/Xrm.Framework.CI.Common/SolutionManagement/SolutionManager.cs | 42,217 | C# |
// Visual Studio Shared Project
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// 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.IO;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Python.Tests.Utilities;
namespace TestUtilities {
public static class TestData {
private static readonly AsyncLocal<TestRunScope> TestRunScopeAsyncLocal = new AsyncLocal<TestRunScope>();
private static string GetRootDir() {
var dir = PathUtils.GetParent(typeof(TestData).Assembly.Location);
while (!string.IsNullOrEmpty(dir) &&
Directory.Exists(dir) &&
!File.Exists(PathUtils.GetAbsoluteFilePath(dir, "build.root"))) {
dir = PathUtils.GetParent(dir);
}
return dir ?? "";
}
/// <summary>
/// Returns the full path to the test data root.
/// </summary>
private static string CalculateTestDataRoot() {
var path = Environment.GetEnvironmentVariable("_TESTDATA_ROOT_PATH");
if (Directory.Exists(path)) {
return path;
}
path = GetRootDir();
if (Directory.Exists(path)) {
foreach (var landmark in new[] {
"TestData",
Path.Combine("src", "UnitTests", "TestData")
}) {
var candidate = PathUtils.GetAbsoluteDirectoryPath(path, landmark);
if (Directory.Exists(candidate)) {
return PathUtils.GetParent(candidate);
}
}
}
throw new InvalidOperationException("Failed to find test data");
}
private static readonly Lazy<string> RootLazy = new Lazy<string>(CalculateTestDataRoot);
public static string Root => RootLazy.Value;
public static string GetDefaultTypeshedPath() {
var asmPath = Assembly.GetExecutingAssembly().GetAssemblyPath();
return Path.Combine(Path.GetDirectoryName(asmPath), "Typeshed");
}
public static Uri GetDefaultModuleUri() => new Uri(GetDefaultModulePath());
public static Uri GetNextModuleUri() => new Uri(GetNextModulePath());
public static Uri[] GetNextModuleUris(int count) {
var uris = new Uri[count];
for (var i = 0; i < count; i++) {
uris[i] = GetNextModuleUri();
}
return uris;
}
public static Uri GetTestSpecificUri(string relativePath) => new Uri(GetTestSpecificPath(relativePath));
public static Uri GetTestSpecificUri(params string[] parts) => new Uri(GetTestSpecificPath(parts));
public static Uri GetTestSpecificRootUri() => TestRunScopeAsyncLocal.Value.RootUri;
public static string GetTestSpecificPath(string relativePath) => TestRunScopeAsyncLocal.Value.GetTestSpecificPath(relativePath);
public static string GetTestSpecificPath(params string[] parts) => TestRunScopeAsyncLocal.Value.GetTestSpecificPath(Path.Combine(parts));
public static string GetTestRelativePath(Uri uri) => TestRunScopeAsyncLocal.Value.GetTestRelativePath(uri);
public static string GetDefaultModulePath() => TestRunScopeAsyncLocal.Value.GetDefaultModulePath();
public static string GetNextModulePath() => TestRunScopeAsyncLocal.Value.GetNextModulePath();
public static string GetAstAnalysisCachePath(Version version, bool testSpecific = false)
=> testSpecific ? TestRunScopeAsyncLocal.Value.GetTestSpecificPath($"AstAnalysisCache{version}") : GetTestOutputRootPath($"AstAnalysisCache{version}");
public static async Task<Uri> CreateTestSpecificFileAsync(string relativePath, string content) {
var path = GetTestSpecificPath(relativePath);
Directory.CreateDirectory(Path.GetDirectoryName(path));
using (var stream = File.Create(path)) {
var contentBytes = Encoding.Default.GetBytes(content);
await stream.WriteAsync(contentBytes, 0, contentBytes.Length);
}
return new Uri(path);
}
/// <summary>
/// Returns the full path to the deployed file.
/// </summary>
public static string GetPath(params string[] paths) {
var res = Root;
foreach (var p in paths) {
res = PathUtils.GetAbsoluteFilePath(res, p);
}
return res;
}
private static string CalculateTestOutputRoot() {
var path = Environment.GetEnvironmentVariable("_TESTDATA_TEMP_PATH");
if (string.IsNullOrEmpty(path)) {
path = Path.Combine(GetRootDir(), "TestResults", DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss"));
}
if (!Directory.Exists(path)) {
Directory.CreateDirectory(path);
}
return path;
}
private static readonly Lazy<string> TestOutputRootLazy = new Lazy<string>(CalculateTestOutputRoot);
/// <summary>
/// Returns the full path to a temporary directory in the test output root.
/// This is within the deployment to ensure that test files are easily cleaned up.
/// </summary>
private static string GetTestOutputRootPath(string subPath = null) {
var path = PathUtils.GetAbsoluteDirectoryPath(TestOutputRootLazy.Value, subPath);
if (!Directory.Exists(path)) {
Directory.CreateDirectory(path);
}
Console.WriteLine($"Creating temp directory for test at {path}");
return path;
}
internal static void SetTestRunScope(string testFullName) {
var testDirectoryName = testFullName ?? Path.GetRandomFileName();
var path = Path.Combine(TestOutputRootLazy.Value, testDirectoryName);
Directory.CreateDirectory(path);
TestRunScopeAsyncLocal.Value = new TestRunScope(PathUtils.EnsureEndSeparator(path));
}
internal static void ClearTestRunScope() {
TestRunScopeAsyncLocal.Value = null;
}
}
internal class TestRunScope {
private readonly string _root;
private int _moduleCounter;
public Uri RootUri { get; }
public TestRunScope(string root) {
_root = root;
RootUri = new Uri(_root);
}
public string GetDefaultModulePath() => GetTestSpecificPath($"module.py");
public string GetNextModulePath() => GetTestSpecificPath($"module{++_moduleCounter}.py");
public string GetTestSpecificPath(string relativePath) => Path.Combine(_root, relativePath);
public string GetTestRelativePath(Uri uri) {
var relativeUri = RootUri.MakeRelativeUri(uri);
var relativePath = Uri.UnescapeDataString(relativeUri.ToString());
return relativePath.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar);
}
}
}
| 43.432584 | 163 | 0.640926 | [
"Apache-2.0"
] | brianbok/python-language-server | src/UnitTests/Core/Impl/TestData.cs | 7,733 | C# |
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Websites.Data;
namespace Websites.Api
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<WebsitesDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("WebsitesDatabase")));
services.AddScoped<WebsitesDbContext>();
services.AddScoped<WebsiteRepository>();
services.AddControllers();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}
| 29.603774 | 106 | 0.62269 | [
"MIT"
] | GeorgiPetrovGH/.Net-core-WebAPI-project | Source/Websites/Websites.Api/Startup.cs | 1,569 | C# |
using FSH.WebApi.Domain.Common.Events;
namespace FSH.WebApi.Application.Catalog.Products.EventHandlers;
public class ProductDeletedEventHandler : IEventNotificationHandler<EntityDeletedEvent<Product>>
{
private readonly ILogger<ProductDeletedEventHandler> _logger;
public ProductDeletedEventHandler(ILogger<ProductDeletedEventHandler> logger) => _logger = logger;
public Task Handle(EventNotification<EntityDeletedEvent<Product>> notification, CancellationToken cancellationToken)
{
_logger.LogInformation("{event} Triggered", notification.Event.GetType().Name);
return Task.CompletedTask;
}
} | 39.5625 | 120 | 0.797788 | [
"MIT"
] | DevJr14/dotnet-webapi-boilerplate | src/Core/Application/Catalog/Products/EventHandlers/ProductDeletedEventHandler.cs | 633 | C# |
using System;
namespace Device.Net
{
/// <summary>
/// Represents the definition of a device that has been physically connected and has a DeviceId
/// </summary>
public class ConnectedDeviceDefinition : ConnectedDeviceDefinitionBase
{
#region Public Methods
public string DeviceId { get; set; }
#endregion
#region Constructor
public ConnectedDeviceDefinition(string deviceId)
{
if(string.IsNullOrEmpty(deviceId))
{
throw new ArgumentNullException(nameof(deviceId));
}
DeviceId = deviceId;
}
#endregion
}
} | 24.518519 | 99 | 0.601208 | [
"MIT"
] | boek/Device.Net | src/Device.Net/ConnectedDeviceDefinition.cs | 664 | C# |
using My.AspNetCore.WebForms.Rendering;
using System;
using System.IO;
using System.Text.Encodings.Web;
using System.Threading.Tasks;
namespace My.AspNetCore.WebForms.Controls
{
public class Image : Control
{
public string AlternateText { get; set; }
public string DescriptionUrl { get; set; }
public ImageAlign ImageAlign { get; set; }
public string ImageUrl { get; set; }
public async override Task RenderAsync(TextWriter writer)
{
var tagBuilder = new TagBuilder("img")
{
TagRenderMode = TagRenderMode.Normal
};
tagBuilder.Attributes.Add("alt", AlternateText);
tagBuilder.Attributes.Add("src", ImageUrl);
if (!String.IsNullOrEmpty(DescriptionUrl))
{
tagBuilder.Attributes.Add("longdesc", DescriptionUrl);
}
if (ImageAlign != ImageAlign.NotSet)
{
tagBuilder.Attributes.Add("align", ImageAlign.ToString().ToLower());
}
tagBuilder.WriteTo(writer, HtmlEncoder.Default);
await Task.CompletedTask;
}
}
}
| 26.886364 | 84 | 0.590871 | [
"MIT"
] | hishamco/WebForms | src/My.AspNetCore.WebForms/Controls/image.cs | 1,185 | C# |
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace JiraWebApi
{
/// <summary>
/// Fields meta information.
/// </summary>
[Serializable]
public sealed class Fields : ISerializable
{
/// <summary>
/// Initializes a new instance of the Fields class.
/// </summary>
private Fields()
{ }
/// <summary>
/// Initializes a new instance of the Fields class by serialization.
/// </summary>
/// <param name="info">The System.Runtime.Serialization.SerializationInfo to populate with data.</param>
/// <param name="context">The destination (see System.Runtime.Serialization.StreamingContext) for this serialization.</param>
private Fields(SerializationInfo info, StreamingContext context)
{
int i = 1;
Dictionary<string, FieldMeta> metaFields = new Dictionary<string, FieldMeta>();
foreach (SerializationEntry entry in info)
{
JObject obj = entry.Value as JObject;
FieldMeta fieldMeta = null;
Trace.WriteLine(string.Format("entry {0} : {1} ", i++, entry.Name));
fieldMeta = obj.ToObject<FieldMeta>();
metaFields.Add(entry.Name, fieldMeta);
}
this.MetaFields = metaFields;
}
/// <summary>
/// Not supported.
/// </summary>
/// <param name="info">The System.Runtime.Serialization.SerializationInfo to populate with data.</param>
/// <param name="context">The destination (see System.Runtime.Serialization.StreamingContext) for this serialization.</param>
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
throw new NotSupportedException();
}
/// <summary>
/// Meta fields.
/// </summary>
public IDictionary<string, FieldMeta> MetaFields { get; set; }
}
}
| 34.396825 | 133 | 0.601754 | [
"MIT"
] | Bassman2/JiraWebApi | JiraWebApi/Fields.cs | 2,169 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.