-
MY PROJECTS
-
Recent Posts
- Junit. Jupiter
- Java. SpringBoot Example how to work with dateTime in Specification
- Java.SpringBoot.PopularAnnotations
- SpringBoot. Exception Management
- Java.Hibernate.JoinTableAnnotation
- SpringBoot.Making our first starter and autoconfiguration
- Spring. Creating main annotation to start business logic
- Spring.Reading from properties file
- Spring.How to define spring version inside springBoot ?
- SpringBoot App inside Docker
- Kafka.FirstExperience
- Docker.MySql and Lost connection to MySQL server at ‘reading initial communication packet’, system error: 0
- Gradle.Tips
- Spring.AppConfig
- Leetcode.Best-time-to-buy-and-sell-stock
- LeetCode.ClimbStairs.Fibbonacci
- Leetcode.Roman-to-integer
- LeetCode.Palindrome-number
- Java.DesignPatterns.Lightweight
- Java.DesignPatterns.Proxy
Categories
- Aptana
- Azure
- C#
- DataSnap
- DBExpress
- Delphi
- Delphi и сети
- Delphi. Язык программирования
- ExtJS
- FastReport
- FireDAC
- FireMonkey
- GIT
- ICS
- IDE
- IIS
- Indy
- InnoSetup
- javascript
- jQuery
- JSON
- LiveBindings
- MSHTML
- MySQL
- PHP
- REST
- Ribbons
- SMS
- SQL инструкции
- SVN
- TRichView
- UniGui
- WebBroker
- WinAPI
- Windows
- Алгоритмы
- Без рубрики
- Деревья
- Ищу ответ
- Компонентостроение
- Мои компоненты
- Начальный уровень
- Обработка исключений
- Парсинг
- Потоки(Threads)
- Регулярные выражения
- Тестирование приложений
Author Archives: Stanislav_Panteleev
С#. Attributes. Practice
This example shows -reading attributes -initialize object in dependence of attributes value -reading attributes from class and from properties -early binding / late binding examples -iteration through types
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using CarLib; using Numbers; using System.Reflection; namespace AttrPracticeMain { class Program { static void Main(string[] args) { ReflectOnAttributesUsingEarlyBinding(); // early binding EvenNumbersWithIteration(); // late binding NotEvenNumbers(); // late binding EvenNumbers(); // late binding EvenNotEvenOrBoth(); // late binding EvenOddOrBothToProps(); //late binding Console.ReadLine(); } static void EvenNumbersWithIteration() { // get types Assembly asm = Assembly.LoadFile("C:\\C#\\MyC#StudyProjects\\08_Attributes\\Practice\\AttrPracticeMain\\AttrPracticeMain\\bin\\Debug\\Numbers.dll"); Type TCustomAttribute = asm.GetType("Numbers.CustomAttribute"); PropertyInfo PropertyDescription = TCustomAttribute.GetProperty("Description"); Type[] types = asm.GetTypes(); //iterate through types foreach (Type t in types) { object[] objs = t.GetCustomAttributes(TCustomAttribute, false); foreach (object o in objs) { if ((t.Name == "EvenNumbers") && (PropertyDescription.GetValue(o, null).ToString() == "EvenNumbersClass")) { // Console.WriteLine("Catched"); //Create instance and fill array with Evens object EvenNumbersObject = Activator.CreateInstance(t); (EvenNumbersObject as EvenNumbers).Content = new int[] { 2, 4, 6 }; Console.WriteLine("Success even numbers with iteration"); } } } } static void EvenNumbers() { Assembly asm = Assembly.LoadFile("C:\\C#\\MyC#StudyProjects\\08_Attributes\\Practice\\AttrPracticeMain\\AttrPracticeMain\\bin\\Debug\\Numbers.dll"); Type TCustomAttribute = asm.GetType("Numbers.CustomAttribute"); Type TEvenNumbers=asm.GetType("Numbers.EvenNumbers"); PropertyInfo PropertyDescription = TCustomAttribute.GetProperty("Description"); var myCustomAttribute= TEvenNumbers.GetCustomAttribute(TCustomAttribute); if (PropertyDescription.GetValue(myCustomAttribute, null).ToString() == "EvenNumbersClass") { // create instance and fill array object EvenNumbersObject = Activator.CreateInstance(TEvenNumbers); (EvenNumbersObject as EvenNumbers).Content = new int[] { 2, 4, 6 }; Console.WriteLine("Success with Even Numbers"); } } static void NotEvenNumbers() { Assembly asm = Assembly.LoadFile("C:\\C#\\MyC#StudyProjects\\08_Attributes\\Practice\\AttrPracticeMain\\AttrPracticeMain\\bin\\Debug\\Numbers.dll"); Type TCustomAttribute = asm.GetType("Numbers.CustomAttribute"); Type TNotEvenNumbers = asm.GetType("Numbers.NotEvenNumbers"); PropertyInfo pi = TCustomAttribute.GetProperty("Description"); var myCustomAttribute = TNotEvenNumbers.GetCustomAttribute(TCustomAttribute); if (pi.GetValue(myCustomAttribute, null).ToString() == "NotEvenNumbersClass") { // create instance and fill array object EvenNumbersObject = Activator.CreateInstance(TNotEvenNumbers); (EvenNumbersObject as NotEvenNumbers).Content = new int[] { 1, 3, 5 }; Console.WriteLine("Success with non Even Numbers"); } } static void EvenNotEvenOrBoth() { Assembly asm = Assembly.LoadFile("C:\\C#\\MyC#StudyProjects\\08_Attributes\\Practice\\AttrPracticeMain\\AttrPracticeMain\\bin\\Debug\\Numbers.dll"); Type TCustomAttribute = asm.GetType("Numbers.CustomAttribute"); Type TAllNumbers = asm.GetType("Numbers.AllNumbers"); PropertyInfo pi = TCustomAttribute.GetProperty("Description"); var myCustomAttribute = TAllNumbers.GetCustomAttribute(TCustomAttribute); if (pi.GetValue(myCustomAttribute, null).ToString() == "EvenNumbers") { // create instance and fill array object EvenNumbersObject = Activator.CreateInstance(TAllNumbers); (EvenNumbersObject as AllNumbers).Content = new int[] { 2, 4, 6 }; } else if (pi.GetValue(myCustomAttribute, null).ToString() == "NotEvenNumbers") { // create instance and fill array object EvenNumbersObject = Activator.CreateInstance(TAllNumbers); (EvenNumbersObject as AllNumbers).Content = new int[] { 1, 3, 5 }; } else if (pi.GetValue(myCustomAttribute, null).ToString() == "EvenAndUnEvenNumbers") { // create instance and fill array object NumbersObject = Activator.CreateInstance(TAllNumbers); (NumbersObject as AllNumbers).Content = new int[] { 1, 2, 3, 4, 5, 6 }; } Console. WriteLine("Success with non Even Numbers. Current option is "+ (pi.GetValue(myCustomAttribute, null).ToString())); } // read attributes early binding private static void ReflectOnAttributesUsingEarlyBinding() { Type t = typeof(SportsCar); // Knowing type SportsCar, so early binding object[] customAtts = t.GetCustomAttributes(false); foreach (Object o in customAtts) { if (o is CustomAttributeDescription) Console.WriteLine("->{0}\n", (o as CustomAttributeDescription).Description); } } //--------------- static void EvenOddOrBothToProps() { // load and define types Assembly asm = Assembly.LoadFile("C:\\C#\\MyC#StudyProjects\\08_Attributes\\Practice\\AttrPracticeMain\\AttrPracticeMain\\bin\\Debug\\Numbers.dll"); Type TCustomAttribute = asm.GetType("Numbers.CustomAttribute"); Type TAllNumbers = asm.GetType("Numbers.AllNumbers"); PropertyInfo pi = TCustomAttribute.GetProperty("Description"); var myCustomAttribute = TAllNumbers.GetCustomAttribute(TCustomAttribute); //creating instance object EvenNumbersObject = Activator.CreateInstance(TAllNumbers); // reading props and filling arrays PropertyInfo[] piArray = TAllNumbers.GetProperties(); foreach (PropertyInfo p in piArray) { var propAttr = p.GetCustomAttribute(TCustomAttribute); //if (propAttr!=null) continue; if ((propAttr != null)&&(pi.GetValue(propAttr, null).ToString() == "Even")) { (EvenNumbersObject as AllNumbers).IntArray = new int[] { 2, 4, 6 }; } if ((propAttr != null)&&(pi.GetValue(propAttr, null).ToString() == "Odd")) { // create instance and fill with evens (EvenNumbersObject as AllNumbers).AnotherIntArray = new int[] { 1, 3, 5 }; } } //check foreach (int i in (EvenNumbersObject as AllNumbers).IntArray) Console.WriteLine(i); Console.WriteLine(" "); foreach (int i in (EvenNumbersObject as AllNumbers).AnotherIntArray) Console.WriteLine(i); } } } |
Numbers
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Numbers { // defining Custom Attribute class public sealed class CustomAttribute : System.Attribute { public string Description { get; set; } public CustomAttribute(string ADescription) { Description = ADescription; } public CustomAttribute() { } } public abstract class Numbers { public int[] Content { get; set; } } [CustomAttribute("EvenNumbersClass")] public class EvenNumbers:Numbers { } [CustomAttribute("NotEvenNumbersClass")] public class NotEvenNumbers:Numbers { } [CustomAttribute("EvenNumbers")] public class AllNumbers : Numbers { } } |
CarLib
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CarLib { // defining Custom Attribute class public sealed class CustomAttributeDescription : System.Attribute { public string Description { get; set; } public CustomAttributeDescription(string ADescription) { Description = ADescription; } public CustomAttributeDescription() { } } [Serializable, CustomAttributeDescription("BaseClass")] public abstract class Car { public int MaxSpeed { get; set; } public abstract void TurboBoost(); } [Serializable, CustomAttributeDescription("It is attribute description.There is Descendent of Car")] public class SportsCar : Car { public SportsCar() { MaxSpeed = 160; } public override void TurboBoost() { Console.WriteLine(MaxSpeed+" km/h"); } } } |
Posted in C#
Comments Off on С#. Attributes. Practice
C#. Attributes
Definition Attributes – descendants of System.Attribute, some kind of annotations of code, applied for some object. Standart attributes are [CLSCompliant] – Common Language Specification [DLLImport] [Obsolete] – deprecated [Serializable] [NonSerialized] [WebMethod] Self made attributes also possible Attribute consumers Compiler, some … Continue reading
Posted in C#
Comments Off on C#. Attributes
С#. LateBindingExamples
Late binding means – we can create instance not in compilation time but in execution and call methods with or without params -invoke methods with / without params -setting private fields
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Reflection; using System.IO; namespace LateBindingApp { class Program { static void Main(string[] args) { Console.WriteLine("***Fun with Late Binding***"); Assembly a = null; try { a = Assembly.LoadFrom("C:\\C#\\MyC#StudyProjects\\07_DifferentMains\\LateBindingApp\\LateBindingApp\\bin\\Debug\\CarLibrary2.dll"); } catch (FileNotFoundException ex) { Console.WriteLine(ex.Message); return; } if (a != null) CreateUsingLateBinding(a); Console.ReadLine(); } static void CreateUsingLateBinding(Assembly asm) { try { Type miniVan = asm.GetType("CarLibrary.MiniVan"); object obj = Activator.CreateInstance(miniVan); // call method with reflection MethodInfo mi = miniVan.GetMethod("TurboBoost"); // invoke method without params mi.Invoke(obj, null); // call method with reflection with params MethodInfo mi1 = miniVan.GetMethod("TurnOnRadio"); // invoke method with params //object[] paramsArray=new object[] {true, "someRadioMessage"} mi1.Invoke(obj, new object[] { true, "someRadioMessage" }); // setting private field // typeof(Foo).GetField("_bar", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(objectForFoocClass, "newValue"); miniVan.GetField("SomeField", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(obj, "SomeValue"); // getting private field // var _barVariable = typeof(Foo).GetField("_bar", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(objectForFooClass); var fieldValue =miniVan.GetField("SomeField", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(obj); Console.WriteLine(fieldValue); Console.WriteLine("Created a {0} using late binding!", obj); } catch (Exception e) { Console.WriteLine(e.Message); } } } } |
Posted in C#
Comments Off on С#. LateBindingExamples
C#. Dynamically loaded assembly
Load and LoadFrom commands…
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Reflection; using System.IO; namespace ExternalAssemblyReflector2 { class Program { static void DisplayTypesInAsm(Assembly asm) { Console.WriteLine("***Types in assembly***"); Console.WriteLine("->{0}",asm.FullName); Type[] types = asm.GetTypes(); foreach (Type t in types) Console.WriteLine("Type :{0}",t); Console.WriteLine(""); } static void Main(string[] args) { Console.WriteLine("***External Assembly Viewer"); string asmName = ""; Assembly asm = null; do { Console.WriteLine("\nEnter assembly to evaluate"); Console.WriteLine("or enter Q to quit"); asmName = Console.ReadLine(); if (asmName.ToUpper() == "Q") { break; } try { asm = Assembly.LoadFrom(asmName); // Load also possible but LoadFrom has more wide context DisplayTypesInAsm(asm); } catch { Console.WriteLine("Sorry can't find assembly"); } } while(true); } } } |
This will give
1 2 3 4 5 6 7 8 9 10 11 |
***External Assembly Viewer Enter assembly to evaluate or enter Q to quit CarLibrary.dll ***Types in assembly*** ->CarLibrary, Version=1.0.0.0, Culture=neutral, PublicKeyToken=6a9228aea5de13fa Type :CarLibrary.EngineState Type :CarLibrary.Car Type :CarLibrary.SportsCar Type :CarLibrary.MiniVan |
Posted in C#
Comments Off on C#. Dynamically loaded assembly
C#. Reflection
Reflection – getting info about type during execution.
1 |
using System.Reflection; |
#1 Need instance and info about type, before getting type
1 2 3 4 |
SportsCar viper = new SportsCar("Viper",240,40); Type t = viper.GetType(); Console.WriteLine("Type of viper is: "+t); Console.ReadLine(); |
#2 Need info about type before getting type
1 2 |
SportsCar viper = new SportsCar("Viper",240,40); Type t = typeof(SportsCar); |
#3 in current assembly with string param
1 2 |
//in current assembly Type t = Type.GetType("CarLibrary.SportsCar",false,true); |
#4 in external … Continue reading
Posted in C#
Comments Off on C#. Reflection
C#. Shared assembly
Lets use Carlib.dll from One file Assembly 1. Strong name Properties – > Signing – > Sign the assembly -> New – > SomeName (for ex. myKeyPair.snk) 2. Install assembly to GAC (Global Assembly Cache) go to C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Visual Studio … Continue reading
Posted in C#
Comments Off on C#. Shared assembly
С#. Assembly theory
Assembly – versioned (for ex. 1.0.0.0), self described( has manifest, links to other external assemblies, info about all types) binary, supported by CLR (Common Language Runtime). One EXE is divided in may exe, dll files. Assembly defines type borders. Example. … Continue reading
Posted in C#
Comments Off on С#. Assembly theory
C#. Creating one file assembly. Example
Lets create CarLibrary.dll assembly File NewProject ClassLibrary
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CarLibrary { public enum EngineState {EngineAlive, engineDead} public abstract class Car { public string PetName { get; set; } public int CurrentSpeed { get; set; } public int MaxSpeed { get; set; } protected EngineState egnState = EngineState.EngineAlive; public EngineState EngineState {get { return egnState; }} public abstract void TurboBoost(); public Car(){} public Car(string name, int maxSp, int currSp) { PetName = name; MaxSpeed = maxSp; CurrentSpeed = currSp; } } } |
In other file Derived.cs 2 derived classes ClassView – addReference – System.Windows.Forms
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using CarLibrary; using System.Windows.Forms; namespace CarLibrary { public class SportsCar : Car { public SportsCar() { } public SportsCar(string name, int maxSp, int currSp) : base(name, maxSp, currSp) { } public override void TurboBoost() { MessageBox.Show("Turbo Boost Sports Car"); } } public class MiniVan : Car { public MiniVan() { } public MiniVan(string name, int maxSp, int currSp) : base(name, maxSp, currSp) { } public override void TurboBoost() { MessageBox.Show("Turbo Boost MiniVan"); } } } |
Now lets create new project CarClient ClassView – addReference – Browse – CarLibrary.dll
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using CarLibrary; namespace CarClient { class Program { static void Main(string[] args) { SportsCar viper = new SportsCar("Viper",240,40); viper.TurboBoost(); MiniVan mv = new MiniVan(); mv.TurboBoost(); Console.ReadLine(); } } } |
Posted in C#
Comments Off on C#. Creating one file assembly. Example
C#. Namespace examples
123
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using MyShapes; using The3DHexagon=My3DShapes.Hexagon; // alias for class with same name namespace CustomNameSpace { class Program { static void Main(string[] args) { // one way Hexagon h = new Hexagon(); Circle c = new Circle(); Square s = new Square(); //another, no need to write using MyShapes MyShapes.Hexagon h1 = new Hexagon(); MyShapes.Circle c1 = new Circle(); MyShapes.Square s1 = new Square(); // The3DHexagon h2 = new The3DHexagon(); } } namespace someEmbedded { public class SomeClass { Hexagon h = new Hexagon(); } } } |
Circle.cs
1 2 3 4 5 6 7 8 9 10 11 12 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MyShapes { class Circle { } } |
Hexagon.cs
1 2 3 4 5 6 7 8 9 10 11 12 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MyShapes { class Hexagon { } } |
Square.cs
1 2 3 4 5 6 7 8 9 10 11 12 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MyShapes { class Square { } } |
Posted in C#
Comments Off on C#. Namespace examples
C#. Delegates, Func, Action
Ну, есть ключевое слово delegate — это описание сигнатуры функции, т. е., её списка параметров и типа возвращаемого значения. Используется так:
1 |
public delegate bool MyPredicate(int x); |
Им можно пользоваться так:
1 2 3 4 5 6 7 8 9 10 |
private bool IsOdd(int i) { return i % 2 != 0; } private Analyze(MyPredicate p, int x) { bool result = p(x); if (result) Console.WriteLine("found!"); } Analyze(IsOdd, 1); // печатает "found!" |
С другой стороны, есть готовые, предопределённые сигнатуры функций (Func<TArg1, TArg2, …, TResult> с возвращаемым … Continue reading
Posted in C#
Comments Off on C#. Delegates, Func, Action