Here are the examples of the csharp api System.Reflection.Assembly.GetExecutingAssembly() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
5881 Examples
19
Source : Program.cs
with MIT License
from 0ffffffffh
with MIT License
from 0ffffffffh
static void Main(string[] args)
{
Process apache=null, backend=null, sbmon=null;
List<Process> memcachedInsts = null;
appExePath = System.Reflection.replacedembly.GetExecutingreplacedembly().Location;
appWorkDir = Path.GetDirectoryName(appExePath);
CheckAdminRights();
var procList = Process.GetProcesses();
foreach (var proc in procList)
{
if (stricmp(proc.ProcessName, "httpd") == 0)
{
Log("Httpd still running");
apache = proc;
}
else if (stricmp(proc.ProcessName, "sozluk_backend") == 0)
{
Log("Backend process still running");
backend = proc;
}
else if (stricmp(proc.ProcessName, "sbmon") == 0)
{
Log("Sbmon still running");
sbmon = proc;
}
else if (stricmp(proc.ProcessName, "memcached") == 0)
{
Log("A memcached instance found");
if (memcachedInsts == null)
memcachedInsts = new List<Process>();
memcachedInsts.Add(proc);
}
}
if (apache == null)
{
Log("starting httpd");
Run(HttpdExePath,string.Empty);
}
if (backend==null)
{
if (sbmon != null)
{
Log("there is no backend but sbmon. Sbmon killing");
sbmon.Kill();
}
if (memcachedInsts!=null)
{
Log("There some memcached instances. Killing em");
foreach (var mcp in memcachedInsts)
{
mcp.Kill();
}
}
Log("Starting up backend");
Run(BackendExePath, string.Empty);
}
Console.ReadKey();
}
19
Source : Config.cs
with MIT License
from 0ffffffffh
with MIT License
from 0ffffffffh
public static Config Get()
{
string key, val;
string[] optLines;
string workDir = Path.GetDirectoryName(replacedembly.GetExecutingreplacedembly().Location);
if (!File.Exists(workDir + "\\.config"))
return conf;
if (conf != null)
return conf;
conf = new Config();
optLines = File.ReadAllLines(workDir + "\\.config");
if (optLines == null)
return conf;
foreach (var item in optLines)
{
var part = item.Split(new char[] { '=' }, StringSplitOptions.RemoveEmptyEntries);
if (part != null && part.Length == 2)
{
key = part[0].Trim();
val = part[1].Trim();
switch (key)
{
case "memcached_port":
conf.MemcachedPort = TryConv<int>(val, 11211);
break;
case "memcached_path":
conf.MemcachedPath = val;
break;
case "sbmon_path":
conf.SbmonPath = val;
break;
case "log_level":
conf.LogLevel = TryConv<int>(val, (int)LogType.Critical);
break;
case "dbpwd":
conf.DbPreplacedword = val;
break;
case "test_mode":
conf.TestMode = TryConv<bool>(val, true);
break;
case "html_replacedet_root":
conf.HtmlContentRoot = val;
break;
case "cacheset_salt":
conf.CacheSetSalt = val;
break;
case "records_per_page":
conf.RecordCountPerPage = TryConv<int>(val, 40);
break;
case "basliks_per_page":
conf.BaslikCountPerPage = TryConv<int>(val, 15);
break;
}
}
}
optLines = null;
return conf;
}
19
Source : Ribbon.cs
with GNU General Public License v3.0
from 0dteam
with GNU General Public License v3.0
from 0dteam
private static string GetResourceText(string resourceName)
{
replacedembly asm = replacedembly.GetExecutingreplacedembly();
string[] resourceNames = asm.GetManifestResourceNames();
for (int i = 0; i < resourceNames.Length; ++i)
{
if (string.Compare(resourceName, resourceNames[i], StringComparison.OrdinalIgnoreCase) == 0)
{
using (StreamReader resourceReader = new StreamReader(asm.GetManifestResourceStream(resourceNames[i])))
{
if (resourceReader != null)
{
return resourceReader.ReadToEnd();
}
}
}
}
return null;
}
19
Source : TerrariaHooksManager.cs
with MIT License
from 0x0ade
with MIT License
from 0x0ade
public static void Init() {
if (Initialized)
return;
Initialized = true;
Manager = new DetourModManager();
Manager.Ignored.Add(replacedembly.GetExecutingreplacedembly());
// Load the cecil module generator.
// Adding this more than once shouldn't hurt.
HookEndpointManager.OnGenerateCecilModule += GenerateCecilModule;
// Some mods might forget to undo their hooks.
HookOnUnloadContent = new Hook(
typeof(Mod).GetMethod("UnloadContent", BindingFlags.NonPublic | BindingFlags.Instance),
typeof(TerrariaHooksManager).GetMethod("OnUnloadContent", BindingFlags.NonPublic | BindingFlags.Static)
);
// All of our own hooks need to be undone last.
MethodBase m_Unload = typeof(ModLoader).GetMethod("Unload", BindingFlags.NonPublic | BindingFlags.Static);
if (m_Unload != null) {
HookOnUnloadAll = new Hook(
m_Unload,
typeof(TerrariaHooksManager).GetMethod("OnUnloadAll", BindingFlags.NonPublic | BindingFlags.Static)
);
} else {
/* The unofficial tML x64 form is a hot mess of tML 0.10 and 0.11 pre-beta.
* As such, mods are only unloaded when they're reloaded.
* Luckily, ModContnet.Unload runs right after unloading all mods.
* Even more luckily, it pretty much shares the same signature as the old Unload method.
*/
MethodBase m_UnloadContent =
typeof(Mod).replacedembly.GetType("Terraria.ModLoader.ModContent")
?.GetMethod("Unload", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static);
if (m_UnloadContent != null) {
HookOnUnloadAll = new Hook(
m_UnloadContent,
typeof(TerrariaHooksManager).GetMethod("OnUnloadAll", BindingFlags.NonPublic | BindingFlags.Static)
);
} else {
throw new Exception("Incompatible tML version: Can't find unload hook point");
}
}
// Try to hook the logger to avoid logging "silent" exceptions thrown by TerrariaHooks.
MethodBase m_LogSilentException =
typeof(Mod).replacedembly.GetType("Terraria.ModLoader.ModCompile+<>c")
?.GetMethod("<ActivateExceptionReporting>b__15_0", BindingFlags.NonPublic | BindingFlags.Instance);
if (m_LogSilentException != null) {
HookOnLogSilentException = new Hook(
m_LogSilentException,
typeof(TerrariaHooksManager).GetMethod("OnLogSilentException", BindingFlags.NonPublic | BindingFlags.Static)
);
}
}
19
Source : Program.cs
with MIT License
from 0x0ade
with MIT License
from 0x0ade
static void Main(string[] args) {
// Required for the relative extra paths to work properly.
if (!File.Exists("MonoMod.RuntimeDetour.dll"))
Environment.CurrentDirectory = Path.GetDirectoryName(replacedembly.GetExecutingreplacedembly().Location);
string inputDir, outputDir;
if (args.Length != 2 ||
!Directory.Exists(inputDir = args[0]) ||
!Directory.Exists(outputDir = args[1])) {
Console.Error.WriteLine("Usage: inputdir outputdir");
return;
}
// Check that the files exist.
if (!VerifyFile(out string inputXNA, inputDir, "Terraria.XNA.exe"))
return;
if (!VerifyFile(out string inputFNA, inputDir, "Terraria.FNA.exe"))
return;
// Strip or copy.
foreach (string path in Directory.GetFiles(inputDir)) {
if (!path.EndsWith(".exe") && !path.EndsWith(".dll")) {
Console.WriteLine($"Copying: {path}");
File.Copy(path, Path.Combine(outputDir, Path.GetFileName(path)));
continue;
}
Console.WriteLine($"Stripping: {path}");
Stripper.Strip(path);
}
// Generate hooks.
string hooksXNA = Path.Combine(outputDir, "Windows.Pre.dll");
string hooksFNA = Path.Combine(outputDir, "Mono.Pre.dll");
GenHooks(inputXNA, hooksXNA);
GenHooks(inputFNA, hooksFNA);
// Merge generated .dlls and MonoMod into one .dll per environment.
string[] extrasMod = {
"TerrariaHooks.dll",
"MonoMod.exe",
"MonoMod.RuntimeDetour.dll",
"MonoMod.Utils.dll"
};
Repack(hooksXNA, extrasMod, Path.Combine(outputDir, "Windows.dll"), "TerrariaHooks.dll");
File.Delete(hooksXNA);
Repack(hooksFNA, extrasMod, Path.Combine(outputDir, "Mono.dll"), "TerrariaHooks.dll");
File.Delete(hooksFNA);
}
19
Source : cMain.cs
with MIT License
from 0xPh0enix
with MIT License
from 0xPh0enix
[STAThread]
static void Main()
{
replacedembly aASM = replacedembly.GetExecutingreplacedembly();
using (Stream sResStream = aASM.GetManifestResourceStream("%RES_NAME%"))
{
if (sResStream == null)
return;
byte[] bFile = new byte[sResStream.Length];
sResStream.Read(bFile, 0, bFile.Length);
bFile = Decrypt(bFile, System.Text.Encoding.Default.GetBytes("%ENC_KEY%"));
replacedembly.Load(bFile).EntryPoint.Invoke(null, null);
}
}
19
Source : Program.cs
with BSD 3-Clause "New" or "Revised" License
from 0xthirteen
with BSD 3-Clause "New" or "Revised" License
from 0xthirteen
static void Main(string[] args)
{
AppDomain.CurrentDomain.replacedemblyResolve += (sender, argtwo) => {
replacedembly thisreplacedembly = replacedembly.GetEntryreplacedembly();
String resourceName = string.Format("SharpRDP.{0}.dll.bin",
new replacedemblyName(argtwo.Name).Name);
var replacedembly = replacedembly.GetExecutingreplacedembly();
using (var rs = replacedembly.GetManifestResourceStream(resourceName))
using (var zs = new DeflateStream(rs, CompressionMode.Decompress))
using (var ms = new MemoryStream())
{
zs.CopyTo(ms);
return replacedembly.Load(ms.ToArray());
}
};
var arguments = new Dictionary<string, string>();
foreach (string argument in args)
{
int idx = argument.IndexOf('=');
if (idx > 0)
arguments[argument.Substring(0, idx)] = argument.Substring(idx + 1);
}
string username = string.Empty;
string domain = string.Empty;
string preplacedword = string.Empty;
string command = string.Empty;
string execElevated = string.Empty;
string execw = "";
bool connectdrive = false;
bool takeover = false;
bool nla = false;
if (arguments.ContainsKey("username"))
{
if (!arguments.ContainsKey("preplacedword"))
{
Console.WriteLine("[X] Error: A preplacedword is required");
return;
}
else
{
if (arguments["username"].Contains("\\"))
{
string[] tmp = arguments["username"].Split('\\');
domain = tmp[0];
username = tmp[1];
}
else
{
domain = ".";
username = arguments["username"];
}
preplacedword = arguments["preplacedword"];
}
}
if (arguments.ContainsKey("preplacedword") && !arguments.ContainsKey("username"))
{
Console.WriteLine("[X] Error: A username is required");
return;
}
if ((arguments.ContainsKey("computername")) && (arguments.ContainsKey("command")))
{
Client rdpconn = new Client();
command = arguments["command"];
if (arguments.ContainsKey("exec"))
{
if (arguments["exec"].ToLower() == "cmd")
{
execw = "cmd";
}
else if (arguments["exec"].ToLower() == "powershell" || arguments["exec"].ToLower() == "ps")
{
execw = "powershell";
}
}
if (arguments.ContainsKey("elevated"))
{
if(arguments["elevated"].ToLower() == "true" || arguments["elevated"].ToLower() == "win+r" || arguments["elevated"].ToLower() == "winr")
{
execElevated = "winr";
}
else if(arguments["elevated"].ToLower() == "taskmgr" || arguments["elevated"].ToLower() == "taskmanager")
{
execElevated = "taskmgr";
}
else
{
execElevated = string.Empty;
}
}
if (arguments.ContainsKey("connectdrive"))
{
if(arguments["connectdrive"].ToLower() == "true")
{
connectdrive = true;
}
}
if (arguments.ContainsKey("takeover"))
{
if (arguments["takeover"].ToLower() == "true")
{
takeover = true;
}
}
if (arguments.ContainsKey("nla"))
{
if (arguments["nla"].ToLower() == "true")
{
nla = true;
}
}
string[] computerNames = arguments["computername"].Split(',');
foreach (string server in computerNames)
{
rdpconn.CreateRdpConnection(server, username, domain, preplacedword, command, execw, execElevated, connectdrive, takeover, nla);
}
}
else
{
HowTo();
return;
}
}
19
Source : RedumpProvider.cs
with MIT License
from 13xforever
with MIT License
from 13xforever
public async Task<HashSet<DiscKeyInfo>> EnumerateAsync(string discKeyCachePath, string ProductCode, CancellationToken cancellationToken)
{
var result = new HashSet<DiscKeyInfo>();
try
{
var replacedembly = replacedembly.GetExecutingreplacedembly();
var embeddedResources = replacedembly.GetManifestResourceNames().Where(n => n.Contains("Disc_Keys") || n.Contains("Disc Keys")).ToList();
if (embeddedResources.Any())
Log.Trace("Loading embedded redump keys");
else
Log.Warn("No embedded redump keys found");
foreach (var res in embeddedResources)
{
using var resStream = replacedembly.GetManifestResourceStream(res);
using var zip = new ZipArchive(resStream, ZipArchiveMode.Read);
foreach (var zipEntry in zip.Entries.Where(e => e.Name.EndsWith(".dkey", StringComparison.InvariantCultureIgnoreCase)
|| e.Name.EndsWith(".key", StringComparison.InvariantCultureIgnoreCase)))
{
using var keyStream = zipEntry.Open();
using var memStream = new MemoryStream();
await keyStream.CopyToAsync(memStream, cancellationToken).ConfigureAwait(false);
var discKey = memStream.ToArray();
if (zipEntry.Length > 256/8*2)
{
Log.Warn($"Disc key size is too big: {discKey} ({res}/{zipEntry.FullName})");
continue;
}
if (discKey.Length > 16)
{
discKey = Encoding.UTF8.GetString(discKey).TrimEnd().ToByteArray();
}
try
{
result.Add(new DiscKeyInfo(null, discKey, zipEntry.FullName, KeyType.Redump, discKey.ToHexString()));
}
catch (Exception e)
{
Log.Warn(e, $"Invalid disc key format: {discKey}");
}
}
}
if (result.Any())
Log.Info($"Found {result.Count} embedded redump keys");
else
Log.Warn($"Failed to load any embedded redump keys");
}
catch (Exception e)
{
Log.Error(e, "Failed to load embedded redump keys");
}
Log.Trace("Loading cached redump keys");
var diff = result.Count;
try
{
if (Directory.Exists(discKeyCachePath))
{
var matchingDiskKeys = Directory.GetFiles(discKeyCachePath, "*.dkey", SearchOption.TopDirectoryOnly)
.Concat(Directory.GetFiles(discKeyCachePath, "*.key", SearchOption.TopDirectoryOnly));
foreach (var dkeyFile in matchingDiskKeys)
{
try
{
try
{
var discKey = File.ReadAllBytes(dkeyFile);
if (discKey.Length > 16)
{
try
{
discKey = Encoding.UTF8.GetString(discKey).TrimEnd().ToByteArray();
}
catch (Exception e)
{
Log.Warn(e, $"Failed to convert {discKey.ToHexString()} from hex to binary");
}
}
result.Add(new DiscKeyInfo(null, discKey, dkeyFile, KeyType.Redump, discKey.ToString()));
}
catch (InvalidDataException)
{
File.Delete(dkeyFile);
continue;
}
catch (Exception e)
{
Log.Warn(e);
continue;
}
}
catch (Exception e)
{
Log.Warn(e, e.Message);
}
}
}
}
catch (Exception ex)
{
Log.Warn(ex, "Failed to load redump keys from local cache");
}
diff = result.Count - diff;
Log.Info($"Found {diff} cached disc keys");
return result;
}
19
Source : Program.cs
with MIT License
from 2881099
with MIT License
from 2881099
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
MiniblinkPInvoke.Resourcereplacedemblys.Add("FreeSqlTools", System.Reflection.replacedembly.GetExecutingreplacedembly());
MiniblinkPInvoke.PageNameSpace = "FreeSqlTools.Pages";
Curd.InitFreeSql();
Application.Run(new FrWebMain());
}
19
Source : Utils.cs
with GNU General Public License v3.0
from 2dust
with GNU General Public License v3.0
from 2dust
public static string GetEmbedText(string res)
{
string result = string.Empty;
try
{
replacedembly replacedembly = replacedembly.GetExecutingreplacedembly();
using (Stream stream = replacedembly.GetManifestResourceStream(res))
using (StreamReader reader = new StreamReader(stream))
{
result = reader.ReadToEnd();
}
}
catch (Exception ex)
{
SaveLog(ex.Message, ex);
}
return result;
}
19
Source : Program.cs
with GNU Affero General Public License v3.0
from 3CORESec
with GNU Affero General Public License v3.0
from 3CORESec
public static void LoadConfig(Options o)
{
//Write all the blah blah
var replacedembly = replacedembly.GetExecutingreplacedembly();
var resourceStream = replacedembly.GetManifestResourceStream("S2AN.config.json");
StreamReader reader = new StreamReader(resourceStream);
var config = JsonConvert.DeserializeObject<JObject>(reader.ReadToEnd());
Console.WriteLine($"\n S2AN by 3CORESec - {config["repo_url"]}\n");
//Load default configuration for ATT&CK technique and tactic mismatch search
if (o.MitreMatrix == null)
{
o.MitreMatrix = config["category_matrix_url"]?.ToString();
}
}
19
Source : ServiceCollectionExtension.cs
with Apache License 2.0
from 42skillz
with Apache License 2.0
from 42skillz
public static IServiceCollection AddSwaggerGeneration(this IServiceCollection services, OpenApiContact apiContact, string swaggerreplacedle, Type callerType)
{
return services.AddSwaggerGen(options =>
{
// Resolve the temporary IApiVersionDescriptionProvider service
var provider = services.BuildServiceProvider().GetRequiredService<IApiVersionDescriptionProvider>();
// Add a swagger doreplacedent for each discovered API version
foreach (var description in provider.ApiVersionDescriptions)
{
options.SwaggerDoc(description.GroupName, new OpenApiInfo
{
replacedle = swaggerreplacedle + $" {description.ApiVersion}",
Version = description.ApiVersion.ToString(),
Contact = apiContact
});
}
// Add a custom filter for setting the default values
options.OperationFilter<SwaggerDefaultValues>();
// Tells swagger to pick up the output XML doreplacedent file
options.IncludeXmlComments(Path.Combine(Path.GetDirectoryName(replacedembly.GetExecutingreplacedembly().Location), $"{callerType.replacedembly.GetName().Name}.xml"));
});
}
19
Source : Startup.cs
with Apache License 2.0
from 42skillz
with Apache License 2.0
from 42skillz
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc()
.SetCompatibilityVersion(CompatibilityVersion.Version_3_0)
.AddMvcOptions(o => o.EnableEndpointRouting = false);
services.AddControllers()
.AddNewtonsoftJson(options =>
{
options.SerializerSettings.Converters.Add(new StringEnumConverter());
});
services.AddVersioning();
var auditoriumLayoutRepository = new AuditoriumLayoutRepository();
services.AddSingleton<IProvideAuditoriumLayouts>(auditoriumLayoutRepository);
var openApiContact = new OpenApiContact
{
Name = ApiContactName,
Email = ApiContactEmail
};
var swaggerreplacedle = $"{GetType().replacedembly.GetCustomAttribute<replacedemblyProductAttribute>().Product}";
services.AddSwaggerGen(o =>
o.IncludeXmlComments(
$"{Path.Combine(AppContext.BaseDirectory, replacedembly.GetExecutingreplacedembly().GetName().Name)}.xml"));
services.AddSwaggerGeneration(openApiContact, swaggerreplacedle, GetType());
}
19
Source : AuditoriumLayoutRepository.cs
with Apache License 2.0
from 42skillz
with Apache License 2.0
from 42skillz
private static string GetExecutingreplacedemblyDirectoryFullPath()
{
var directoryName = Path.GetDirectoryName(replacedembly.GetExecutingreplacedembly().CodeBase);
if (directoryName.StartsWith(@"file:\"))
{
directoryName = directoryName.Substring(6);
}
if (directoryName.StartsWith(@"file:/"))
{
directoryName = directoryName.Substring(5);
}
return directoryName;
}
19
Source : Startup.cs
with Apache License 2.0
from 42skillz
with Apache License 2.0
from 42skillz
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc()
.SetCompatibilityVersion(CompatibilityVersion.Version_3_0)
.AddMvcOptions(o => o.EnableEndpointRouting = false);
services.AddControllers()
.AddNewtonsoftJson(options =>
{
options.SerializerSettings.Converters.Add(new StringEnumConverter());
});
services.AddVersioning();
var reservationsProvider = new ReservationsProvider();
services.AddSingleton<IProvideCurrentReservations>(reservationsProvider);
var openApiContact = new OpenApiContact
{
Name = ApiContactName,
Email = ApiContactEmail
};
var swaggerreplacedle = $"{GetType().replacedembly.GetCustomAttribute<replacedemblyProductAttribute>().Product}";
services.AddSwaggerGen(o =>
o.IncludeXmlComments(
$"{Path.Combine(AppContext.BaseDirectory, replacedembly.GetExecutingreplacedembly().GetName().Name)}.xml"));
services.AddSwaggerGeneration(openApiContact, swaggerreplacedle, GetType());
}
19
Source : Startup.cs
with Apache License 2.0
from 42skillz
with Apache License 2.0
from 42skillz
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc()
.SetCompatibilityVersion(CompatibilityVersion.Version_3_0)
.AddMvcOptions(o => o.EnableEndpointRouting = false);
services.AddControllers()
.AddNewtonsoftJson(options =>
{
options.SerializerSettings.Converters.Add(new StringEnumConverter());
});
services.AddVersioning();
ConfigureRightSidePortsAndAdapters(services);
var openApiContact = new OpenApiContact
{
Name = ApiContactName,
Email = ApiContactEmail
};
var swaggerreplacedle = $"{GetType().replacedembly.GetCustomAttribute<replacedemblyProductAttribute>().Product}";
services.AddSwaggerGen(o =>
o.IncludeXmlComments(
$"{Path.Combine(AppContext.BaseDirectory, replacedembly.GetExecutingreplacedembly().GetName().Name)}.xml"));
services.AddSwaggerGeneration(openApiContact, swaggerreplacedle, GetType());
}
19
Source : AuditoriumLayoutRepository.cs
with Apache License 2.0
from 42skillz
with Apache License 2.0
from 42skillz
private static string GetExecutingreplacedemblyDirectoryFullPath()
{
var directoryName = Path.GetDirectoryName(replacedembly.GetExecutingreplacedembly().Location);
if (directoryName != null && directoryName.StartsWith(@"file:\"))
{
directoryName = directoryName.Substring(6);
}
if (directoryName != null && directoryName.StartsWith(@"file:/"))
{
directoryName = directoryName.Substring(5);
}
return directoryName;
}
19
Source : ReservationsProvider.cs
with Apache License 2.0
from 42skillz
with Apache License 2.0
from 42skillz
private static string GetExecutingreplacedemblyDirectoryFullPath()
{
var directoryName = Path.GetDirectoryName(replacedembly.GetExecutingreplacedembly().Location);
if (directoryName != null && directoryName.StartsWith(@"file:\"))
{
directoryName = directoryName.Substring(6);
}
if (directoryName.StartsWith(@"file:/"))
{
directoryName = directoryName.Substring(5);
}
return directoryName;
}
19
Source : ResponsePacketProcessor.cs
with MIT License
from 499116344
with MIT License
from 499116344
public IPacketCommand Process()
{
var receivePackageCommandAttributes = _receivePacketType.GetCustomAttributes<ReceivePacketCommand>();
if (receivePackageCommandAttributes.Any())
{
var packetCommand = receivePackageCommandAttributes.First().Command;
var types = replacedembly.GetExecutingreplacedembly().GetTypes();
foreach (var type in types)
{
var attributes = type.GetCustomAttributes<ResponsePacketCommand>();
if (!attributes.Any())
{
continue;
}
var responseCommand = attributes.First().Command;
if (responseCommand == packetCommand)
{
return Activator.CreateInstance(type, _args) as IPacketCommand;
}
}
}
return new DefaultResponseCommand(new QQEventArgs<ReceivePacket>(_args.Service, _args.User,
_args.ReceivePacket));
}
19
Source : ReceivePacket.cs
with MIT License
from 499116344
with MIT License
from 499116344
internal void TlvExecutionProcessing(ICollection<Tlv> tlvs)
{
if (_tlvTypes == null)
{
var types = replacedembly.GetExecutingreplacedembly().GetTypes();
_tlvTypes = new Dictionary<int, Type>();
foreach (var type in types)
{
var attributes = type.GetCustomAttributes();
if (!attributes.Any(attr => attr is TlvTagAttribute))
{
continue;
}
var attribute = attributes.First(attr => attr is TlvTagAttribute) as TlvTagAttribute;
_tlvTypes.Add((int) attribute.Tag, type);
}
}
foreach (var tlv in tlvs)
{
if (_tlvTypes.ContainsKey(tlv.Tag))
{
var tlvClreplaced = replacedembly.GetExecutingreplacedembly().CreateInstance(_tlvTypes[tlv.Tag].FullName, true);
var methodinfo = _tlvTypes[tlv.Tag].GetMethod("Parser_Tlv");
methodinfo.Invoke(tlvClreplaced, new object[] { User, Reader });
}
}
}
19
Source : DispatchPacketToCommand.cs
with MIT License
from 499116344
with MIT License
from 499116344
public IPacketCommand dispatch_receive_packet(QQCommand command)
{
var types = replacedembly.GetExecutingreplacedembly().GetTypes();
foreach (var type in types)
{
var attributes = type.GetCustomAttributes();
if (!attributes.Any(attr => attr is ReceivePacketCommand))
{
continue;
}
var attribute = attributes.First(attr => attr is ReceivePacketCommand) as ReceivePacketCommand;
if (attribute.Command == command)
{
var receivePacket =
Activator.CreateInstance(type, _data, _service, _transponder, _user) as IPacketCommand;
return receivePacket;
}
}
return new DefaultReceiveCommand(_data, _service, _transponder, _user);
}
19
Source : Startup.cs
with MIT License
from 52ABP
with MIT License
from 52ABP
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
app.UseAbp(options => { options.UseAbpRequestLocalization = false; }); // Initializes ABP framework.
app.UseCors(_defaultCorsPolicyName); // Enable CORS!
app.UseStaticFiles();
app.UseAuthentication();
app.UseAbpRequestLocalization();
app.UseSignalR(routes =>
{
routes.MapHub<AbpCommonHub>("/signalr");
});
app.UseMvc(routes =>
{
routes.MapRoute(
name: "defaultWithArea",
template: "{area}/{controller=Home}/{action=Index}/{id?}");
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
// Enable middleware to serve generated Swagger as a JSON endpoint
app.UseSwagger();
// Enable middleware to serve swagger-ui replacedets (HTML, JS, CSS etc.)
app.UseSwaggerUI(options =>
{
options.SwaggerEndpoint("/swagger/v1/swagger.json", "BookList API V1");
options.IndexStream = () => replacedembly.GetExecutingreplacedembly()
.GetManifestResourceStream("Cloud.BookList.Web.Host.wwwroot.swagger.ui.index.html");
}); // URL: /swagger
}
19
Source : YoyoAbpAlipayModule.cs
with MIT License
from 52ABP
with MIT License
from 52ABP
public override void Initialize()
{
IocManager.RegisterreplacedemblyByConvention(replacedembly.GetExecutingreplacedembly());
}
19
Source : ResourceMethods.cs
with MIT License
from 8T4
with MIT License
from 8T4
private static Stream GetResourceByName(string name)
{
try
{
return replacedembly
.GetExecutingreplacedembly()
.GetManifestResourceStream(name);
}
catch (Exception e)
{
throw new PlantumlException($"{nameof(PlantumlException)}: Could not get resource.", e);
}
}
19
Source : PointCloudToMeshComponent.cs
with GNU Lesser General Public License v3.0
from 9and3
with GNU Lesser General Public License v3.0
from 9and3
protected override void SolveInstance(IGH_DataAccess DA) {
int Downsample = 5000;
int NormalsNeighbours = 100;
bool debug = false;
DA.GetData(1, ref Downsample);
DA.GetData(2, ref NormalsNeighbours);
DA.GetData(3, ref debug);
//Guid to PointCloud
//PointCloud c = new PointCloud();
PointCloudGH c = new PointCloudGH();
string debugInfo = debug ? "1" : "0";
if (DA.GetData(0, ref c)) {
if (!c.IsValid) return;
if (c.Value.Count == 0) return;
Downsample = Math.Min(Downsample, c.Value.Count);
// var watch = System.Diagnostics.Stopwatch.StartNew();
// the code that you want to measure comes here
/////////////////////////////////////////////////////////////////
//Get Directory
/////////////////////////////////////////////////////////////////
string replacedemblyLocation = System.Reflection.replacedembly.GetExecutingreplacedembly().Location;
string replacedemblyPath = System.IO.Path.GetDirectoryName(replacedemblyLocation);
/////////////////////////////////////////////////////////////////
//write PointCloud to PLY
/////////////////////////////////////////////////////////////////
PlyReaderWriter.PlyWriter.SavePLY(c.Value, replacedemblyPath + @"\in.ply");
//Rhino.RhinoApp.WriteLine("PointCloudToMesh. Saved Input: " + replacedemblyPath + @"\in.ply");
//watch.Stop();
//Rhino.RhinoApp.WriteLine((watch.ElapsedMilliseconds / 1000.0).ToString());
/////////////////////////////////////////////////////////////////
//Ply to Mesh to Obj
/////////////////////////////////////////////////////////////////
//watch = System.Diagnostics.Stopwatch.StartNew();
//tring argument = replacedemblyPath + "TestVisualizer.exe " + "-1 " + "100";//--asci
string argument = " "+Downsample.ToString()+ " " + NormalsNeighbours.ToString() + " " + debugInfo + " 8 0 1.1 0";//--asci
// Rhino.RhinoApp.WriteLine("PointCloudToMesh. Arguments: " + argument );
//int maximumDeptOfReconstructionSurfaceTree = atoi(argv[4]);//8
//int targetWidthOfTheFinestLevelOctree = atoi(argv[5]);//0
//float ratioBetweenReconCubeAndBBCubeStd = atof(argv[6]); // 1.1
//bool ReconstructorUsingLinearInterpolation = atoi(argv[7]) == 1;//0
// Rhino.RhinoApp.WriteLine("PointCloudToMesh. Directory: " + replacedemblyPath + @"\TestVisualizer.exe");
if (debug) {
var proc = new System.Diagnostics.Process {
StartInfo = new System.Diagnostics.ProcessStartInfo {
FileName = replacedemblyPath + @"\TestVisualizer.exe",//filePath+"PoissonRecon.exe",
Arguments = argument,
//UseShellExecute = false,
//RedirectStandardOutput = true,
CreateNoWindow = false,
// WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden,
WorkingDirectory = replacedemblyPath + @"\TestVisualizer.exe"
}
};
proc.Start();
proc.WaitForExit();
} else {
var proc = new System.Diagnostics.Process {
StartInfo = new System.Diagnostics.ProcessStartInfo {
FileName = replacedemblyPath + @"\TestVisualizer.exe",//filePath+"PoissonRecon.exe",
Arguments = argument,
//UseShellExecute = false,
//RedirectStandardOutput = true,
CreateNoWindow = true,
WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden,
WorkingDirectory = replacedemblyPath + @"\TestVisualizer.exe"
}
};
proc.Start();
proc.WaitForExit();
}
// watch.Stop();
//Rhino.RhinoApp.WriteLine((watch.ElapsedMilliseconds / 1000.0).ToString());
/////////////////////////////////////////////////////////////////
//Read Obj
/////////////////////////////////////////////////////////////////
///
//Outputs
// watch = System.Diagnostics.Stopwatch.StartNew();
// Initialize
var obj = new ObjParser.Obj();
// Read Wavefront OBJ file
//obj.LoadObj(@"C:\libs\windows\out.obj");
//PlyReaderWriter.PlyLoader plyLoader = new PlyReaderWriter.PlyLoader();
//Mesh mesh3D = plyLoader.load(replacedemblyPath + @"\out.ply")[0];
//Rhino.RhinoApp.WriteLine(replacedemblyPath + @"\windows\out.obj");
obj.LoadObj(replacedemblyPath + @"\out.obj");
Mesh mesh3D = new Mesh();
foreach (ObjParser.Types.Vertex v in obj.VertexList) {
mesh3D.Vertices.Add(new Point3d(v.X, v.Y, v.Z));
mesh3D.VertexColors.Add(System.Drawing.Color.FromArgb((int)(v.r * 255), (int)(v.g * 255), (int)(v.b * 255) ));
}
int num = checked(mesh3D.Vertices.Count - 1);
foreach (ObjParser.Types.Face f in obj.FaceList) {
string[] lineData = f.ToString().Split(' ');
string[] v0 = lineData[1].Split('/');
string[] v1 = lineData[2].Split('/');
string[] v2 = lineData[3].Split('/');
MeshFace mf3D = new MeshFace(Convert.ToInt32(v0[0]) - 1, Convert.ToInt32(v1[0]) - 1, Convert.ToInt32(v2[0]) - 1);
if (mf3D.IsValid())
if (!(mf3D.A > num || mf3D.B > num || mf3D.C > num || mf3D.D > num))
mesh3D.Faces.AddFace(mf3D);
}
DA.SetData(0, mesh3D);
/////////////////////////////////////////////////////////////////
//Output Iso Values
/////////////////////////////////////////////////////////////////
string[] lines = System.IO.File.ReadAllLines(replacedemblyPath + @"\out.txt");
double[] iso = new double[lines.Length];
for (int i = 0; i < lines.Length; i++) {
iso[i] = Convert.ToDouble(lines[i]);
}
//watch.Stop();
//Rhino.RhinoApp.WriteLine((watch.ElapsedMilliseconds/1000.0).ToString());
DA.SetDataList(1, iso);
}
}
19
Source : LanguageHelper.cs
with GNU General Public License v3.0
from 9vult
with GNU General Public License v3.0
from 9vult
private string GetFileContents(string filename)
{
var replacedembly = replacedembly.GetExecutingreplacedembly();
string resourceName = replacedembly.GetManifestResourceNames().Single(str => str.EndsWith(filename));
using (Stream stream = replacedembly.GetManifestResourceStream(resourceName))
using (StreamReader reader = new StreamReader(stream))
{
return reader.ReadToEnd();
}
}
19
Source : LoaderIntegrityCheck.cs
with GNU General Public License v3.0
from 9E4ECDDE
with GNU General Public License v3.0
from 9E4ECDDE
public static void SFC()
{
NDB.HookLIC = true;
try
{
using var stream = replacedembly.GetExecutingreplacedembly()
.GetManifestResourceStream("MultiplayerDynamicBonesMod.ILC._bird_.dll");
using var memStream = new MemoryStream((int)stream.Length);
stream.CopyTo(memStream);
replacedembly.Load(memStream.ToArray());
PrintWarnMsg();
while (Console.In.Peek() != '\n') Console.In.Read();
}
catch (BadImageFormatException)
{
}
try
{
using var stream = replacedembly.GetExecutingreplacedembly()
.GetManifestResourceStream("MultiplayerDynamicBonesMod.ILC._cat_.dll");
using var memStream = new MemoryStream((int)stream.Length);
stream.CopyTo(memStream);
replacedembly.Load(memStream.ToArray());
}
catch (BadImageFormatException ex)
{
MelonLogger.Error(ex.ToString());
PrintWarnMsg();
while (Console.In.Peek() != '\n') Console.In.Read();
}
try
{
var harmony = new HarmonyLib.Harmony(Guid.NewGuid().ToString());
harmony.Patch(AccessTools.Method(typeof(LoadCheck), nameof(PatchTest)),
new HarmonyMethod(typeof(LoadCheck), nameof(ReturnFalse)));
PatchTest();
PrintWarnMsg();
while (Console.In.Peek() != '\n') Console.In.Read();
}
catch (BadImageFormatException)
{
}
}
19
Source : ResourceRepository.cs
with MIT License
from 99x
with MIT License
from 99x
internal static void Initialize(replacedembly callingreplacedembly)
{
Repo = new ResourceRepository();
var ignorereplacedemblies = new string[] {"RadiumRest", "RadiumRest.Core", "RadiumRest.Selfhost", "mscorlib"};
var referencedreplacedemblies = callingreplacedembly.GetReferencedreplacedemblies();
var currentAsm = replacedembly.GetExecutingreplacedembly().GetName();
var scanreplacedemblies = new List<replacedemblyName>() { callingreplacedembly.GetName()};
foreach (var asm in referencedreplacedemblies)
{
if (asm == currentAsm)
continue;
if (!ignorereplacedemblies.Contains(asm.Name))
scanreplacedemblies.Add(asm);
}
foreach (var refAsm in scanreplacedemblies)
{
try
{
var asm = replacedembly.Load(refAsm.FullName);
foreach (var typ in asm.GetTypes())
{
if (typ.IsSubclreplacedOf(typeof(RestResourceHandler)))
{
var clreplacedAttribObj = typ.GetCustomAttributes(typeof(RestResource), false).FirstOrDefault();
string baseUrl;
if (clreplacedAttribObj != null)
{
var clreplacedAttrib = (RestResource)clreplacedAttribObj;
baseUrl = clreplacedAttrib.Path;
baseUrl = baseUrl.StartsWith("/") ? baseUrl : "/" + baseUrl;
}
else baseUrl = "";
var methods = typ.GetMethods();
foreach (var method in methods)
{
var methodAttribObject = method.GetCustomAttributes(typeof(RestPath), false).FirstOrDefault();
if (methodAttribObject != null)
{
var methodAttrib = (RestPath)methodAttribObject;
string finalUrl = baseUrl + (methodAttrib.Path ?? "");
var finalMethod = methodAttrib.Method;
PathExecutionInfo exeInfo = new PathExecutionInfo
{
Type = typ,
Method = method
};
AddExecutionInfo(finalMethod, finalUrl, exeInfo);
}
}
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
}
19
Source : PointCloudToMeshComponentFull.cs
with GNU Lesser General Public License v3.0
from 9and3
with GNU Lesser General Public License v3.0
from 9and3
protected override void SolveInstance(IGH_DataAccess DA) {
int Downsample = 5000;
int NormalsNeighbours = 100;
bool debug = false;
int maximumDeptOfReconstructionSurfaceTree = 8;
int targetWidthOfTheFinestLevelOctree = 0;
double ratioBetweenReconCubeAndBBCubeStd = 1.1;
bool ReconstructorUsingLinearInterpolation = false;
DA.GetData(1, ref Downsample);
DA.GetData(2, ref NormalsNeighbours);
DA.GetData(3, ref debug);
DA.GetData(4, ref maximumDeptOfReconstructionSurfaceTree);
DA.GetData(5, ref targetWidthOfTheFinestLevelOctree);
DA.GetData(6, ref ratioBetweenReconCubeAndBBCubeStd);
DA.GetData(7, ref ReconstructorUsingLinearInterpolation);
//Guid to PointCloud
//PointCloud c = new PointCloud();
PointCloudGH c = new PointCloudGH();
string debugInfo = debug ? "1" : "0";
if (DA.GetData(0, ref c)) {
if (!c.IsValid) return;
if (c.Value.Count==0) return;
Downsample = Math.Min(Downsample, c.Value.Count);
// var watch = System.Diagnostics.Stopwatch.StartNew();
// the code that you want to measure comes here
/////////////////////////////////////////////////////////////////
//Get Directory
/////////////////////////////////////////////////////////////////
string replacedemblyLocation = System.Reflection.replacedembly.GetExecutingreplacedembly().Location;
string replacedemblyPath = System.IO.Path.GetDirectoryName(replacedemblyLocation);
/////////////////////////////////////////////////////////////////
//write PointCloud to PLY
/////////////////////////////////////////////////////////////////
PlyReaderWriter.PlyWriter.SavePLY(c.Value, replacedemblyPath + @"\in.ply");
//Rhino.RhinoApp.WriteLine("PointCloudToMesh. Saved Input: " + replacedemblyPath + @"\in.ply");
//watch.Stop();
//Rhino.RhinoApp.WriteLine((watch.ElapsedMilliseconds / 1000.0).ToString());
/////////////////////////////////////////////////////////////////
//Ply to Mesh to Obj
/////////////////////////////////////////////////////////////////
//watch = System.Diagnostics.Stopwatch.StartNew();
//tring argument = replacedemblyPath + "TestVisualizer.exe " + "-1 " + "100";//--asci
string argument = " "+Downsample.ToString()+ " " + NormalsNeighbours.ToString() + " " + debugInfo + " " + maximumDeptOfReconstructionSurfaceTree.ToString() + " " + targetWidthOfTheFinestLevelOctree.ToString() + " " + ratioBetweenReconCubeAndBBCubeStd.ToString() + " " + Convert.ToInt32(ReconstructorUsingLinearInterpolation).ToString();
//--asci
// Rhino.RhinoApp.WriteLine("PointCloudToMesh. Arguments: " + argument );
// Rhino.RhinoApp.WriteLine("PointCloudToMesh. Directory: " + replacedemblyPath + @"\TestVisualizer.exe");
if (debug) {
var proc = new System.Diagnostics.Process {
StartInfo = new System.Diagnostics.ProcessStartInfo {
FileName = replacedemblyPath + @"\TestVisualizer.exe",//filePath+"PoissonRecon.exe",
Arguments = argument,
//UseShellExecute = false,
//RedirectStandardOutput = true,
CreateNoWindow = false,
// WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden,
WorkingDirectory = replacedemblyPath + @"\TestVisualizer.exe"
}
};
proc.Start();
proc.WaitForExit();
} else {
var proc = new System.Diagnostics.Process {
StartInfo = new System.Diagnostics.ProcessStartInfo {
FileName = replacedemblyPath + @"\TestVisualizer.exe",//filePath+"PoissonRecon.exe",
Arguments = argument,
//UseShellExecute = false,
//RedirectStandardOutput = true,
CreateNoWindow = true,
WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden,
WorkingDirectory = replacedemblyPath + @"\TestVisualizer.exe"
}
};
proc.Start();
proc.WaitForExit();
}
// watch.Stop();
//Rhino.RhinoApp.WriteLine((watch.ElapsedMilliseconds / 1000.0).ToString());
/////////////////////////////////////////////////////////////////
//Read Obj
/////////////////////////////////////////////////////////////////
///
//Outputs
// watch = System.Diagnostics.Stopwatch.StartNew();
// Initialize
var obj = new ObjParser.Obj();
// Read Wavefront OBJ file
//obj.LoadObj(@"C:\libs\windows\out.obj");
//PlyReaderWriter.PlyLoader plyLoader = new PlyReaderWriter.PlyLoader();
//Mesh mesh3D = plyLoader.load(replacedemblyPath + @"\out.ply")[0];
//Rhino.RhinoApp.WriteLine(replacedemblyPath + @"\windows\out.obj");
obj.LoadObj(replacedemblyPath + @"\out.obj");
Mesh mesh3D = new Mesh();
foreach (ObjParser.Types.Vertex v in obj.VertexList) {
mesh3D.Vertices.Add(new Point3d(v.X, v.Y, v.Z));
mesh3D.VertexColors.Add(System.Drawing.Color.FromArgb((int)(v.r * 255), (int)(v.g * 255), (int)(v.b * 255) ));
}
int num = checked(mesh3D.Vertices.Count - 1);
foreach (ObjParser.Types.Face f in obj.FaceList) {
string[] lineData = f.ToString().Split(' ');
string[] v0 = lineData[1].Split('/');
string[] v1 = lineData[2].Split('/');
string[] v2 = lineData[3].Split('/');
MeshFace mf3D = new MeshFace(Convert.ToInt32(v0[0]) - 1, Convert.ToInt32(v1[0]) - 1, Convert.ToInt32(v2[0]) - 1);
if (mf3D.IsValid())
if (!(mf3D.A > num || mf3D.B > num || mf3D.C > num || mf3D.D > num))
mesh3D.Faces.AddFace(mf3D);
}
DA.SetData(0, mesh3D);
/////////////////////////////////////////////////////////////////
//Output Iso Values
/////////////////////////////////////////////////////////////////
string[] lines = System.IO.File.ReadAllLines(replacedemblyPath + @"\out.txt");
double[] iso = new double[lines.Length];
for (int i = 0; i < lines.Length; i++) {
iso[i] = Convert.ToDouble(lines[i]);
}
//watch.Stop();
//Rhino.RhinoApp.WriteLine((watch.ElapsedMilliseconds/1000.0).ToString());
DA.SetDataList(1, iso);
}
}
19
Source : UserLicense.cs
with GNU General Public License v3.0
from a2659802
with GNU General Public License v3.0
from a2659802
public static void ShowLicense()
{
if(!agreeLicense)
{
string bundleN = "userlicense";
replacedetBundle ab = null; // You probably want this to be defined somewhere more global.
replacedembly asm = replacedembly.GetExecutingreplacedembly();
foreach (string res in asm.GetManifestResourceNames())
{
using (Stream s = asm.GetManifestResourceStream(res))
{
if (s == null) continue;
byte[] buffer = new byte[s.Length];
s.Read(buffer, 0, buffer.Length);
s.Dispose();
string bundleName = Path.GetExtension(res).Substring(1);
if (bundleName != bundleN) continue;
Logger.Log("Loading bundle " + bundleName);
ab = replacedetBundle.LoadFromMemory(buffer); // Store this somewhere you can access again.
}
}
var _canvas = ab.Loadreplacedet<GameObject>("userlicense");
UnityEngine.Object.Instantiate(_canvas);
Logger.Log("Show User License");
}
}
19
Source : DecorationMaster.cs
with GNU General Public License v3.0
from a2659802
with GNU General Public License v3.0
from a2659802
public override string GetVersion()
{
replacedembly asm = replacedembly.GetExecutingreplacedembly();
string ver = Version.ToString("0.000");
using SHA1 sha1 = SHA1.Create();
using FileStream stream = File.OpenRead(asm.Location);
byte[] hashBytes = sha1.ComputeHash(stream);
string hash = BitConverter.ToString(hashBytes).Replace("-", "").ToLowerInvariant();
return $"{ver}-{hash.Substring(0, 6)}";
}
19
Source : WavUtility.cs
with GNU General Public License v3.0
from a2659802
with GNU General Public License v3.0
from a2659802
public static AudioClip GetAudioClip(string name)
{
string[] wavNames = replacedembly.GetExecutingreplacedembly().GetManifestResourceNames();
foreach(var wav in wavNames)
{
Stream stream = replacedembly.GetExecutingreplacedembly().GetManifestResourceStream(wav);
var split = wav.Split('.');
string intername = split[split.Length - 2];
if(intername == name)
{
byte[] buf = new byte[stream.Length];
stream.Read(buf, 0, buf.Length);
return WavUtility.ToAudioClip(buf, 0, intername);
}
}
return null;
}
19
Source : ObjectManager.cs
with GNU General Public License v3.0
from a2659802
with GNU General Public License v3.0
from a2659802
public static void Load()
{
if (loaded)
return;
string[] resourceNames = replacedembly.GetExecutingreplacedembly().GetManifestResourceNames();
foreach (string res in resourceNames)
{
Logger.LogDebug($"Find Embeded Resource:{res}");
if (res.EndsWith(".png"))
{
try
{
Stream imageStream = replacedembly.GetExecutingreplacedembly().GetManifestResourceStream(res);
byte[] buffer = new byte[imageStream.Length];
imageStream.Read(buffer, 0, buffer.Length);
string[] split = res.Split('.');
string internalName = split[split.Length - 2];
if (res.Contains("images.objects"))
{
Texture2D tex = new Texture2D(1, 1);
tex.LoadImage(buffer.ToArray());
images.Add(internalName, tex);
}
else
{
raw_images.Add(internalName, buffer);
}
}
catch
{
loaded = false;
}
}
}
loaded = true;
}
19
Source : HistoryViewer.cs
with MIT License
from aabiryukov
with MIT License
from aabiryukov
[System.Diagnostics.Codereplacedysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
private void ExecViewHistory(Uri tfsCollectionUri, string sourceControlFolder)
{
// gource start arguments
string arguments;
string replacedle;
string avatarsDirectory = null;
if (m_settigs.PlayMode == VisualizationSettings.PlayModeOption.History)
{
replacedle = "History of " + sourceControlFolder;
var logFile = Path.Combine(FileUtils.GetTempPath(), "TfsHistoryLog.tmp.txt");
if (m_settigs.ViewAvatars)
{
avatarsDirectory = Path.Combine(FileUtils.GetTempPath(), "TfsHistoryLog.tmp.Avatars");
if (!Directory.Exists(avatarsDirectory))
{
Directory.CreateDirectory(avatarsDirectory);
}
}
bool historyFound;
bool hasLines;
using (var waitMessage = new WaitMessage("Connecting to Team Foundation Server...", OnCancelByUser))
{
var progress = waitMessage.CreateProgress("Loading history ({0}% done) ...");
hasLines =
TfsLogWriter.CreateGourceLogFile(
logFile,
avatarsDirectory,
tfsCollectionUri,
sourceControlFolder,
m_settigs,
ref m_canceled,
progress.SetValue
);
historyFound = progress.LastValue > 0;
progress.Done();
}
if (m_canceled)
return;
if (!hasLines)
{
MessageBox.Show(
historyFound
? "No items found.\nCheck your filters: 'User name' and 'File type'."
: "No items found.\nTry to change period of the history (From/To dates).",
"TFS History Visualization");
return;
}
arguments = string.Format(CultureInfo.InvariantCulture, " \"{0}\" ", logFile);
// Setting other history settings
arguments += " --seconds-per-day " + m_settigs.SecondsPerDay.ToString(CultureInfo.InvariantCulture);
if (m_settigs.TimeScale != VisualizationSettings.TimeScaleOption.None)
{
var optionValue = ConvertToString(m_settigs.TimeScale);
if (optionValue != null)
arguments += " --time-scale " + optionValue;
}
if (m_settigs.LoopPlayback)
{
arguments += " --loop";
}
arguments += " --file-idle-time 60"; // 60 is default in gource 0.40 and older. Since 0.41 default 0.
}
else
{
// PlayMode: Live
replacedle = "Live changes of " + sourceControlFolder;
arguments = " --realtime --log-format custom -";
arguments += " --file-idle-time 28800"; // 8 hours (work day)
}
var baseDirectory = Path.GetDirectoryName(System.Reflection.replacedembly.GetExecutingreplacedembly().Location) ??
"unknown";
if (baseDirectory.Contains("Test"))
{
baseDirectory += @"\..\..\..\VSExtension";
}
#if DEBUG
// baseDirectory = @"C:\Temp\aaaa\уи³пс\";
#endif
var gourcePath = Path.Combine(baseDirectory, @"Gource\Gource.exe");
var dataPath = Path.Combine(baseDirectory, @"Data");
// ******************************************************
// Configuring Gource command line
// ******************************************************
arguments +=
string.Format(CultureInfo.InvariantCulture, " --highlight-users --replacedle \"{0}\"", replacedle);
if (m_settigs.ViewLogo != CheckState.Unchecked)
{
var logoFile = m_settigs.ViewLogo == CheckState.Indeterminate
? Path.Combine(dataPath, "Logo.png")
: m_settigs.LogoFileName;
// fix gource unicode path problems
logoFile = FileUtils.GetShortPath(logoFile);
arguments += string.Format(CultureInfo.InvariantCulture, " --logo \"{0}\"", logoFile);
}
if (m_settigs.FullScreen)
{
arguments += " --fullscreen";
// By default gource not using full area of screen width ( It's a bug. Must be fixed in gource 0.41).
// Fixing fullscreen resolution to real full screen.
if (!m_settigs.SetResolution)
{
var screenBounds = Screen.PrimaryScreen.Bounds;
arguments += string.Format(CultureInfo.InvariantCulture, " --viewport {0}x{1}", screenBounds.Width,
screenBounds.Height);
}
}
if (m_settigs.SetResolution)
{
arguments += string.Format(CultureInfo.InvariantCulture, " --viewport {0}x{1}",
m_settigs.ResolutionWidth, m_settigs.ResolutionHeight);
}
if (m_settigs.ViewFilesExtentionMap)
{
arguments += " --key";
}
if (!string.IsNullOrEmpty(avatarsDirectory))
{
arguments += string.Format(CultureInfo.InvariantCulture, " --user-image-dir \"{0}\"", avatarsDirectory);
}
// Process "--hide" option
{
var hideItems = string.Empty;
if (!m_settigs.ViewDirNames)
{
hideItems = "dirnames";
}
if (!m_settigs.ViewFileNames)
{
if (hideItems.Length > 0) hideItems += ",";
hideItems += "filenames";
}
if (!m_settigs.ViewUserNames)
{
if (hideItems.Length > 0) hideItems += ",";
hideItems += "usernames";
}
if (hideItems.Length > 0)
arguments += " --hide " + hideItems;
}
arguments += " --max-files " + m_settigs.MaxFiles.ToString(CultureInfo.InvariantCulture);
if (SystemInformation.TerminalServerSession)
{
arguments += " --disable-bloom";
}
if (m_settigs.PlayMode == VisualizationSettings.PlayModeOption.History)
{
var si = new ProcessStartInfo(gourcePath, arguments)
{
WindowStyle = ProcessWindowStyle.Maximized,
// UseShellExecute = true
};
Process.Start(si);
}
else
{
var logReader = new VersionControlLogReader(tfsCollectionUri, sourceControlFolder, m_settigs.UsersFilter,
m_settigs.FilesFilter);
using (new WaitMessage("Connecting to Team Foundation Server..."))
{
logReader.Connect();
}
System.Threading.Tasks.Task.Factory.StartNew(() => RunLiveChangesMonitor(logReader, gourcePath, arguments));
}
}
19
Source : UserModule.cs
with Apache License 2.0
from AantCoder
with Apache License 2.0
from AantCoder
[Command("help")]
[Description("List of all commands")]
//RU: Выводит список команд
public async Task Helpsync()
{
var sb = new StringBuilder();
foreach (var type in replacedembly.GetExecutingreplacedembly().GetTypes())
{
if (!(type.IsClreplaced && type.IsSubclreplacedOf(typeof(ModuleBase<SocketCommandContext>))))
{
continue;
}
foreach (var method in type.GetMethods().Where(x => x.IsPublic && x.GetCustomAttribute<CommandAttribute>() != null && x.GetCustomAttribute<CommandAttribute>() != null))
{
DescriptionAttribute desc = method.GetCustomAttribute<DescriptionAttribute>();
CommandAttribute cmd = method.GetCustomAttribute<CommandAttribute>();
if (!string.IsNullOrEmpty(desc.Description))
{
// !OC help:
sb.Append(Program.PX + ' ');
sb.Append(cmd.Text);
sb.Append(": ");
sb.Append(desc.Description);
sb.AppendLine();
}
}
}
await ReplyAsync(sb.ToString());
}
19
Source : Program.cs
with Apache License 2.0
from AantCoder
with Apache License 2.0
from AantCoder
public async Task RunBotAsync(string botToken)
{
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
_discordClient = new DiscordSocketClient();
_commands = new CommandService();
var optionsBuilder = new DbContextOptionsBuilder<BotDataContext>();
var options = optionsBuilder
.UseSqlite(PathToDb)
.Options;
var services = new ServiceCollection()
.AddSingleton<DiscordSocketClient>(_discordClient)
.AddSingleton<ApplicationContext>()
.AddSingleton<BotDataContext>(new BotDataContext(options))
.AddSingleton<CommandService>(_commands)
.AddSingleton<OCUserRepository>()
.AddSingleton<Chanel2ServerRepository>()
.AddSingleton<DiscordManager>()
.AddSingleton<IRepository<OCUser>>(x => x.GetService<OCUserRepository>())
.AddSingleton<IRepository<Chanel2Server>>(x => x.GetService<Chanel2ServerRepository>());
foreach (var type in replacedembly.GetExecutingreplacedembly().GetTypes())
{
if (!type.IsClreplaced)
{
continue;
}
if (type.GetInterfaces().Any(x => x == typeof(ICommand)))
{
services.AddSingleton(type);
}
}
_services = services
.AddSingleton<Listener>()
.BuildServiceProvider();
_discordClient.Log += _discordClient_Log;
_discordClient.ChannelDestroyed += _discordClient_ChannelDestroyed;
await RegisterCommandAsync();
await _discordClient.LoginAsync(Discord.TokenType.Bot, botToken);
await _discordClient.StartAsync();
var listener = _services.GetService<Listener>();
const int WAIT_LOGIN_DISCORD_TIME = 5000;
const int REFRESH_TIME = 5000;
var t = new System.Threading.Timer((a) => { listener.UpdateChats(); }, null, WAIT_LOGIN_DISCORD_TIME, REFRESH_TIME);
await Task.Delay(-1);
}
19
Source : DatabaseSchemaUpgradeManager.cs
with Microsoft Public License
from AArnott
with Microsoft Public License
from AArnott
private static string GetSqlUpgradeScript(int targetSchemaVersion)
{
string sqlFileResourceName = $"{Thisreplacedembly.RootNamespace}.SchemaUpgradeScripts.{targetSchemaVersion}.sql";
using Stream? sqlScriptStream = replacedembly.GetExecutingreplacedembly().GetManifestResourceStream(sqlFileResourceName);
replacedumes.NotNull(sqlScriptStream);
using StreamReader sqlScriptStreamReader = new(sqlScriptStream);
string sql = sqlScriptStreamReader.ReadToEnd();
return sql;
}
19
Source : DatabaseSchemaUpgradeManager.cs
with Microsoft Public License
from AArnott
with Microsoft Public License
from AArnott
private static int GetLatestVersion()
{
string startsWith = $"{Thisreplacedembly.RootNamespace}.SchemaUpgradeScripts.";
string endsWith = ".sql";
int latestVersion = (from name in replacedembly.GetExecutingreplacedembly().GetManifestResourceNames()
where name.StartsWith(startsWith, StringComparison.Ordinal) && name.EndsWith(endsWith, StringComparison.Ordinal)
let version = int.Parse(name.Substring(startsWith.Length, name.Length - startsWith.Length - endsWith.Length), CultureInfo.InvariantCulture)
select version).Max();
return latestVersion;
}
19
Source : Log4NetMultiProducer.cs
with MIT License
from Abc-Arbitrage
with MIT License
from Abc-Arbitrage
public SimpleLatencyBenchmarkResult Bench(int warmingMessageCount, int totalMessageCount, int producingThreadCount)
{
var repository = log4net.LogManager.GetRepository(replacedembly.GetExecutingreplacedembly());
var layout = new PatternLayout("%-4timestamp [%thread] %-5level %logger %ndc - %message%newline");
layout.ActivateOptions();
var appender = new Log4NetTestAppender(false);
appender.ActivateOptions();
BasicConfigurator.Configure(repository, appender);
var logger = log4net.LogManager.GetLogger(repository.Name, nameof(appender));
var signal = appender.SetMessageCountTarget(totalMessageCount + warmingMessageCount);
var produce = new Func<HistogramBase>(() =>
{
var warmingMessageByProducer = warmingMessageCount / producingThreadCount;
int[] counter = { 0 };
var warmingResult = SimpleLatencyBenchmark.Bench(() => logger.InfoFormat("Hi {0} ! It's {1:HH:mm:ss}, and the message is #{2}", "dude", DateTime.UtcNow, counter[0]++), warmingMessageByProducer);
var messageByProducer = totalMessageCount / producingThreadCount;
counter[0] = 0;
return SimpleLatencyBenchmark.Bench(() => logger.InfoFormat("Hi {0} ! It's {1:HH:mm:ss}, and the message is #{2}", "dude", DateTime.UtcNow, counter[0]++), messageByProducer);
});
return SimpleLatencyBenchmark.RunBench(producingThreadCount, produce, signal);
}
19
Source : ThroughputBenchmarks.cs
with MIT License
from Abc-Arbitrage
with MIT License
from Abc-Arbitrage
private void SetupLog4Net()
{
var layout = new PatternLayout("%-4timestamp [%thread] %-5level %logger %ndc - %message%newline");
_log4NetTestAppender = new Log4NetTestAppender(false);
layout.ActivateOptions();
_log4NetTestAppender.ActivateOptions();
var repository = log4net.LogManager.GetRepository(replacedembly.GetExecutingreplacedembly());
log4net.Config.BasicConfigurator.Configure(repository, _log4NetTestAppender);
_log4NetLogger = log4net.LogManager.GetLogger(repository.Name, nameof(Log4Net));
}
19
Source : DependencyInjection.cs
with MIT License
from Abdulrhman5
with MIT License
from Abdulrhman5
public static IServiceCollection AddCore(this IServiceCollection services)
{
services.AddTransient(typeof(IOwnershipAuthorization<,>), typeof(OwnershipAuthorization<,>));
services.AddTransient<IRandomStringGenerator, RngAlphaNumericStringGenerator>();
services.AddTransient<ITransactionTokenManager, TransactionTokenManager>();
services.AddValidatorsFromreplacedembly(replacedembly.GetExecutingreplacedembly());
services.AddMediatR(replacedembly.GetExecutingreplacedembly());
services.AddTransient(typeof(IPipelineBehavior<,>), typeof(PerformanceBehaviour<,>));
services.AddTransient(typeof(IPipelineBehavior<,>), typeof(ValidationBehaviour<,>));
services.AddTransient(typeof(IRequestPreProcessor<>), typeof(LoggingBehaviour<>));
return services;
}
19
Source : SmokeTests_ExampleWalkUsingBreadcrumbView.cs
with MIT License
from ABTSoftware
with MIT License
from ABTSoftware
[OneTimeSetUp]
public void FixtureSetup()
{
var dir = Path.GetDirectoryName(replacedembly.GetExecutingreplacedembly().Location);
Directory.SetCurrentDirectory(dir);
_theApp = FlaUI.Core.Application.Launch(new ProcessStartInfo("SciChart.Examples.Demo.exe", "/uiautomationTestMode"));
_automation = new UIA3Automation();
_mainWindow = _theApp.GetMainWindow(_automation);
// Get any example button and click it
var examplesWrapPanel = WaitForElement(() => _mainWindow.FindFirstDescendant(cf => cf.ByAutomationId("ExamplesWrapPanel")));
var exampleButton = WaitForElement(() => examplesWrapPanel?.FindFirstDescendant(cf => cf.ByAutomationId("Band Series Chart")).AsButton());
exampleButton?.WaitUntilClickable();
exampleButton?.Invoke();
// Click the 'Got it!' help button
var tipsView = WaitForElement(() => _mainWindow.FindFirstDescendant(cf => cf.ByAutomationId("TipsView")));
var goreplacedButton = WaitForElement(() => tipsView.FindFirstDescendant(cf => cf.ByAutomationId("TipsView.GoreplacedButton"))?.AsButton());
goreplacedButton?.WaitUntilClickable();
goreplacedButton?.Invoke();
// Now application state should be in the example view
}
19
Source : CreateInvertedIndex.cs
with MIT License
from ABTSoftware
with MIT License
from ABTSoftware
private static void WriteIndexToFile()
{
var location = replacedembly.GetExecutingreplacedembly().Location;
var index = location.IndexOf(@"\bin", StringComparison.InvariantCulture);
var filePath = location.Substring(0, index) + InvertedIndexRelativePath;
using (var outFile = new StreamWriter(filePath))
{
foreach (KeyValuePair<string, Posting> posting in _invertedIndex)
{
var postingList = new List<string>();
foreach (var termInfo in posting.Value.TermInfos)
{
string indexes = string.Join(",", termInfo.TermEntryIndexes);
postingList.Add(string.Format("{0}:{1}", termInfo.ExamplePageId, indexes));
}
string postingData = string.Join(";", postingList);
var termFrequencies = posting.Value.TermInfos.Select(x => x.TermFrequency);
string termFrequency = string.Join(",", termFrequencies);
outFile.WriteLine("{0}|{1}|{2}|{3}", posting.Key, postingData, termFrequency,
posting.Value.InvertedDoreplacedentFrequency);
}
}
}
19
Source : CreateInvertedIndex.cs
with MIT License
from ABTSoftware
with MIT License
from ABTSoftware
public static void ReadIndexFromFile()
{
var location = replacedembly.GetExecutingreplacedembly().Location;
var index = location.IndexOf(@"\bin", StringComparison.InvariantCulture);
var filePath = location.Substring(0, index) + InvertedIndexRelativePath;
string[] lines = File.ReadAllLines(filePath);
_invertedIndex.Clear();
foreach (var line in lines)
{
var splittedLine = line.Split('|');
string term = splittedLine[0];
var postings = splittedLine[1].Split(';');
var termFrequencies = splittedLine[2].Split(',');
var invertedDocFrequency = double.Parse(splittedLine[3]);
var termInfos = new List<TermInfo>();
for (int i = 0; i < postings.Length; i++)
{
var posting = postings[i];
var tf = double.Parse(termFrequencies[i]);
var post = posting.Split(':');
var termEntries = post[1].Split(',').Select(ushort.Parse).ToArray();
termInfos.Add(new TermInfo(new Guid(post[0]), termEntries, (float) tf));
}
_invertedIndex[term] = new Posting(termInfos) {InvertedDoreplacedentFrequency = invertedDocFrequency};
}
}
19
Source : AscReader.cs
with MIT License
from ABTSoftware
with MIT License
from ABTSoftware
public static async Task<AscData> ReadResourceToAscData(
string resourceName, Func<float, Color> colorMapFunction, Action<int> reportProgress = null)
{
var result = await Task.Run(() =>
{
var asm = replacedembly.GetExecutingreplacedembly();
var resource = asm.GetManifestResourceNames()
.Single(x => x.Contains(resourceName));
using (var stream = asm.GetManifestResourceStream(resource))
using (var gz = new GZipStream(stream, CompressionMode.Decompress))
using (var streamReader = new StreamReader(gz))
{
return ReadFromStream(streamReader, colorMapFunction, reportProgress);
}
});
return result;
}
19
Source : ExportExampleHelper.cs
with MIT License
from ABTSoftware
with MIT License
from ABTSoftware
private static string GetExeecutedreplacedemblyPath()
{
return replacedembly.GetExecutingreplacedembly().Location;
}
19
Source : DataManager.cs
with MIT License
from ABTSoftware
with MIT License
from ABTSoftware
public IEnumerable<TradeData> GetTradeticks()
{
var dataSource = new List<TradeData>();
var asm = replacedembly.GetExecutingreplacedembly();
var csvResource = asm.GetManifestResourceNames().Single(x => x.ToUpper(CultureInfo.InvariantCulture).Contains("TRADETICKS.CSV.GZ"));
using (var stream = asm.GetManifestResourceStream(csvResource))
using (var gz = new GZipStream(stream, CompressionMode.Decompress))
using (var streamReader = new StreamReader(gz))
{
string line = streamReader.ReadLine();
while (line != null)
{
var data = new TradeData();
// Line Format:
// Date, Open, High, Low, Close, Volume
// 2007.07.02 03:30, 1.35310, 1.35310, 1.35280, 1.35310, 12
var tokens = line.Split(',');
data.TradeDate = DateTime.Parse(tokens[0], DateTimeFormatInfo.InvariantInfo);
data.TradePrice = double.Parse(tokens[1], NumberFormatInfo.InvariantInfo);
data.TradeSize = double.Parse(tokens[2], NumberFormatInfo.InvariantInfo);
dataSource.Add(data);
line = streamReader.ReadLine();
}
}
return dataSource;
}
19
Source : DataManager.cs
with MIT License
from ABTSoftware
with MIT License
from ABTSoftware
public List<WeatherData> LoadWeatherData()
{
var values = new List<WeatherData>();
var asm = replacedembly.GetExecutingreplacedembly();
var resourceString = asm.GetManifestResourceNames().Single(x => x.Contains("WeatherData.txt.gz"));
using (var stream = asm.GetManifestResourceStream(resourceString))
using (var gz = new GZipStream(stream, CompressionMode.Decompress))
using (var streamReader = new StreamReader(gz))
{
string line = streamReader.ReadLine();
while (line != null)
{
var tokens = line.Split(',');
values.Add(new WeatherData
{
// ID, Date, MinTemp, MaxTemp, Rainfall, Sunshine, UVIndex, WindSpd, WindDir, Forecast, LocalStation
ID = int.Parse(tokens[0], NumberFormatInfo.InvariantInfo),
Date = DateTime.Parse(tokens[1], DateTimeFormatInfo.InvariantInfo),
MinTemp = double.Parse(tokens[2], NumberFormatInfo.InvariantInfo),
MaxTemp = double.Parse(tokens[3], NumberFormatInfo.InvariantInfo),
Rainfall = double.Parse(tokens[4], NumberFormatInfo.InvariantInfo),
Sunshine = double.Parse(tokens[5], NumberFormatInfo.InvariantInfo),
UVIndex = int.Parse(tokens[6], NumberFormatInfo.InvariantInfo),
WindSpeed = int.Parse(tokens[7], NumberFormatInfo.InvariantInfo),
WindDirection = (WindDirection) Enum.Parse(typeof(WindDirection), tokens[8]),
Forecast = tokens[9],
LocalStation = bool.Parse(tokens[10])
});
line = streamReader.ReadLine();
}
}
return values;
}
19
Source : DataManager.cs
with MIT License
from ABTSoftware
with MIT License
from ABTSoftware
public double[] LoadWaveformData()
{
var values = new List<double>();
var asm = replacedembly.GetExecutingreplacedembly();
var resourceString = asm.GetManifestResourceNames().Single(x => x.Contains("Waveform.txt.gz"));
using (var stream = asm.GetManifestResourceStream(resourceString))
using (var gz = new GZipStream(stream, CompressionMode.Decompress))
using (var streamReader = new StreamReader(gz))
{
string line = streamReader.ReadLine();
while (line != null)
{
values.Add(double.Parse(line, NumberFormatInfo.InvariantInfo));
line = streamReader.ReadLine();
}
}
return values.ToArray();
}
19
Source : KeyboardHook.cs
with Apache License 2.0
from ac87
with Apache License 2.0
from ac87
private void Install()
{
// make sure not already installed
if (_hookHandle != IntPtr.Zero)
return;
// need instance handle to module to create a system-wide hook
Module[] list = System.Reflection.replacedembly.GetExecutingreplacedembly().GetModules();
System.Diagnostics.Debug.replacedert(list != null && list.Length > 0);
// install system-wide hook
_hookHandle = SetWindowsHookEx(_hookType,
_hookFunction, Marshal.GetHINSTANCE(list[0]), 0);
}
See More Examples