// Stolen from the guts of MEF ConventionBuilder code, // supports the default type selection logic of // ConventionBuilder.ForTypesDerivedFrom<T>() internal static bool IsGenericDescendentOf(TypeInfo openType, TypeInfo baseType) { if (openType.BaseType == null) { return(false); } if (openType.BaseType == baseType.AsType()) { return(true); } foreach (Type type in openType.ImplementedInterfaces) { if (type.IsConstructedGenericType && type.GetGenericTypeDefinition() == baseType.AsType()) { return(true); } } return(MefExtensions.IsGenericDescendentOf(IntrospectionExtensions.GetTypeInfo(openType.BaseType), baseType)); }
public X509Certificate2Collection loadCertificate(string name, string password = "") { var assembly = IntrospectionExtensions.GetTypeInfo(typeof(MainPage)).Assembly; var stream = assembly.GetManifestResourceStream(string.Format("controller.{0}", name)); var memoryStream = new MemoryStream(); stream.CopyTo(memoryStream); var cert = new X509Certificate2Collection(); if (string.IsNullOrEmpty(password)) { cert.Import(memoryStream.ToArray()); } else { cert.Import(memoryStream.ToArray(), password, X509KeyStorageFlags.UserKeySet); } return(cert); }
public override Assembly LoadAssembly(string name) { if (name.StartsWith("mscorlib")) { return(IntrospectionExtensions.GetTypeInfo(typeof(object)).Assembly); } if (name == "IronRuby, Version=1.1.4.0, Culture=neutral, PublicKeyToken=7f709c5b713576e1") { return(IntrospectionExtensions.GetTypeInfo(typeof(Ruby)).Assembly); } if (name == "IronRuby.Libraries, Version=1.1.4.0, Culture=neutral, PublicKeyToken=7f709c5b713576e1") { return(IntrospectionExtensions.GetTypeInfo(typeof(Integer)).Assembly); } return(base.LoadAssembly(name)); }
private static TypeInfo FindGenericBaseType(Type currentType, Type genericBaseType) { var type = currentType; while (type != null) { Console.WriteLine(type); var typeInfo = IntrospectionExtensions.GetTypeInfo(type); Console.WriteLine(typeInfo); var genericType = type.IsGenericType ? type.GetGenericTypeDefinition() : null; Console.WriteLine(genericType); if (genericType != null && genericType == genericBaseType) { return(typeInfo); } type = type.BaseType; } return(null); }
private async void UpdateMap() { try { var assembly = IntrospectionExtensions.GetTypeInfo(typeof(MapsView)).Assembly; //Stream stream = assembly.GetManifestResourceStream("tcc.Places.json"); Stream stream = assembly.GetManifestResourceStream("tcc.Barra.json"); string text = string.Empty; using (var reader = new StreamReader(stream)) { text = reader.ReadToEnd(); } var resultObject = JsonConvert.DeserializeObject <Places>(text); foreach (var place in resultObject.results) { placesList.Add(new Place { PlaceName = place.name, Address = place.vicinity, Location = place.geometry.location, Position = new Position(place.geometry.location.lat, place.geometry.location.lng), Icon = place.icon, }); } MyMap.ItemsSource = placesList; //PlacesListView.ItemsSource = placesList; //var loc = await Xamarin.Essentials.Geolocation.GetLocationAsync(); //LOCALIZAÇÃO MANUAL //MyMap.MoveToRegion(MapSpan.FromCenterAndRadius(new Position(-15.876713, -52.318660), Distance.FromKilometers(2))); //PEGA A LOCALIZACAO ATUAL //var myposition = await Plugin.Geolocator.CrossGeolocator.Current.GetPositionAsync(); //MyMap.MoveToRegion(MapSpan.FromCenterAndRadius(new Position(myposition.Latitude, myposition.Longitude), Distance.FromKilometers(5))); } catch { _ = App.Current.MainPage.DisplayAlert("Atencao", "mensagem de erro", "OK"); } }
/// <summary> /// 全局统一注册所有事件处理程序,实现了IEventHandlers的 /// 目前只支持注册显示实现IEventHandlers的处理程序,不支持匿名处理程序 /// </summary> public void SubscribeAll() { var types = AssemblyHelper.GetTypesByInterfaces(typeof(IBusHandler <>)); Dictionary <string, List <string> > keyDic = new Dictionary <string, List <string> >(); foreach (var item in types) { if (!item.IsGenericParameter) { TypeInfo typeInfo = IntrospectionExtensions.GetTypeInfo(item); foreach (var t in typeInfo.GetMethods().Where(i => i.Name == "Handle")) { //ioc name key var eventKey = t.GetParameters().First().ParameterType.Name; var key = t.GetParameters().First().ParameterType.Name + "_" + item.Name; //eventhandler var inter = typeof(IBusHandler <>).MakeGenericType(t.GetParameters().First().ParameterType); container.Register(inter, item, key); if (keyDic.ContainsKey(eventKey)) { var oldEvent = keyDic[eventKey]; oldEvent.Add(key); } else { var newEvent = new List <string>(); newEvent.Add(key); keyDic.Add(eventKey, newEvent); } } } //redis存储事件与处理程序的映射关系 foreach (var hash in keyDic) { RedisManager.Instance.GetDatabase().HashSet( ESBKEY, hash.Key.ToString(), JsonConvert.SerializeObject(hash.Value)); } } }
public static IServiceCollection AddMessageHandlers(this IServiceCollection services, string assemblyName) { var assemblyPath = Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), assemblyName + ".dll"); var assembly = Assembly.Load(AssemblyLoadContext.GetAssemblyName(assemblyPath)); var classTypes = assembly.ExportedTypes.Select(t => IntrospectionExtensions.GetTypeInfo(t)).Where(t => t.IsClass && !t.IsAbstract); foreach (var type in classTypes) { var interfaces = type.ImplementedInterfaces.Select(i => i.GetTypeInfo()); foreach (var handlerType in interfaces.Where(i => i.IsGenericType)) { services.AddTransient(handlerType.AsType(), type.AsType()); } } return(services); }
private static bool PopulateBooks() { using (SQLiteConnection conn = new SQLiteConnection(App.DatabaseLocation)) { var books = new List <Book>(); var assembly = IntrospectionExtensions.GetTypeInfo(typeof(Book)).Assembly; Stream stream = assembly.GetManifestResourceStream("SkyrimGuide.Data.Books.csv"); using (var reader = new System.IO.StreamReader(stream)) { if (reader != null) { using (var csvReader = new CsvReader(reader, CultureInfo.CurrentCulture)) { while (csvReader.Read()) { books.Add(new Book { BookTitle = csvReader.GetField <string>(0), Author = csvReader.GetField <string>(1), Description = csvReader.GetField <string>(2), Value = csvReader.GetField <string>(3), Type = csvReader.GetField <string>(4), BookLocation = csvReader.GetField <string>(5) .Replace("UK", "Understone Keep") .Replace("FH", "The Frozen Hearth - Winterhold ") .Replace("DR", "Dragonsreach") .Replace("WH", "The White Hall - Dawnstar") .Replace("FAH", "Falion's House") .Replace("BP", "The Blue Palace") .Replace("CW", "College of Winterhold") .Replace("PK", "Palace of the Kings") .Replace("MK", "Mistveil Keep") }); } } } } conn.InsertAll(books); return(true); } }
public static void Init(string rootPath) { if (IsLoaded) { return; } #if __IOS__ _resourcePrefix = "PoseSportsPredict.iOS."; #elif __ANDROID__ _resourcePrefix = "PoseSportsPredict.Android."; #endif Debug.WriteLine("Using this resource prefix: " + _resourcePrefix); _assembly = IntrospectionExtensions.GetTypeInfo(typeof(LoadingPage)).Assembly; LoadTable(rootPath); IsLoaded = true; }
private void Read() { try { var assembly = IntrospectionExtensions.GetTypeInfo(typeof(XamarinMapStyle)).Assembly; Stream stream = assembly.GetManifestResourceStream("Brot.EmbededFiles.MapStyleBrot.json"); using (var reader = new System.IO.StreamReader(stream)) { var json = reader.ReadToEnd(); this.Text = json; } } catch (Exception ex) { Debug.WriteLine(ex.Message); } }
private void EmitLoadGenricMethodArguments(MethodEmitter methodEmitter, MethodInfo method, Reference invocationLocal) { var genericParameters = method.GetGenericArguments().FindAll(t => IntrospectionExtensions.GetTypeInfo(t).IsGenericParameter); var genericParamsArrayLocal = methodEmitter.CodeBuilder.DeclareLocal(typeof(Type[])); methodEmitter.CodeBuilder.AddStatement( new AssignStatement(genericParamsArrayLocal, new NewArrayExpression(genericParameters.Length, typeof(Type)))); for (var i = 0; i < genericParameters.Length; ++i) { methodEmitter.CodeBuilder.AddStatement( new AssignArrayStatement(genericParamsArrayLocal, i, new TypeTokenExpression(genericParameters[i]))); } methodEmitter.CodeBuilder.AddExpression( new MethodInvocationExpression(invocationLocal, InvocationMethods.SetGenericMethodArguments, new ReferenceExpression( genericParamsArrayLocal))); }
private void ButtonClickStart(object sender, EventArgs e) { try { var assembly = IntrospectionExtensions.GetTypeInfo(typeof(AppForDoctors.MainPage)).Assembly; Stream stream = new FileStream(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "TEST.json"), FileMode.Open); //assembly.GetManifestResourceStream("AppForDoctors.125.json"); string text = ""; using (var reader = new System.IO.StreamReader(stream)) { text = reader.ReadToEnd(); } Des(text); NextQuestion(); } catch { DisplayAlert("ОШИБКА", "Обновите тест", "ОK"); } }
public static IServiceCollection AgregarDependencias(this IServiceCollection services, string nombreProyecto) { var assemblyRuta = Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), nombreProyecto + ".dll"); var assembly = Assembly.Load(AssemblyLoadContext.GetAssemblyName(assemblyRuta)); var tiposClases = assembly.ExportedTypes.Select(t => IntrospectionExtensions.GetTypeInfo(t)).Where(t => t.IsClass && !t.IsAbstract); foreach (var tipo in tiposClases) { var interfaces = tipo.ImplementedInterfaces.Select(i => i.GetTypeInfo()); foreach (var tipoInterfaz in interfaces.Where(i => i.IsInterface)) { services.AddTransient(tipoInterfaz.AsType(), tipo.AsType()); } } return(services); }
private AppSettingsManager() { try { // Setup the stream to read and analyze the json file. var assembly = IntrospectionExtensions.GetTypeInfo(typeof(AppSettingsManager)).Assembly; var stream = assembly.GetManifestResourceStream($"{ Namespace }.{ Filename }"); using (var reader = new StreamReader(stream)) { var json = reader.ReadToEnd(); secrets = JObject.Parse(json); } } catch (Exception e) { Crashes.TrackError(e); } }
private static bool PopulateMerchants() { using (SQLiteConnection conn = new SQLiteConnection(App.DatabaseLocation)) { var merchants = new List <Merchant>(); var assembly = IntrospectionExtensions.GetTypeInfo(typeof(Merchant)).Assembly; Stream stream = assembly.GetManifestResourceStream("SkyrimGuide.Data.Merchants.csv"); using (var reader = new System.IO.StreamReader(stream)) { if (reader != null) { using (var csvReader = new CsvReader(reader, CultureInfo.CurrentCulture)) { while (csvReader.Read()) { var newMerchant = new Merchant { Name = csvReader.GetField <string>(0), PartnerOrReplacement = csvReader.GetField <string>(1), Region = csvReader.GetField <string>(4), StoreLocationName = csvReader.GetField <string>(5), Merchandise = csvReader.GetField <string>(6), Gold = csvReader.GetField <string>(7), Investable = csvReader.GetField <string>(8).Contains("Yes"), MasterTrader = csvReader.GetField <string>(9).Contains("Yes"), Notes = csvReader.GetField <string>(10) }; if (!newMerchant.Investable) { newMerchant.Invested = null; } merchants.Add(newMerchant); } } } } conn.InsertAll(merchants); return(true); } }
protected override void OnAppearing() { if (onAppearingFirstTime) { base.OnAppearing(); searchBar.WidthRequest = this.Width - (btnNext.WidthRequest + btnPrevious.WidthRequest + 18); flexViewer.HeightRequest = this.Height - searchBar.HeightRequest; if (_pickingFile) { _pickingFile = false; return; } assembly = IntrospectionExtensions.GetTypeInfo(typeof(GettingStarted)).Assembly;; Stream stream = assembly.GetManifestResourceStream("FlexViewer101.Resources.Simple List.pdf"); flexViewer.LoadDocument(stream); onAppearingFirstTime = false; } }
public static int?TryInt(object val, bool useCulture = true) { CultureInfo info = useCulture ? CultureInfo.CurrentCulture : CultureInfo.InvariantCulture; if (val == null) { return(0); } if (IsNumber(val)) { if (val is DateTime) { return(new int?((int)DateTimeExtension.ToOADate((DateTime)val))); } if (val is TimeSpan) { TimeSpan span = (TimeSpan)val; return(new int?((int)span.TotalDays)); } try { return(new int?(Convert.ToInt32(val, (IFormatProvider)info))); } catch (InvalidCastException) { return(null); } } if (val is string) { int num; if (int.TryParse((string)(val as string), (NumberStyles)NumberStyles.Any, (IFormatProvider)info, out num)) { return(new int?(num)); } } else if (IntrospectionExtensions.GetTypeInfo(val.GetType()).IsEnum) { return(new int?((int)((int)val))); } return(null); }
/// <summary> /// Processes the data file and add food items to picker. /// </summary> private void LoadFoodFile() { //Allows access to the saved imbedded text file in the solution explorer assembly. var assembly = IntrospectionExtensions.GetTypeInfo(typeof(FoodDetailsPage)).Assembly; //Use stream to open up and find text file within the solution explorer. Stream stream = assembly.GetManifestResourceStream("MMFitnessApp.food.txt"); //String array to store each of the food items from the text file. string[] foodItem; //List of string to hold food names to populate picker. List <string> foodNames = new List <string>(); //Process the food text file. Allows to read each line in the text file. using (var reader = new StreamReader(stream)) { //Skips the headers in the food text file. reader.ReadLine(); //To loop through each line and store it in the string array. Read until not at the end of the stream. while (!reader.EndOfStream) { //Read file line for line. Array after each tab. foodItem = reader.ReadLine().Split('\t'); //Create a new food with each loop. FoodItems food = new FoodItems(foodItem); //Adding a food name from the foodItems. foodNames.Add(food.FoodName); //Provides a food for the list. foodList.Add(food); } ; } //Adds the names to the picker PckFood.ItemsSource = foodNames; }
public LoadResourceXml() { #region How to load an XML file embedded resource var assembly = IntrospectionExtensions.GetTypeInfo(typeof(LoadResourceText)).Assembly; Stream stream = assembly.GetManifestResourceStream("RussianFlashCards.Russian.xml"); List <Item> monkeys; using (var reader = new StreamReader(stream)) { var serializer = new XmlSerializer(typeof(List <Item>)); monkeys = (List <Item>)serializer.Deserialize(reader); } #endregion var listView = new ListView(); listView.ItemTemplate = new DataTemplate(() => { var textCell = new TextCell(); textCell.SetBinding(TextCell.TextProperty, "Name"); textCell.SetBinding(TextCell.DetailProperty, "Location"); return(textCell); }); listView.ItemsSource = monkeys; Content = new StackLayout { Margin = new Thickness(20), VerticalOptions = LayoutOptions.StartAndExpand, Children = { new Label { Text = "Embedded Resource XML File", FontSize = Device.GetNamedSize(NamedSize.Medium, typeof(Label)), FontAttributes = FontAttributes.Bold }, listView } }; // NOTE: use for debugging, not in released app code! //foreach (var res in assembly.GetManifestResourceNames()) // System.Diagnostics.Debug.WriteLine("found resource: " + res); }
public LoadResourceJson() { #region How to load an Json file embedded resource var assembly = IntrospectionExtensions.GetTypeInfo(typeof(LoadResourceText)).Assembly; Stream stream = assembly.GetManifestResourceStream("WorkingWithFiles.LibJsonResource.json"); Earthquake[] earthquakes; using (var reader = new StreamReader(stream)) { var json = reader.ReadToEnd(); var rootobject = JsonConvert.DeserializeObject <Rootobject>(json); earthquakes = rootobject.earthquakes; } #endregion var listView = new ListView(); listView.ItemTemplate = new DataTemplate(() => { var textCell = new TextCell(); textCell.SetBinding(TextCell.TextProperty, "Data"); return(textCell); }); listView.ItemsSource = earthquakes; Content = new StackLayout { Margin = new Thickness(20), VerticalOptions = LayoutOptions.StartAndExpand, Children = { new Label { Text = "Embedded Resource JSON File", FontSize = Device.GetNamedSize(NamedSize.Medium, typeof(Label)), FontAttributes = FontAttributes.Bold }, listView } }; // NOTE: use for debugging, not in released app code! //foreach (var res in assembly.GetManifestResourceNames()) // System.Diagnostics.Debug.WriteLine("found resource: " + res); }
private string GetText() { try { var assembly = IntrospectionExtensions.GetTypeInfo(typeof(App)).Assembly; Stream stream = assembly.GetManifestResourceStream("NAV.sources.csv"); string text = ""; using (var reader = new System.IO.StreamReader(stream)) { text = reader.ReadToEnd(); } return(text); } catch (Exception e) { Debug.WriteLine(e.Message); return("error"); } }
internal async Task <List <Banklist> > GetParticipatingBanksFromFile() { List <Banklist> bk = new List <Banklist>(); var assembly = IntrospectionExtensions.GetTypeInfo(typeof(BusinessLogic)).Assembly; Stream stream = assembly.GetManifestResourceStream("SterlingSwitch.Pages.LocalTransfer.File.GetParticipatingBanks.json"); using (var reader = new StreamReader(stream)) { var json = reader.ReadToEnd(); json = json.JsonCleanUp(); var data = JsonConvert.DeserializeObject <List <Banklist> >(json); if (data.Any()) { bk = data; return(bk); } } return(bk); }
public CustomerListSample() { try { var assembly = IntrospectionExtensions.GetTypeInfo(typeof(CustomerListSample)).Assembly; var stream = assembly.GetManifestResourceStream("PoolGuy.Mobile.Data.Models.SampleData.Customers.json"); using (var reader = new StreamReader(stream)) { var json = reader.ReadToEnd(); if (!string.IsNullOrEmpty(json)) { _customers = JsonConvert.DeserializeObject <CustomerSample[]>(json); } } } catch (Exception e) { Debug.WriteLine(e); } }
public static string ReadSupplierProductsJsonFile() { try { var assembly = IntrospectionExtensions.GetTypeInfo(typeof(ReadJson)).Assembly; Stream stream = assembly.GetManifestResourceStream("Cognizant.Hackathon.Shared.Mobile.Data.JsonFile.supplierProducts.json"); string json; using (var reader = new System.IO.StreamReader(stream)) { json = reader.ReadToEnd(); } return(json); } catch (Exception ex) { throw new Exception(ex.Message); } }
static CidadeData() { Cidades = new List <Cidade>(); var assembly = IntrospectionExtensions.GetTypeInfo(typeof(Cidade)).Assembly; Stream stream = assembly.GetManifestResourceStream("ConsultaClimaApp.city.list.json"); using (var reader = new StreamReader(stream)) { string json = reader.ReadToEnd(); ListaCidade cidades = JsonConvert.DeserializeObject <ListaCidade>(json); foreach (var cidade in cidades.data) { Cidades.Add(cidade); } } Cidades = Cidades.OrderBy(cidade => cidade.name).ToList(); }
/// <summary> /// This searches and invokes the logging configuration class. /// Override if you want to configure logging directly /// </summary> private void ConfigureLog() { var logConfig = AppAssemblies.SelectMany(a => a.GetPublicTypes(t => t.Name == ConfigureLoggerName)).FirstOrDefault(); if (logConfig == null) { return; } dynamic inst = System.TypeExtensions.CreateInstance(logConfig); var method = IntrospectionExtensions.GetTypeInfo(logConfig).GetMethod("Run"); var hasResult = method.ReturnType == typeof(Action <string>); if (hasResult) { _logger = inst.Run(_settings); return; } inst.Run(_settings); }
public static double getAreaEmission(int zipcode) { var assembly = IntrospectionExtensions.GetTypeInfo(typeof(Calculator)).Assembly; Stream stream = assembly.GetManifestResourceStream("CarbonFootprintApp.data.txt"); string text = ""; using (var reader = new System.IO.StreamReader(stream)) { text = reader.ReadToEnd(); } JObject thing = JObject.Parse(text); var result = thing["EGRID_DATA"].FirstOrDefault(i => i["Zip"].ToString() == zipcode.ToString()); double emissionRate = 0; if (result != null) { emissionRate = result["annual emission rate"].ToObject <double>(); } return(emissionRate); }
public PrivacyPoliticyPage() { InitializeComponent(); var assembly = IntrospectionExtensions.GetTypeInfo(typeof(LoadResourceText)).Assembly; Stream stream = assembly.GetManifestResourceStream("Final_App.privacyPolitics.txt"); try { using (var reader = new System.IO.StreamReader(stream)) { text = reader.ReadToEnd(); } } catch (ArgumentNullException ge) { Console.WriteLine("Argument null"); } policy.Text = text; }
public static string LoadContentString(string contentResourceName) { string result = null; if (!string.IsNullOrEmpty(contentResourceName)) { Stream stream = IntrospectionExtensions .GetTypeInfo(typeof(Documents)) .Assembly .GetManifestResourceStream($"MobileKidsIdApp.Resources.Docs.{contentResourceName}.html"); if (stream != null) { using var reader = new StreamReader(stream); result = reader.ReadToEnd(); } } return(result ?? MissingResourceContent); }
public string GetLicenseContent() { const string ROOTCLASS = "ResinTimer"; string path = string.Empty; string content = string.Empty; var assembly = IntrospectionExtensions.GetTypeInfo(typeof(LicenseViewer)).Assembly; switch (LicenseType) { case "Syncfusion License": path = $"{ROOTCLASS}.License_Syncfusion.txt"; break; case "MIT License - Microsoft Corporation": path = $"{ROOTCLASS}.License_MIT_Microsoft.txt"; break; case "MIT License - James Newton-King": path = $"{ROOTCLASS}.License_MIT_JamesNewtonKing.txt"; break; case "MIT License": path = $"{ROOTCLASS}.License_MIT.txt"; break; case "MIT License - Andrius Kirilovas": path = $"{ROOTCLASS}.License_MIT_AndriusKirilovas.txt"; break; default: return(string.Empty); } using (var reader = new StreamReader(assembly.GetManifestResourceStream(path))) { content = reader.ReadToEnd(); } return(content); }