Here are the examples of the csharp api System.Reflection.Assembly.GetAssembly(System.Type) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
823 Examples
19
Source : XnaToFnaHelper.cs
with zlib License
from 0x0ade
with zlib License
from 0x0ade
public static void PlatformHook(string name) {
Type t_Helper = typeof(XnaToFnaHelper);
replacedembly fna = replacedembly.Getreplacedembly(typeof(Game));
FieldInfo field = fna.GetType("Microsoft.Xna.Framework.FNAPlatform").GetField(name);
// Store the original delegate into fna_name.
t_Helper.GetField($"fna_{name}").SetValue(null, field.GetValue(null));
// Replace the value with the new method.
field.SetValue(null, Delegate.CreateDelegate(fna.GetType($"Microsoft.Xna.Framework.FNAPlatform+{name}Func"), t_Helper.GetMethod(name)));
}
19
Source : FileCache.cs
with Apache License 2.0
from acarteas
with Apache License 2.0
from acarteas
public override Type BindToType(string replacedemblyName, string typeName)
{
Type typeToDeserialize = null;
String currentreplacedembly = replacedembly.Getreplacedembly(typeof(LocalCacheBinder)).FullName;
replacedemblyName = currentreplacedembly;
// Get the type using the typeName and replacedemblyName
typeToDeserialize = Type.GetType(String.Format("{0}, {1}",
typeName, replacedemblyName));
return typeToDeserialize;
}
19
Source : FileCacheManager.cs
with Apache License 2.0
from acarteas
with Apache License 2.0
from acarteas
public override Type BindToType(string replacedemblyName, string typeName)
{
Type typeToDeserialize = null;
String currentreplacedembly = replacedembly.Getreplacedembly(typeof(LocalCacheBinder)).FullName;
replacedemblyName = currentreplacedembly;
// Get the type using the typeName and replacedemblyName
typeToDeserialize = Type.GetType(String.Format("{0}, {1}",
typeName, replacedemblyName));
return typeToDeserialize;
}
19
Source : SCaddins.cs
with GNU Lesser General Public License v3.0
from acnicholas
with GNU Lesser General Public License v3.0
from acnicholas
public Result OnStartup(UIControlledApplication application)
{
ribbonPanel = TryGetPanel(application, "Scott Carver");
if (ribbonPanel == null)
{
return Result.Failed;
}
var scdll = new Uri(replacedembly.Getreplacedembly(typeof(SCaddinsApp)).CodeBase).LocalPath;
ribbonPanel.AddItem(LoadScexport(scdll));
ribbonPanel.AddStackedItems(
LoadSCopy(scdll, 16),
LoadSCuv(scdll),
LoadHatchEditor(scdll));
ribbonPanel.AddStackedItems(
LoadSCaos(scdll),
LoadSCightlines(scdll),
LoadSCasfar(scdll));
ribbonPanel.AddStackedItems(
LoadScheduleExporter(scdll),
LoadSCloudShed(scdll),
LoadSCoord(scdll));
ribbonPanel.AddStackedItems(
LoadSCulcase(scdll),
LoadSpellingChecker(scdll),
LoadSCincrement(scdll));
ribbonPanel.AddStackedItems(
LoadNextSheet(scdll),
LoadPreviousSheet(scdll),
LoadOpenSheet(scdll));
ribbonPanel.AddStackedItems(
LoadSCwash(scdll),
LoadModelWizard(scdll),
LoadAbout(scdll));
ribbonPanel.AddSlideOut();
ribbonPanel.AddStackedItems(
LoadGlobalSettings(scdll),
LoadRunScript(scdll));
return Result.Succeeded;
}
19
Source : RunScriptCommand.cs
with GNU Lesser General Public License v3.0
from acnicholas
with GNU Lesser General Public License v3.0
from acnicholas
private static string[] Getreplacedemblies()
{
var scdll = new Uri(System.Reflection.replacedembly.Getreplacedembly(typeof(SCaddinsApp)).CodeBase).LocalPath;
var revitVersion = "2016";
#if REVIT2017
revitVersion = "2017";
#elif REVIT2018
revitVersion = "2018";
#elif REVIT2019
revitVersion = "2019";
#elif REVIT2020
revitVersion = "2020";
#endif
// ReSharper disable once StringLiteralTypo
string[] replacedemblies = { @"C:\Program Files\Autodesk\Revit " + revitVersion + @"\RevitAPI.dll", @"C:\Program Files\Autodesk\Revit " + revitVersion + @"\RevitAPIUI.dll", scdll };
return replacedemblies;
}
19
Source : ExampleDisplay.cs
with GNU General Public License v3.0
from adam8797
with GNU General Public License v3.0
from adam8797
public string ReadFile()
{
using (var file = replacedembly.Getreplacedembly(GetType()).GetManifestResourceStream("ExampleProject.ExampleCode." + _textFile))
using (var reader = new StreamReader(file))
{
return reader.ReadToEnd();
}
}
19
Source : Hotkeys.cs
with MIT License
from adrenak
with MIT License
from adrenak
[MenuItem("Edit/HotKeys/Toggle Lock &q")]
static void ToggleInspectorLock() {
if (_mouseOverWindow == null) {
if (!EditorPrefs.HasKey("LockableInspectorIndex"))
EditorPrefs.SetInt("LockableInspectorIndex", 0);
int i = EditorPrefs.GetInt("LockableInspectorIndex");
Type type = replacedembly.Getreplacedembly(typeof(Editor)).GetType("UnityEditor.InspectorWindow");
Object[] findObjectsOfTypeAll = Resources.FindObjectsOfTypeAll(type);
_mouseOverWindow = (EditorWindow)findObjectsOfTypeAll[i];
}
if (_mouseOverWindow != null && _mouseOverWindow.GetType().Name == "InspectorWindow") {
Type type = replacedembly.Getreplacedembly(typeof(Editor)).GetType("UnityEditor.InspectorWindow");
PropertyInfo propertyInfo = type.GetProperty("isLocked");
bool value = (bool)propertyInfo.GetValue(_mouseOverWindow, null);
propertyInfo.SetValue(_mouseOverWindow, !value, null);
_mouseOverWindow.Repaint();
}
}
19
Source : Hotkeys.cs
with MIT License
from adrenak
with MIT License
from adrenak
[MenuItem("Edit/HotKeys/Clear Console %&c")]
static void ClearConsole() {
Type type = replacedembly.Getreplacedembly(typeof(Editor)).GetType("UnityEditorInternal.LogEntries");
type.GetMethod("Clear").Invoke(null, null);
}
19
Source : PostProcessingInspector.cs
with MIT License
from AdultLink
with MIT License
from AdultLink
void OnEnable()
{
if (target == null)
return;
// Aggregate custom post-fx editors
var replacedembly = replacedembly.Getreplacedembly(typeof(PostProcessingInspector));
var editorTypes = replacedembly.GetTypes()
.Where(x => x.IsDefined(typeof(PostProcessingModelEditorAttribute), false));
var customEditors = new Dictionary<Type, PostProcessingModelEditor>();
foreach (var editor in editorTypes)
{
var attr = (PostProcessingModelEditorAttribute)editor.GetCustomAttributes(typeof(PostProcessingModelEditorAttribute), false)[0];
var effectType = attr.type;
var alwaysEnabled = attr.alwaysEnabled;
var editorInst = (PostProcessingModelEditor)Activator.CreateInstance(editor);
editorInst.alwaysEnabled = alwaysEnabled;
editorInst.profile = target as PostProcessingProfile;
editorInst.inspector = this;
customEditors.Add(effectType, editorInst);
}
// ... and corresponding models
var baseType = target.GetType();
var property = serializedObject.Gereplacederator();
while (property.Next(true))
{
if (!property.hasChildren)
continue;
var type = baseType;
var srcObject = ReflectionUtils.GetFieldValueFromPath(serializedObject.targetObject, ref type, property.propertyPath);
if (srcObject == null)
continue;
PostProcessingModelEditor editor;
if (customEditors.TryGetValue(type, out editor))
{
var effect = (PostProcessingModel)srcObject;
if (editor.alwaysEnabled)
effect.enabled = editor.alwaysEnabled;
m_CustomEditors.Add(editor, effect);
editor.target = effect;
editor.serializedProperty = property.Copy();
editor.OnPreEnable();
}
}
// Prepare monitors
m_Monitors = new List<PostProcessingMonitor>();
var monitors = new List<PostProcessingMonitor>
{
new HistogramMonitor(),
new WaveformMonitor(),
new ParadeMonitor(),
new VectorscopeMonitor()
};
var monitorNames = new List<GUIContent>();
foreach (var monitor in monitors)
{
if (monitor.IsSupported())
{
monitor.Init(m_ConcreteTarget.monitors, this);
m_Monitors.Add(monitor);
monitorNames.Add(monitor.GetMonitorreplacedle());
}
}
m_MonitorNames = monitorNames.ToArray();
if (m_Monitors.Count > 0)
m_ConcreteTarget.monitors.onFrameEndEditorOnly = OnFrameEnd;
}
19
Source : ExtensionTests.cs
with MIT License
from AElfProject
with MIT License
from AElfProject
[Fact]
public void FindContractTests()
{
{
var code = ReadCode(replacedembly.Getreplacedembly(typeof(StructuredState)).Location);
var asm = replacedembly.Load(code);
Should.Throw<NullReferenceException>(() => asm.FindContractContainer());
asm.FindContractBaseType().ShouldBeNull();
Should.Throw<InvalidOperationException>(() => asm.FindContractType().ShouldBeNull());
asm.FindExecutionObserverProxyType().ShouldBeNull();
}
{
var code = ReadContractCode(typeof(TestContract));
var asm = replacedembly.Load(code);
asm.FindContractContainer().ShouldNotBeNull();
asm.FindContractBaseType().ShouldNotBeNull();
asm.FindContractType().ShouldNotBeNull();
asm.FindExecutionObserverProxyType().ShouldBeNull();
}
{
var code = ReadPatchedContractCode(typeof(TestContract));
var asm = replacedembly.Load(code);
asm.FindContractContainer().ShouldNotBeNull();
asm.FindContractBaseType().ShouldNotBeNull();
asm.FindContractType().ShouldNotBeNull();
asm.FindExecutionObserverProxyType().ShouldNotBeNull();
}
}
19
Source : CSharpCodeOpsTestBase.cs
with MIT License
from AElfProject
with MIT License
from AElfProject
protected byte[] ReadContractCode(Type contractType)
{
var location = Path.Combine(ContractDllDir, replacedembly.Getreplacedembly(contractType).ManifestModule.Name);
return ReadCode( location);
}
19
Source : CSharpCodeOpsTestBase.cs
with MIT License
from AElfProject
with MIT License
from AElfProject
protected ModuleDefinition GetModule(Type type)
{
var code = ReadCode(replacedembly.Getreplacedembly(type).Location);
var modDef = ModuleDefinition.ReadModule(new MemoryStream(code));
return modDef;
}
19
Source : InstranceMaker.cs
with MIT License
from AiursoftWeb
with MIT License
from AiursoftWeb
private static object GenerateWithConstructor(Type type)
{
// Has default constructor.
if (type.GetConstructors().Length == 1 &&
!type.GetConstructors()[0].GetParameters().Any() &&
!type.IsAbstract)
{
return replacedembly.Getreplacedembly(type)?.CreateInstance(type.FullName ?? string.Empty);
}
else if (type.GetConstructors().Any(t => t.IsPublic) && !type.IsAbstract)
{
// Has a constructor, and constructor has some arguments.
var constructor = type.GetConstructors()[0];
var args = constructor.GetParameters();
object[] parameters = new object[args.Length];
for (int i = 0; i < args.Length; i++)
{
var requirement = args[i].ParameterType;
parameters[i] = Make(requirement);
}
return replacedembly.Getreplacedembly(type)?.CreateInstance(type.FullName ?? string.Empty, true, BindingFlags.Default, null, parameters, null, null);
}
else if (type.IsAbstract)
{
return null;
}
else if (!type.GetConstructors().Any(t => t.IsPublic))
{
return null;
}
else
{
return replacedembly.Getreplacedembly(type)?.CreateInstance(type.FullName ?? string.Empty);
}
}
19
Source : NodeEditorReflection.cs
with MIT License
from aksyr
with MIT License
from aksyr
public static void OpenPreferences() {
try {
#if UNITY_2018_3_OR_NEWER
SettingsService.OpenUserPreferences("Preferences/Node Editor");
#else
//Open preferences window
replacedembly replacedembly = replacedembly.Getreplacedembly(typeof(UnityEditor.EditorWindow));
Type type = replacedembly.GetType("UnityEditor.PreferencesWindow");
type.GetMethod("ShowPreferencesWindow", BindingFlags.NonPublic | BindingFlags.Static).Invoke(null, null);
//Get the window
EditorWindow window = EditorWindow.GetWindow(type);
//Make sure custom sections are added (because waiting for it to happen automatically is too slow)
FieldInfo refreshField = type.GetField("m_RefreshCustomPreferences", BindingFlags.NonPublic | BindingFlags.Instance);
if ((bool) refreshField.GetValue(window)) {
type.GetMethod("AddCustomSections", BindingFlags.NonPublic | BindingFlags.Instance).Invoke(window, null);
refreshField.SetValue(window, false);
}
//Get sections
FieldInfo sectionsField = type.GetField("m_Sections", BindingFlags.Instance | BindingFlags.NonPublic);
IList sections = sectionsField.GetValue(window) as IList;
//Iterate through sections and check contents
Type sectionType = sectionsField.FieldType.GetGenericArguments() [0];
FieldInfo sectionContentField = sectionType.GetField("content", BindingFlags.Instance | BindingFlags.Public);
for (int i = 0; i < sections.Count; i++) {
GUIContent sectionContent = sectionContentField.GetValue(sections[i]) as GUIContent;
if (sectionContent.text == "Node Editor") {
//Found contents - Set index
FieldInfo sectionIndexField = type.GetField("m_SelectedSectionIndex", BindingFlags.Instance | BindingFlags.NonPublic);
sectionIndexField.SetValue(window, i);
return;
}
}
#endif
} catch (Exception e) {
Debug.LogError(e);
Debug.LogWarning("Unity has changed around internally. Can't open properties through reflection. Please contact xNode developer and supply unity version number.");
}
}
19
Source : NodeDataCache.cs
with MIT License
from aksyr
with MIT License
from aksyr
private static void BuildCache() {
portDataCache = new PortDataCache();
System.Type baseType = typeof(Node);
List<System.Type> nodeTypes = new List<System.Type>();
System.Reflection.replacedembly[] replacedemblies = System.AppDomain.CurrentDomain.Getreplacedemblies();
replacedembly selfreplacedembly = replacedembly.Getreplacedembly(baseType);
if (selfreplacedembly.FullName.StartsWith("replacedembly-CSharp") && !selfreplacedembly.FullName.Contains("-firstpreplaced")) {
// If xNode is not used as a DLL, check only CSharp (fast)
nodeTypes.AddRange(selfreplacedembly.GetTypes().Where(t => !t.IsAbstract && baseType.IsreplacedignableFrom(t)));
} else {
// Else, check all relevant DDLs (slower)
// ignore all unity related replacedemblies
foreach (replacedembly replacedembly in replacedemblies) {
if (replacedembly.FullName.StartsWith("Unity")) continue;
// unity created replacedemblies always have version 0.0.0
if (!replacedembly.FullName.Contains("Version=0.0.0")) continue;
nodeTypes.AddRange(replacedembly.GetTypes().Where(t => !t.IsAbstract && baseType.IsreplacedignableFrom(t)).ToArray());
}
}
for (int i = 0; i < nodeTypes.Count; i++) {
CachePorts(nodeTypes[i]);
}
}
19
Source : GameServer.cs
with GNU General Public License v3.0
from AlanMorel
with GNU General Public License v3.0
from AlanMorel
public void Start()
{
List<Guild> guilds = DatabaseManager.Guilds.FindAll();
foreach (Guild guild in guilds)
{
GuildManager.AddGuild(guild);
}
ushort port = ushort.Parse(Environment.GetEnvironmentVariable("GAME_PORT"));
Start(port);
CommandManager.RegisterAll(replacedembly.Getreplacedembly(typeof(CommandBase)));
Sessions = new();
Logger.Info("Game Server Started.".ColorGreen());
}
19
Source : LogEntry.cs
with MIT License
from alen-smajic
with MIT License
from alen-smajic
static void Initialize()
{
if (_type == null)
{
var flags = BindingFlags.Instance | BindingFlags.Public;
var replacedembly = replacedembly.Getreplacedembly(typeof(Editor));
_type = replacedembly.GetType("UnityEditorInternal.LogEntry");
if (_type == null) // 2017 Fix
{
_type = replacedembly.GetType("UnityEditor.LogEntry");
}
_condition = _type.GetField("condition", flags);
_errorNum = _type.GetField("errorNum", flags);
_file = _type.GetField("file", flags);
_line = _type.GetField("line", flags);
_mode = _type.GetField("mode", flags);
_instanceID = _type.GetField("instanceID", flags);
_identifier = _type.GetField("identifier", flags);
_isWorldPlaying = _type.GetField("isWorldPlaying", flags);
instance = Activator.CreateInstance(_type);
}
}
19
Source : PythonConsole.cs
with MIT License
from AlexLemminG
with MIT License
from AlexLemminG
static string GlobalreplacedemblyImport(){
var import = new StringBuilder();
import.Append ("\nimport ");
bool importedOne = false;
var globalTypes = replacedembly.Getreplacedembly (typeof(PythonConsole)).GetTypes ();
foreach (var type in globalTypes) {
if (type.IsPublic && type.Namespace == null) {
if (importedOne) {
import.Append (',');
} else {
importedOne = true;
}
import.Append (type.Name);
}
}
return import.ToString ();
}
19
Source : BotFactory.cs
with Apache License 2.0
from AlexWan
with Apache License 2.0
from AlexWan
static Dictionary<string, Type> GetTypesWithBotAttribute()
{
replacedembly replacedembly = replacedembly.Getreplacedembly(typeof(BotPanel));
Dictionary<string, Type> bots = new Dictionary<string, Type>();
foreach(Type type in replacedembly.GetTypes())
{
object[] attributes = type.GetCustomAttributes(typeof(BotAttribute), false);
if (attributes.Length > 0)
{
bots[((BotAttribute) attributes[0]).Name] = type;
}
}
return bots;
}
19
Source : EditorUI.cs
with MIT License
from allenwp
with MIT License
from allenwp
public static unsafe void SubmitUI(EnreplacedyAdmin admin)
{
if (replacedemblies == null)
{
replacedemblies = new Dictionary<string, replacedembly>();
replacedemblies["Game replacedembly"] = Program.Gamereplacedembly;
replacedemblies["VectorEngine"] = replacedembly.Getreplacedembly(typeof(VectorEngine.EnreplacedyAdmin));
replacedemblies["VectorEngine.Extras"] = replacedembly.Getreplacedembly(typeof(VectorEngine.Extras.Util.EditorUtil));
replacedemblies["Host replacedembly"] = replacedembly.GetExecutingreplacedembly();
}
var enreplacedyToComponentGroups = EnreplacedyAdminUtil.GetEnreplacedyToComponentGroupsMapping(admin, out ComponentGroup[] componentGroups);
SubmitMainMenu();
SubmitSystemsWindow(admin);
SubmitSceneGraphWindow(admin);
SubmitEnreplacediesWindow(admin, enreplacedyToComponentGroups);
SubmitInspectorWindow(admin);
SubmitMidiWindow();
SubmitInvokeWindow();
SubmitComponentGroupFilesWindow(admin);
SubmitComponentGroupsWindow(admin, componentGroups);
CleanUp(admin);
}
19
Source : TestRunner.cs
with MIT License
from alonf
with MIT License
from alonf
public static IEnumerable<object[]> GetTests(int numTests)
{
var result =
from type in replacedembly.Getreplacedembly(typeof(TestRunner))!.GetTypes()
from property in type.GetProperties(
BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)
let testCaseAttribute = property.GetCustomAttribute<TestCase>()
where testCaseAttribute != null
select new[] {testCaseAttribute.TestName, property.GetValue(null)}.Take(numTests).ToArray();
return result;
}
19
Source : Utils.cs
with MIT License
from Alprog
with MIT License
from Alprog
public static Type GetreplacedemblyType(string name)
{
return replacedembly.Getreplacedembly(typeof(Utils)).GetType(name);
}
19
Source : Utils.cs
with MIT License
from Alprog
with MIT License
from Alprog
public static Type[] GetreplacedemblyTypes()
{
return replacedembly.Getreplacedembly(typeof(Utils)).GetTypes();
}
19
Source : Program.cs
with MIT License
from anastasios-stamoulis
with MIT License
from anastasios-stamoulis
void run() {
var ver = System.Reflection.replacedembly.Getreplacedembly(typeof(CNTK.Trainer)).FullName;
Console.WriteLine(ver);
load_data();
create_network();
train_network();
evaluate_network();
}
19
Source : ModbusServer.cs
with MIT License
from AndreasAmMueller
with MIT License
from AndreasAmMueller
private Response HandleEncapsulatedInterface(Request request)
{
var response = new Response(request);
if (request.MEIType != MEIType.ReadDeviceInformation)
{
response.ErrorCode = ErrorCode.IllegalFunction;
return response;
}
if ((byte)request.MEIObject < 0x00 ||
(byte)request.MEIObject > 0xFF ||
((byte)request.MEIObject > 0x06 && (byte)request.MEIObject < 0x80))
{
response.ErrorCode = ErrorCode.IllegalDataAddress;
return response;
}
if (request.MEICategory < DeviceIDCategory.Basic || request.MEICategory > DeviceIDCategory.Individual)
{
response.ErrorCode = ErrorCode.IllegalDataValue;
return response;
}
string version = replacedembly.Getreplacedembly(typeof(ModbusServer))
.GetCustomAttribute<replacedemblyInformationalVersionAttribute>()
.InformationalVersion;
response.MEIType = request.MEIType;
response.MEICategory = request.MEICategory;
var dict = new Dictionary<DeviceIDObject, string>();
switch (request.MEICategory)
{
case DeviceIDCategory.Basic:
response.ConformityLevel = 0x01;
dict.Add(DeviceIDObject.VendorName, "AM.WD");
dict.Add(DeviceIDObject.ProductCode, "AM.WD-MBS-TCP");
dict.Add(DeviceIDObject.MajorMinorRevision, version);
break;
case DeviceIDCategory.Regular:
response.ConformityLevel = 0x02;
dict.Add(DeviceIDObject.VendorName, "AM.WD");
dict.Add(DeviceIDObject.ProductCode, "AM.WD-MBS-TCP");
dict.Add(DeviceIDObject.MajorMinorRevision, version);
dict.Add(DeviceIDObject.VendorUrl, "https://github.com/AndreasAmMueller/Modbus");
dict.Add(DeviceIDObject.ProductName, "AM.WD Modbus");
dict.Add(DeviceIDObject.ModelName, "TCP Server");
dict.Add(DeviceIDObject.UserApplicationName, "Modbus TCP Server");
break;
case DeviceIDCategory.Extended:
response.ConformityLevel = 0x03;
dict.Add(DeviceIDObject.VendorName, "AM.WD");
dict.Add(DeviceIDObject.ProductCode, "AM.WD-MBS-TCP");
dict.Add(DeviceIDObject.MajorMinorRevision, version);
dict.Add(DeviceIDObject.VendorUrl, "https://github.com/AndreasAmMueller/Modbus");
dict.Add(DeviceIDObject.ProductName, "AM.WD Modbus");
dict.Add(DeviceIDObject.ModelName, "TCP Server");
dict.Add(DeviceIDObject.UserApplicationName, "Modbus TCP Server");
break;
case DeviceIDCategory.Individual:
switch (request.MEIObject)
{
case DeviceIDObject.VendorName:
response.ConformityLevel = 0x81;
dict.Add(DeviceIDObject.VendorName, "AM.WD");
break;
case DeviceIDObject.ProductCode:
response.ConformityLevel = 0x81;
dict.Add(DeviceIDObject.ProductCode, "AM.WD-MBS-TCP");
break;
case DeviceIDObject.MajorMinorRevision:
response.ConformityLevel = 0x81;
dict.Add(DeviceIDObject.MajorMinorRevision, version);
break;
case DeviceIDObject.VendorUrl:
response.ConformityLevel = 0x82;
dict.Add(DeviceIDObject.VendorUrl, "https://github.com/AndreasAmMueller/Modbus");
break;
case DeviceIDObject.ProductName:
response.ConformityLevel = 0x82;
dict.Add(DeviceIDObject.ProductName, "AM.WD Modbus");
break;
case DeviceIDObject.ModelName:
response.ConformityLevel = 0x82;
dict.Add(DeviceIDObject.ModelName, "TCP Server");
break;
case DeviceIDObject.UserApplicationName:
response.ConformityLevel = 0x82;
dict.Add(DeviceIDObject.UserApplicationName, "Modbus TCP Server");
break;
default:
response.ConformityLevel = 0x83;
dict.Add(request.MEIObject, "Custom Data for " + request.MEIObject);
break;
}
break;
}
response.MoreRequestsNeeded = false;
response.NextObjectId = 0x00;
response.ObjectCount = (byte)dict.Count;
response.Data = new DataBuffer();
foreach (var kvp in dict)
{
byte[] bytes = Encoding.ASCII.GetBytes(kvp.Value);
response.Data.AddByte((byte)kvp.Key);
response.Data.AddByte((byte)bytes.Length);
response.Data.AddBytes(bytes);
}
return response;
}
19
Source : QuickSettingsViewController.cs
with MIT License
from andruzzzhka
with MIT License
from andruzzzhka
protected override void DidActivate(bool firstActivation, ActivationType activationType)
{
if (firstActivation)
{
_settings = new GameObject("Multiplayer Quick Settings").AddComponent<Settings>();
BSMLParser.instance.Parse(Utilities.GetResourceContent(replacedembly.Getreplacedembly(this.GetType()), "BeatSaberMultiplayer.UI.ViewControllers.RoomScreen.QuickSettingsViewController"), gameObject, _settings);
}
}
19
Source : AutofacModuleRegister.cs
with Apache License 2.0
from anjoy8
with Apache License 2.0
from anjoy8
protected override void Load(ContainerBuilder builder)
{
var basePath = AppContext.BaseDirectory;
//builder.RegisterType<AdvertisementServices>().As<IAdvertisementServices>();
#region 带有接口层的服务注入
var servicesDllFile = Path.Combine(basePath, "Blog.Core.Services.dll");
var repositoryDllFile = Path.Combine(basePath, "Blog.Core.Repository.dll");
if (!(File.Exists(servicesDllFile) && File.Exists(repositoryDllFile)))
{
var msg = "Repository.dll和service.dll 丢失,因为项目解耦了,所以需要先F6编译,再F5运行,请检查 bin 文件夹,并拷贝。";
log.Error(msg);
throw new Exception(msg);
}
// AOP 开关,如果想要打开指定的功能,只需要在 appsettigns.json 对应对应 true 就行。
var cacheType = new List<Type>();
if (Appsettings.app(new string[] { "AppSettings", "RedisCachingAOP", "Enabled" }).ObjToBool())
{
builder.RegisterType<BlogRedisCacheAOP>();
cacheType.Add(typeof(BlogRedisCacheAOP));
}
if (Appsettings.app(new string[] { "AppSettings", "MemoryCachingAOP", "Enabled" }).ObjToBool())
{
builder.RegisterType<BlogCacheAOP>();
cacheType.Add(typeof(BlogCacheAOP));
}
if (Appsettings.app(new string[] { "AppSettings", "TranAOP", "Enabled" }).ObjToBool())
{
builder.RegisterType<BlogTranAOP>();
cacheType.Add(typeof(BlogTranAOP));
}
if (Appsettings.app(new string[] { "AppSettings", "LogAOP", "Enabled" }).ObjToBool())
{
builder.RegisterType<BlogLogAOP>();
cacheType.Add(typeof(BlogLogAOP));
}
builder.RegisterGeneric(typeof(BaseRepository<>)).As(typeof(IBaseRepository<>)).InstancePerDependency();//注册仓储
// 获取 Service.dll 程序集服务,并注册
var replacedemblysServices = replacedembly.LoadFrom(servicesDllFile);
builder.RegisterreplacedemblyTypes(replacedemblysServices)
.AsImplementedInterfaces()
.InstancePerDependency()
.PropertiesAutowired()
.EnableInterfaceInterceptors()//引用Autofac.Extras.DynamicProxy;
.InterceptedBy(cacheType.ToArray());//允许将拦截器服务的列表分配给注册。
// 获取 Repository.dll 程序集服务,并注册
var replacedemblysRepository = replacedembly.LoadFrom(repositoryDllFile);
builder.RegisterreplacedemblyTypes(replacedemblysRepository)
.AsImplementedInterfaces()
.PropertiesAutowired()
.InstancePerDependency();
#endregion
#region 没有接口层的服务层注入
//因为没有接口层,所以不能实现解耦,只能用 Load 方法。
//注意如果使用没有接口的服务,并想对其使用 AOP 拦截,就必须设置为虚方法
//var replacedemblysServicesNoInterfaces = replacedembly.Load("Blog.Core.Services");
//builder.RegisterreplacedemblyTypes(replacedemblysServicesNoInterfaces);
#endregion
#region 没有接口的单独类,启用clreplaced代理拦截
//只能注入该类中的虚方法,且必须是public
//这里仅仅是一个单独类无接口测试,不用过多追问
builder.RegisterreplacedemblyTypes(replacedembly.Getreplacedembly(typeof(Love)))
.EnableClreplacedInterceptors()
.InterceptedBy(cacheType.ToArray());
#endregion
#region 单独注册一个含有接口的类,启用interface代理拦截
//不用虚方法
//builder.RegisterType<AopService>().As<IAopService>()
// .AsImplementedInterfaces()
// .EnableInterfaceInterceptors()
// .InterceptedBy(typeof(BlogCacheAOP));
#endregion
}
19
Source : BasketScenarioBase.cs
with MIT License
from anjoy8
with MIT License
from anjoy8
public TestServer CreateServer()
{
var path = replacedembly.Getreplacedembly(typeof(BasketScenarioBase))
.Location;
var hostBuilder = new WebHostBuilder()
.UseContentRoot(Path.GetDirectoryName(path))
.ConfigureAppConfiguration(cb =>
{
cb.AddJsonFile("appsettings.json", optional: false)
.AddEnvironmentVariables();
}).UseStartup<BasketTestsStartup>();
return new TestServer(hostBuilder);
}
19
Source : CatalogScenarioBase.cs
with MIT License
from anjoy8
with MIT License
from anjoy8
public TestServer CreateServer()
{
var path = replacedembly.Getreplacedembly(typeof(CatalogScenariosBase))
.Location;
var hostBuilder = new WebHostBuilder()
.UseContentRoot(Path.GetDirectoryName(path))
.ConfigureAppConfiguration(cb =>
{
cb.AddJsonFile("appsettings.json", optional: false)
.AddEnvironmentVariables();
})
.UseStartup<Startup>();
var testServer = new TestServer(hostBuilder);
testServer.Host
.MigrateDbContext<CatalogContext>((context, services) =>
{
var env = services.GetService<IWebHostEnvironment>();
var settings = services.GetService<IOptions<CatalogSettings>>();
var logger = services.GetService<ILogger<CatalogContextSeed>>();
new CatalogContextSeed()
.SeedAsync(context, env, settings, logger)
.Wait();
})
.MigrateDbContext<IntegrationEventLogContext>((_, __) => { });
return testServer;
}
19
Source : LocationsScenarioBase.cs
with MIT License
from anjoy8
with MIT License
from anjoy8
public TestServer CreateServer()
{
var path = replacedembly.Getreplacedembly(typeof(LocationsScenarioBase))
.Location;
var hostBuilder = new WebHostBuilder()
.UseContentRoot(Path.GetDirectoryName(path))
.ConfigureAppConfiguration(cb =>
{
cb.AddJsonFile("appsettings.json", optional: false)
.AddEnvironmentVariables();
}).UseStartup<LocationsTestsStartup>();
return new TestServer(hostBuilder);
}
19
Source : MarketingScenarioBase.cs
with MIT License
from anjoy8
with MIT License
from anjoy8
public TestServer CreateServer()
{
var path = replacedembly.Getreplacedembly(typeof(MarketingScenarioBase))
.Location;
var hostBuilder = new WebHostBuilder()
.UseContentRoot(Path.GetDirectoryName(path))
.ConfigureAppConfiguration(cb =>
{
cb.AddJsonFile("appsettings.json", optional: false)
.AddEnvironmentVariables();
})
.CaptureStartupErrors(true)
.UseStartup<MarketingTestsStartup>();
var testServer = new TestServer(hostBuilder);
testServer.Host
.MigrateDbContext<MarketingContext>((context, services) =>
{
var logger = services.GetService<ILogger<MarketingContextSeed>>();
new MarketingContextSeed()
.SeedAsync(context, logger)
.Wait();
});
return testServer;
}
19
Source : MarketingScenariosBase.cs
with MIT License
from anjoy8
with MIT License
from anjoy8
public TestServer CreateServer()
{
var path = replacedembly.Getreplacedembly(typeof(MarketingScenariosBase))
.Location;
var hostBuilder = new WebHostBuilder()
.UseContentRoot(Path.GetDirectoryName(path))
.ConfigureAppConfiguration(cb =>
{
cb.AddJsonFile("Services/Marketing/appsettings.json", optional: false)
.AddEnvironmentVariables();
}).UseStartup<MarketingTestsStartup>();
var testServer = new TestServer(hostBuilder);
testServer.Host
.MigrateDbContext<MarketingContext>((context, services) =>
{
var logger = services.GetService<ILogger<MarketingContextSeed>>();
new MarketingContextSeed()
.SeedAsync(context, logger)
.Wait();
});
return testServer;
}
19
Source : OrderingScenarioBase.cs
with MIT License
from anjoy8
with MIT License
from anjoy8
public TestServer CreateServer()
{
var path = replacedembly.Getreplacedembly(typeof(OrderingScenarioBase))
.Location;
var hostBuilder = new WebHostBuilder()
.UseContentRoot(Path.GetDirectoryName(path))
.ConfigureAppConfiguration(cb =>
{
cb.AddJsonFile("appsettings.json", optional: false)
.AddEnvironmentVariables();
}).UseStartup<OrderingTestsStartup>();
var testServer = new TestServer(hostBuilder);
testServer.Host
.MigrateDbContext<OrderingContext>((context, services) =>
{
var env = services.GetService<IWebHostEnvironment>();
var settings = services.GetService<IOptions<OrderingSettings>>();
var logger = services.GetService<ILogger<OrderingContextSeed>>();
new OrderingContextSeed()
.SeedAsync(context, env, settings, logger)
.Wait();
})
.MigrateDbContext<IntegrationEventLogContext>((_, __) => { });
return testServer;
}
19
Source : BasketScenariosBase.cs
with MIT License
from anjoy8
with MIT License
from anjoy8
public TestServer CreateServer()
{
var path = replacedembly.Getreplacedembly(typeof(BasketScenariosBase))
.Location;
var hostBuilder = new WebHostBuilder()
.UseContentRoot(Path.GetDirectoryName(path))
.ConfigureAppConfiguration(cb =>
{
cb.AddJsonFile("Services/Basket/appsettings.json", optional: false)
.AddEnvironmentVariables();
}).UseStartup<BasketTestsStartup>();
return new TestServer(hostBuilder);
}
19
Source : CatalogScenariosBase.cs
with MIT License
from anjoy8
with MIT License
from anjoy8
public TestServer CreateServer()
{
var path = replacedembly.Getreplacedembly(typeof(CatalogScenariosBase))
.Location;
var hostBuilder = new WebHostBuilder()
.UseContentRoot(Path.GetDirectoryName(path))
.ConfigureAppConfiguration(cb =>
{
cb.AddJsonFile("Services/Catalog/appsettings.json", optional: false)
.AddEnvironmentVariables();
}).UseStartup<Startup>();
var testServer = new TestServer(hostBuilder);
testServer.Host
.MigrateDbContext<CatalogContext>((context, services) =>
{
var env = services.GetService<IWebHostEnvironment>();
var settings = services.GetService<IOptions<CatalogSettings>>();
var logger = services.GetService<ILogger<CatalogContextSeed>>();
new CatalogContextSeed()
.SeedAsync(context, env, settings, logger)
.Wait();
})
.MigrateDbContext<IntegrationEventLogContext>((_, __) => { });
return testServer;
}
19
Source : LocationsScenariosBase.cs
with MIT License
from anjoy8
with MIT License
from anjoy8
public TestServer CreateServer()
{
var path = replacedembly.Getreplacedembly(typeof(LocationsScenariosBase))
.Location;
var hostBuilder = new WebHostBuilder()
.UseContentRoot(Path.GetDirectoryName(path))
.ConfigureAppConfiguration(cb =>
{
cb.AddJsonFile("Services/Location/appsettings.json", optional: false)
.AddEnvironmentVariables();
}).UseStartup<LocationsTestsStartup>();
var testServer = new TestServer(hostBuilder);
return testServer;
}
19
Source : OrderingScenariosBase.cs
with MIT License
from anjoy8
with MIT License
from anjoy8
public TestServer CreateServer()
{
var path = replacedembly.Getreplacedembly(typeof(OrderingScenariosBase))
.Location;
var hostBuilder = new WebHostBuilder()
.UseContentRoot(Path.GetDirectoryName(path))
.ConfigureAppConfiguration(cb =>
{
cb.AddJsonFile("Services/Ordering/appsettings.json", optional: false)
.AddEnvironmentVariables();
}).UseStartup<OrderingTestsStartup>();
var testServer = new TestServer(hostBuilder);
testServer.Host
.MigrateDbContext<OrderingContext>((context, services) =>
{
var env = services.GetService<IWebHostEnvironment>();
var settings = services.GetService<IOptions<OrderingSettings>>();
var logger = services.GetService<ILogger<OrderingContextSeed>>();
new OrderingContextSeed()
.SeedAsync(context, env, settings, logger)
.Wait();
})
.MigrateDbContext<IntegrationEventLogContext>((_, __) => { });
return testServer;
}
19
Source : Seeder.cs
with MIT License
from AntonioFalcao
with MIT License
from AntonioFalcao
private static void SeedProducts(this ModelBuilder modelBuilder)
{
var types = replacedembly.Getreplacedembly(typeof(Product))?.GetTypes()
.Where(type => type.IsClreplaced && type.IsAbstract is false && type.IsSubclreplacedOf(typeof(Product)));
var productIds = ProductIds.ToList();
types?.ToList().ForEach(type =>
{
var products = Enumerable.Range(0, Amount)
.Select(index =>
{
Guid? productId = productIds.FirstOrDefault();
var product = new
{
Id = productId == default(Guid) ? Guid.NewGuid() : productId,
Description = Faker.Commerce.ProductDescription(),
IntroduceAt = Faker.Date.FutureOffset(),
Name = Faker.Commerce.ProductName(),
PhotoUrl = Faker.Image.PicsumUrl(width:500, height:375, blur: true),
Price = Convert.ToDecimal(Faker.Commerce.Price()),
ProductTypeId = Faker.PickRandom(ProductTypes).Id,
Rating = Faker.Random.Int(0, 10),
Stock = Faker.Random.Int(0, 5000),
Size = Faker.Random.Int(20, 30),
AmountOfPerson = Faker.Random.Int(1, 3),
Option = Faker.PickRandom<Option>(),
BackpackType = Faker.PickRandom<BackpackType>(),
BootType = Faker.PickRandom<BootType>(),
KayakType = Faker.PickRandom<KayakType>()
};
productIds.Remove(productId.Value);
return product;
});
modelBuilder
.Enreplacedy(type)
.HasData(products);
});
}
19
Source : GridPortalComponentEditor.cs
with GNU Lesser General Public License v3.0
from ApexGameTools
with GNU Lesser General Public License v3.0
from ApexGameTools
private void ShowActionSelector()
{
var portal = this.target as GridPortalComponent;
object pa = portal.As<IPortalAction>();
if (pa == null)
{
pa = portal.As<IPortalActionFactory>();
}
if (pa == null)
{
if (_actionsList == null)
{
_actionsList = new List<KeyValuePair<string, Type>>();
var asm = replacedembly.Getreplacedembly(typeof(GridPortalComponent));
foreach (var actionType in asm.GetTypes().Where(t => (typeof(IPortalActionFactory).IsreplacedignableFrom(t) || typeof(IPortalAction).IsreplacedignableFrom(t)) && t.IsSubclreplacedOf(typeof(MonoBehaviour)) && t.IsClreplaced && !t.IsAbstract))
{
var actionName = actionType.Name;
var acm = Attribute.GetCustomAttribute(actionType, typeof(AddComponentMenu)) as AddComponentMenu;
if (acm != null)
{
var startIdx = acm.componentMenu.LastIndexOf('/') + 1;
actionName = acm.componentMenu.Substring(startIdx);
}
var pair = new KeyValuePair<string, Type>(actionName, actionType);
_actionsList.Add(pair);
}
_actionsList.Sort((a, b) => a.Key.CompareTo(b.Key));
_actionsNames = _actionsList.Select(p => p.Key).ToArray();
}
EditorGUILayout.Separator();
var style = new GUIStyle(GUI.skin.label);
style.normal.textColor = Color.yellow;
EditorGUILayout.LabelField("Select a Portal Action", style);
var selectedActionIdx = EditorGUILayout.Popup(-1, _actionsNames);
if (selectedActionIdx >= 0)
{
portal.gameObject.AddComponent(_actionsList[selectedActionIdx].Value);
}
}
}
19
Source : BaseAndroidSetup.cs
with Apache License 2.0
from AppRopio
with Apache License 2.0
from AppRopio
public override IEnumerable<replacedembly> GetViewreplacedemblies()
{
var result = base.GetViewreplacedemblies();
var replacedemblyList = result.ToList();
var viewreplacedemblies = Mvx.IoCProvider.Resolve<IViewLookupService>().replacedemblies;
viewreplacedemblies.ForEach(x =>
{
if (!replacedemblyList.Any(a => a.FullName == x.FullName))
replacedemblyList.Add(x);
});
replacedemblyList.Add(replacedembly.Getreplacedembly((typeof(BaseAndroidSetup))));
return replacedemblyList;
}
19
Source : BaseIosSetup.cs
with Apache License 2.0
from AppRopio
with Apache License 2.0
from AppRopio
public override IEnumerable<replacedembly> GetViewreplacedemblies()
{
var result = base.GetViewreplacedemblies();
var replacedemblyList = result.ToList();
var viewreplacedemblies = Mvx.IoCProvider.Resolve<IViewLookupService>().replacedemblies;
viewreplacedemblies.ForEach(x =>
{
if (!replacedemblyList.Any(a => a.FullName == x.FullName))
replacedemblyList.Add(x);
});
replacedemblyList.Add(replacedembly.Getreplacedembly((typeof(BaseIosSetup))));
return replacedemblyList;
}
19
Source : ServerSettingsInspector.cs
with MIT License
from ArcturusZhang
with MIT License
from ArcturusZhang
public void Awake()
{
this.versionPhoton = System.Reflection.replacedembly.Getreplacedembly(typeof(PhotonPeer)).GetName().Version.ToString();
}
19
Source : SmartEnum.cs
with MIT License
from ardalis
with MIT License
from ardalis
private static TEnum[] GetAllOptions()
{
Type baseType = typeof(TEnum);
return replacedembly.Getreplacedembly(baseType)
.GetTypes()
.Where(t => baseType.IsreplacedignableFrom(t))
.SelectMany(t => t.GetFieldsOfType<TEnum>())
.OrderBy(t => t.Name)
.ToArray();
}
19
Source : Program.cs
with GNU Affero General Public License v3.0
from arklumpus
with GNU Affero General Public License v3.0
from arklumpus
static async Task Main(string[] args)
{
ConsoleColor defaultBackground = Console.BackgroundColor;
ConsoleColor defaultForeground = Console.ForegroundColor;
Console.WriteLine();
Console.WriteLine("MuPDFCore test suite");
Console.WriteLine();
Console.WriteLine("Loading tests...");
replacedembly testreplacedembly = replacedembly.Getreplacedembly(typeof(MuPDFWrapperTests));
Type[] types = testreplacedembly.GetTypes();
List<(string, Func<Task>)> tests = new List<(string, Func<Task>)>();
HashSet<string> filesToDeploy = new HashSet<string>();
for (int i = 0; i < types.Length; i++)
{
bool found = false;
Attribute[] typeAttributes = Attribute.GetCustomAttributes(types[i]);
foreach (Attribute attr in typeAttributes)
{
if (attr is TestClreplacedAttribute)
{
found = true;
break;
}
}
if (found)
{
MethodInfo[] methods = types[i].GetMethods(BindingFlags.Public | BindingFlags.Instance);
foreach (MethodInfo method in methods)
{
bool foundMethod = false;
foreach (Attribute attr in method.GetCustomAttributes())
{
if (attr is TestMethodAttribute)
{
foundMethod = true;
}
if (attr is DeploymenreplacedemAttribute dia)
{
filesToDeploy.Add(dia.Path);
}
}
if (foundMethod)
{
Type type = types[i];
tests.Add((types[i].Name + "." + method.Name, async () =>
{
object obj = Activator.CreateInstance(type);
object returnValue = method.Invoke(obj, null);
if (returnValue is Task task)
{
await task;
}
}
));
}
}
}
}
int longestTestNameLength = (from el in tests select el.Item1.Length).Max();
Console.WriteLine();
Console.BackgroundColor = ConsoleColor.Blue;
Console.Write(" Found {0} tests. ", tests.Count.ToString());
Console.BackgroundColor = defaultBackground;
Console.WriteLine();
Console.WriteLine();
Console.WriteLine("{0} files will be deployed:", filesToDeploy.Count.ToString());
foreach (string sr in filesToDeploy)
{
Console.WriteLine(" " + sr);
}
Console.WriteLine();
string deploymentPath = Path.GetTempFileName();
File.Delete(deploymentPath);
Directory.CreateDirectory(deploymentPath);
foreach (string sr in filesToDeploy)
{
File.Copy(sr, Path.Combine(deploymentPath, Path.GetFileName(sr)));
}
string originalCurrentDirectory = Directory.GetCurrentDirectory();
Directory.SetCurrentDirectory(deploymentPath);
Console.WriteLine("Deployment completed.");
Console.WriteLine();
Console.WriteLine("Running tests...");
Console.WriteLine();
List<(string, Func<Task>)> failedTests = new List<(string, Func<Task>)>();
for (int i = 0; i < tests.Count; i++)
{
Console.Write(tests[i].Item1 + new string(' ', longestTestNameLength - tests[i].Item1.Length + 1));
bool failed = false;
Stopwatch sw = Stopwatch.StartNew();
try
{
await tests[i].Item2();
sw.Stop();
}
catch (Exception ex)
{
sw.Stop();
failed = true;
failedTests.Add(tests[i]);
Console.BackgroundColor = ConsoleColor.Red;
Console.Write(" Failed ");
Console.BackgroundColor = defaultBackground;
Console.Write(" {0}ms", sw.ElapsedMilliseconds.ToString());
Console.WriteLine();
while (ex.InnerException != null)
{
Console.WriteLine(ex.Message);
ex = ex.InnerException;
}
Console.WriteLine(ex.Message);
}
if (!failed)
{
Console.BackgroundColor = ConsoleColor.Green;
Console.Write(" Succeeded ");
Console.BackgroundColor = defaultBackground;
Console.Write(" {0}ms", sw.ElapsedMilliseconds.ToString());
}
Console.WriteLine();
}
Console.WriteLine();
if (failedTests.Count < tests.Count)
{
Console.BackgroundColor = ConsoleColor.Green;
Console.Write(" {0} tests succeeded ", tests.Count - failedTests.Count);
Console.BackgroundColor = defaultBackground;
Console.WriteLine();
}
if (failedTests.Count > 0)
{
Console.BackgroundColor = ConsoleColor.Red;
Console.Write(" {0} tests failed ", failedTests.Count);
Console.BackgroundColor = defaultBackground;
Console.WriteLine();
Console.WriteLine();
Console.WriteLine("Failed tests:");
Console.ForegroundColor = ConsoleColor.Red;
for (int i= 0; i < failedTests.Count; i++)
{
Console.WriteLine(" {0}", failedTests[i].Item1);
}
Console.WriteLine();
Console.ForegroundColor = defaultForeground;
Console.WriteLine();
Console.WriteLine("The failed tests will now be repeated one by one.");
for (int i = 0; i < failedTests.Count; i++)
{
Console.WriteLine();
Console.WriteLine("Press any key to continue...");
Console.WriteLine();
Console.ReadKey();
Console.Write(failedTests[i].Item1 + new string(' ', longestTestNameLength - failedTests[i].Item1.Length + 1));
bool failed = false;
try
{
await failedTests[i].Item2();
}
catch (Exception ex)
{
failed = true;
Console.BackgroundColor = ConsoleColor.Red;
Console.Write(" Failed ");
Console.BackgroundColor = defaultBackground;
Console.WriteLine();
while (ex.InnerException != null)
{
Console.WriteLine(ex.Message);
ex = ex.InnerException;
}
Console.WriteLine(ex.Message);
}
if (!failed)
{
Console.BackgroundColor = ConsoleColor.Green;
Console.Write(" Succeeded ");
Console.BackgroundColor = defaultBackground;
}
Console.WriteLine();
}
}
Directory.SetCurrentDirectory(originalCurrentDirectory);
Directory.Delete(deploymentPath, true);
}
19
Source : GlobalSettings.cs
with GNU Affero General Public License v3.0
from arklumpus
with GNU Affero General Public License v3.0
from arklumpus
internal static void SaveSettings()
{
try
{
string settingsPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), replacedembly.Getreplacedembly(typeof(Modules)).GetName().Name, "settings.json");
File.WriteAllText(settingsPath, System.Text.Json.JsonSerializer.Serialize(GlobalSettings.Settings, SerializationOptions));
}
catch
{
}
}
19
Source : ModuleCreatorWindow.axaml.cs
with GNU Affero General Public License v3.0
from arklumpus
with GNU Affero General Public License v3.0
from arklumpus
private async Task InitializeEditor(string moduleSource, string editorId)
{
this.FindControl<ScrollViewer>("TemplateScrollViewer").IsVisible = false;
Modules.RebuildCachedReferences();
Modules.CachedReferences.Add(CachedMetadataReference.CreateFromFile(Path.Combine(Path.GetDirectoryName(System.Reflection.replacedembly.Getreplacedembly(typeof(Modules)).Location), "PhyloTree.TreeNode.dll"), Path.Combine(Path.GetDirectoryName(System.Reflection.replacedembly.Getreplacedembly(typeof(Modules)).Location), "PhyloTree.TreeNode.xml")));
Modules.CachedReferences.Add(CachedMetadataReference.CreateFromFile(Path.Combine(Path.GetDirectoryName(System.Reflection.replacedembly.Getreplacedembly(typeof(Modules)).Location), "MuPDFCore.dll"), Path.Combine(Path.GetDirectoryName(System.Reflection.replacedembly.Getreplacedembly(typeof(Modules)).Location), "MuPDFCore.xml")));
Modules.CachedReferences.Add(CachedMetadataReference.CreateFromFile(Path.Combine(Path.GetDirectoryName(System.Reflection.replacedembly.Getreplacedembly(typeof(Modules)).Location), "MathNet.Numerics.dll"), Path.Combine(Path.GetDirectoryName(System.Reflection.replacedembly.Getreplacedembly(typeof(Modules)).Location), "MathNet.Numerics.xml")));
Editor editor = await Editor.Create(moduleSource, references: Modules.CachedReferences, guid: editorId);
editor.Background = this.Background;
editor.Margin = new Thickness(0, -10, 0, -10);
this.CodeEditor = editor;
Grid.SetRow(editor, 2);
this.FindControl<Grid>("EditorContainer").Children.Add(editor);
this.FindControl<Grid>("EditorContainerGrid").IsVisible = true;
this.FindControl<MarkdownCanvasControl>("ManualCanvas").Renderer.RasterImageLoader = image => new VectSharp.MuPDFUtils.RasterImageFile(image);
this.FindControl<MarkdownCanvasControl>("ManualCanvas").Renderer.ImageMultiplier *= 1.4;
this.FindControl<MarkdownCanvasControl>("ManualCanvas").Renderer.ImageUnitMultiplier /= 1.4;
this.FindControl<Button>("CancelButton").Click += (s, e) =>
{
this.Close();
};
RibbonBar bar = new RibbonBar(new (string, bool)[] { ("Source code", false), ("Manual", false) }) { FontSize = 15 };
if (GlobalSettings.Settings.RibbonStyle == GlobalSettings.RibbonStyles.Colourful)
{
this.FindControl<Grid>("RibbonBarContainer").Background = new Avalonia.Media.SolidColorBrush(Avalonia.Media.Color.FromRgb(0, 114, 178));
bar.Margin = new Thickness(-1, 0, -1, 0);
bar.Clreplacedes.Add("Colorful");
}
else
{
bar.Clreplacedes.Add("Grey");
}
this.FindControl<Grid>("RibbonBarContainer").Children.Add(bar);
RibbonTabContent tabContent = new RibbonTabContent(new List<(string, List<(string, Control, string, List<(string, Control, string)>, bool, double, Action<int>, string)>)>()
{
("Encode in Base64", new List<(string, Control, string, List<(string, Control, string)>, bool, double, Action<int>, string)>()
{
("Encode binary file", new DPIAwareBox(Icons.GetIcon32("TreeViewer.replacedets.BinaryFile")) { Width = 32, Height = 32 }, null, new List<(string, Control, string)>(), true, 0, (Action<int>)(async _ =>{ await EncodeBinaryFileInBase64(); }), "Embeds a binary file in the code using base-64 encoding."),
("Encode text file", new DPIAwareBox(Icons.GetIcon32("TreeViewer.replacedets.TextFile")) { Width = 32, Height = 32 }, null, new List<(string, Control, string)>(), true, 0, (Action<int>)(async _ =>{ await EncodeTextFileInBase64(); }), "Embeds a text file in the code using base-64 encoding."),
})
});
this.FindControl<Grid>("RibbonTabContainer").Children.Add(tabContent);
TransformOperations.Builder builder = new TransformOperations.Builder(1);
builder.AppendTranslate(-16, 0);
TransformOperations offScreen = builder.Build();
bar.PropertyChanged += async (s, e) =>
{
if (e.Property == RibbonBar.SelectedIndexProperty)
{
int newIndex = (int)e.NewValue;
if (newIndex == 0)
{
this.FindControl<MarkdownCanvasControl>("ManualCanvas").ZIndex = 0;
this.FindControl<MarkdownCanvasControl>("ManualCanvas").RenderTransform = offScreen;
this.FindControl<MarkdownCanvasControl>("ManualCanvas").Opacity = 0;
this.FindControl<MarkdownCanvasControl>("ManualCanvas").IreplacedTestVisible = false;
this.FindControl<Grid>("EditorContainer").ZIndex = 1;
this.FindControl<Grid>("EditorContainer").RenderTransform = TransformOperations.Idenreplacedy;
this.FindControl<Grid>("EditorContainer").Opacity = 1;
this.FindControl<Grid>("EditorContainer").IreplacedTestVisible = true;
}
else
{
this.FindControl<Grid>("EditorContainer").ZIndex = 0;
this.FindControl<Grid>("EditorContainer").RenderTransform = offScreen;
this.FindControl<Grid>("EditorContainer").Opacity = 0;
this.FindControl<Grid>("EditorContainer").IreplacedTestVisible = false;
this.FindControl<MarkdownCanvasControl>("ManualCanvas").ZIndex = 1;
this.FindControl<MarkdownCanvasControl>("ManualCanvas").RenderTransform = TransformOperations.Idenreplacedy;
this.FindControl<MarkdownCanvasControl>("ManualCanvas").Opacity = 1;
this.FindControl<MarkdownCanvasControl>("ManualCanvas").IreplacedTestVisible = true;
await Avalonia.Threading.Dispatcher.UIThread.InvokeAsync(async () =>
{
await Task.Delay(150);
string markdownSource = "";
try
{
List<string> originalReferences = new List<string>();
string fullSource = editor.FullSource;
foreach (Microsoft.Codereplacedysis.MetadataReference reference in editor.References)
{
try
{
originalReferences.Add(reference.Display);
}
catch { }
}
ModuleMetadata metadata = ModuleMetadata.CreateFromSource(fullSource, originalReferences.ToArray());
markdownSource = metadata.BuildReadmeMarkdown();
this.FindControl<MarkdownCanvasControl>("ManualCanvas").DoreplacedentSource = markdownSource;
}
catch (Exception ex)
{
this.FindControl<MarkdownCanvasControl>("ManualCanvas").DoreplacedentSource = "";
MessageBox box = new MessageBox("Attention", "An error occurred while creating the manual for the module!\n" + ex.Message + "\n" + ex.StackTrace + "\n" + markdownSource);
await box.ShowDialog2(this);
}
});
}
}
};
this.FindControl<Button>("OKButton").Click += async (s, e) =>
{
editor.Save();
EventWaitHandle handle = new EventWaitHandle(false, EventResetMode.ManualReset);
ProgressWindow window = new ProgressWindow(handle) { IsIndeterminate = false, ProgressText = "Removing unnecessary references..." };
List<string> originalReferences = new List<string>();
string fullSource = editor.FullSource;
foreach (Microsoft.Codereplacedysis.MetadataReference reference in editor.References)
{
try
{
originalReferences.Add(reference.Display);
}
catch { }
}
try
{
ModuleMetadata.CreateFromSource(fullSource, originalReferences.ToArray());
Thread thr = new Thread(async () =>
{
handle.WaitOne();
List<string> toBeRemoved = new List<string>();
List<string> newReferences = new List<string>(originalReferences);
for (int j = 0; j < originalReferences.Count; j++)
{
List<string> currentReferences = new List<string>(newReferences);
currentReferences.Remove(originalReferences[j]);
try
{
ModuleMetadata.CreateFromSource(fullSource, currentReferences.ToArray());
toBeRemoved.Add(originalReferences[j]);
newReferences = currentReferences;
}
catch
{
}
await Dispatcher.UIThread.InvokeAsync(() => window.Progress = (double)(j + 1) / originalReferences.Count);
}
for (int j = 0; j < toBeRemoved.Count; j++)
{
originalReferences.Remove(toBeRemoved[j]);
}
await Dispatcher.UIThread.InvokeAsync(() => { window.Close(); });
});
thr.Start();
await window.ShowDialog2(this);
try
{
(replacedembly replacedembly, Microsoft.Codereplacedysis.CSharp.CSharpCompilation compilation) = await editor.Compile(DebuggerServer.SynchronousBreak(editor), DebuggerServer.AsynchronousBreak(editor));
Type[] types = replacedembly.GetTypes();
Type moduleType = null;
foreach (Type type in types)
{
if (type.Name == "MyModule")
{
moduleType = type;
break;
}
}
ModuleMetadata metadata = ModuleMetadata.CreateFromSource(fullSource, originalReferences.ToArray());
this.loadAdditionalModule = () =>
{
Module loadedModule = metadata.Load(moduleType, true);
Modules.LoadModule(metadata, loadedModule);
return Task.CompletedTask;
};
this.Close();
}
catch (Exception ex)
{
MessageBox box = new MessageBox("Attention", "An error occurred while compiling the module!\n" + ex.Message);
await box.ShowDialog2(this);
}
}
catch (Exception ex)
{
MessageBox box = new MessageBox("Attention", "An error occurred while compiling the module!\n" + ex.Message);
await box.ShowDialog2(this);
}
};
}
19
Source : MainWindowViewModel.cs
with GNU General Public License v3.0
from Artentus
with GNU General Public License v3.0
from Artentus
private async Task UpdateAsync(bool showResultMessage)
{
if (DownloadQueue.IsJobInProgress)
{
// Updating while downloads are in progress could result in invalid states
await Messages.UpdateWhileDownloading.Show();
}
else
{
bool includePrerelease = VersionStatistics.AppVersion.IsPrerelease || Program.Settings.Get(SettingName.UpdatePrerelease, false);
var (available, version, url, changelog) = await PrepareUpdateAsync(includePrerelease, showResultMessage);
if (available)
{
Log.Information("Found update version {0}", version);
var vm = new UpdateWindowViewModel(version!, changelog!);
var window = View.CreateAndAttach(vm);
await window.ShowDialog(AttachedView);
string fileName = Path.Combine(Program.TemporaryDirectory.FullName, Path.GetFileName(url!));
if ((vm.DialogResult == DialogResult.Ok) && (await DownloadUpdateAsync(url!, fileName)))
{
var metaData = replacedemblyMetadata.Fromreplacedembly(replacedembly.Getreplacedembly(typeof(App))!);
var resolver = new ManualPackageResolver(fileName, version!);
var updateManager = new UpdateManager(metaData, resolver, new ZipPackageExtractor());
var result = await updateManager.CheckForUpdatesAsync();
await updateManager.PrepareUpdateAsync(result.LastVersion!);
string args = "--no-update";
if (!string.IsNullOrEmpty(Program.RestartArgs)) args += " " + Program.RestartArgs;
updateManager.LaunchUpdater(result.LastVersion!, true, args);
Log.Information("Shutting down for update");
AttachedView!.Close();
}
}
else
{
Log.Information("No updates available");
if (showResultMessage) await Messages.NoUpdateFound.Show();
}
}
}
19
Source : UnityDebugViewerWindowUtility.cs
with Apache License 2.0
from AsanCai
with Apache License 2.0
from AsanCai
public static void ClearNativeConsoleWindow()
{
replacedembly unityEditorreplacedembly = replacedembly.Getreplacedembly(typeof(EditorWindow));
Type logEntriesType = unityEditorreplacedembly.GetType("UnityEditor.LogEntries");
if (logEntriesType == null)
{
logEntriesType = unityEditorreplacedembly.GetType("UnityEditorInternal.LogEntries");
if (logEntriesType == null)
{
return;
}
}
object logEntriesInstance = Activator.CreateInstance(logEntriesType);
var clearMethod = logEntriesType.GetMethod("Clear", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
if (clearMethod != null)
{
clearMethod.Invoke(logEntriesInstance, null);
}
var getCountMethod = logEntriesType.GetMethod("GetCount", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
if (getCountMethod == null)
{
return;
}
int count = (int)getCountMethod.Invoke(logEntriesInstance, null);
if (count > 0)
{
Type logEntryType = unityEditorreplacedembly.GetType("UnityEditor.LogEntry");
if (logEntryType == null)
{
logEntryType = unityEditorreplacedembly.GetType("UnityEditorInternal.LogEntry");
if (logEntryType == null)
{
return;
}
}
object logEntryInstacne = Activator.CreateInstance(logEntryType);
var startGettingEntriesMethod = logEntriesType.GetMethod("StartGettingEntries", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
var endGettingEntriesMethod = logEntriesType.GetMethod("EndGettingEntries", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
var getEntryInternalMethod = logEntriesType.GetMethod("GetEntryInternal", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
if (startGettingEntriesMethod == null || endGettingEntriesMethod == null || getEntryInternalMethod == null)
{
return;
}
var infoFieldInfo = logEntryType.GetField("message", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
if (infoFieldInfo == null)
{
infoFieldInfo = logEntryType.GetField("condition", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
if (infoFieldInfo == null)
{
return;
}
}
string info;
startGettingEntriesMethod.Invoke(logEntriesInstance, null);
for (int i = 0; i < count; i++)
{
getEntryInternalMethod.Invoke(logEntriesInstance, new object[] { i, logEntryInstacne });
if (logEntryInstacne == null)
{
continue;
}
info = infoFieldInfo.GetValue(logEntryInstacne).ToString();
UnityDebugViewerLogger.AddLog(info, string.Empty, LogType.Error, UnityDebugViewerDefaultMode.Editor);
}
endGettingEntriesMethod.Invoke(logEntriesInstance, null);
}
}
19
Source : NodeAssemblies.cs
with MIT License
from ashblue
with MIT License
from ashblue
private static Dictionary<Type, Type> GetDataToDisplay () {
var displayTypes = replacedembly
.Getreplacedembly(typeof(NodeEditorBase))
.GetTypes()
.Where(t => t.IsSubclreplacedOf(typeof(NodeEditorBase)));
return displayTypes.ToDictionary(
(k) => {
var attribute = k.GetCustomAttribute<NodeTypeAttribute>();
return attribute.Type;
},
(v) => v);
}
19
Source : NodeAssemblies.cs
with MIT License
from ashblue
with MIT License
from ashblue
private static Dictionary<string, Type> GetStringToData () {
var menuTypes = replacedembly
.Getreplacedembly(typeof(NodeDataBase))
.GetTypes()
.Where(t => t.IsSubclreplacedOf(typeof(NodeDataBase))
&& t.GetCustomAttribute<CreateMenuAttribute>() != null)
.OrderByDescending(t => t.GetCustomAttribute<CreateMenuAttribute>().Priority);
return menuTypes.ToDictionary(
(k) => {
var attribute = k.GetCustomAttribute<CreateMenuAttribute>();
return attribute.Path;
},
(v) => v);
}
See More Examples