-
MY PROJECTS
-
Recent Posts
- SQL.How can you compare two nullable values safely, and how does IS DISTINCT FROM differ from <>?
- SQL.How are NULL values ordered by ORDER BY, how do defaults differ between databases, and how can you control their placement?
- SQL.How does NULL propagate through arithmetic expressions, and how can COALESCE and NULLIF help handle missing values and division by zero?
- SQL.How does NULL affect join conditions, and why can filtering the right-hand table in WHERE remove unmatched rows from a LEFT JOIN?
- SQL.How do GROUP BY and DISTINCT treat NULL values, even though NULL = NULL evaluates to UNKNOWN?
- SQL.How do aggregate functions handle NULL, and what is the difference between COUNT(*), COUNT(column), and COUNT(DISTINCT column)?
- SQL.How does NULL affect IN and NOT IN, and why can NOT EXISTS be a safer choice when a subquery returns nullable values?
- SQL.How do WHERE, HAVING, and CHECK constraints treat conditions that evaluate to UNKNOWN?
- SQL.Why do column = NULL and column <> NULL not work as expected, and when should you use IS NULL and IS NOT NULL?
- SQL.What is SQL’s three-valued logic (TRUE, FALSE, UNKNOWN), and how do AND, OR, and NOT behave with UNKNOWN?
- ChromeDevTools.Watch all failed requests
- SQL.What are domain types (or constraints on data types), and how do they help enforce data correctness?
- SQL.How does SQL handle comparisons between different data types (for example, string vs number), and why is this dangerous?
- SQL.What is the difference between DATE, TIME, TIMESTAMP, and TIMESTAMPTZ, and which one should be used for business events?
- SQL.How do numeric types like INTEGER, BIGINT, DECIMAL, and FLOAT differ in terms of precision and use cases?
- SQL.What problems can arise from implicit type casting in SQL, and how can it affect indexes?
- SQL.How does NULL differ from 0, an empty string, or FALSE in SQL?
- SQL.What is the difference between CHAR, VARCHAR, and TEXT, and when would you choose each?
- SQL.What is MVCC ?
- SQL.What is AutoVacuum Postgres ?
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)
- Регулярные выражения
- Тестирование приложений
Category Archives: C#
C#. Threads and delegates
delegates gives functionality of creating additional threads… examples
|
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 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Threading; using System.Runtime.Remoting.Messaging; namespace SyncDelegateReview { public delegate int BinaryOp(int x, int y); class Program { private static bool isDone = false; static void Main(string[] args) { //SyncCall(); //ASyncCall(); //ASyncCall2(); // works like annoying manager, always asks if additional thread isCompleted //ASyncCall3(); // works like annoying manager, always asks if additional thread isCompleted AsyncCallBackExample(); } static int Add(int x, int y) { Console.WriteLine("Add() invoked on thread {0}", Thread.CurrentThread.ManagedThreadId ); Thread.Sleep(5000); return x+y; } static void SyncCall() // << blocks main thread { Console.WriteLine("*** Sync Delegate Review ***"); Console.WriteLine("Main() invoked on thread {0}", Thread.CurrentThread.ManagedThreadId); BinaryOp b = new BinaryOp(Add); int answer = b(10, 10); // in main thread, sync mode... Console.WriteLine("Doing more work in Main()"); Console.WriteLine("10 + 10 is {0}", answer); Console.ReadLine(); } static void ASyncCall() // << blocks main thread { Console.WriteLine("*** ASync Delegate Review ***"); Console.WriteLine("Main() invoked on thread {0}", Thread.CurrentThread.ManagedThreadId); BinaryOp b = new BinaryOp(Add); //int answer = b(10, 10); // in main thread, sync mode... IAsyncResult itf = b.BeginInvoke(10, 10, null, null); Console.WriteLine("Doing more work in Main()!"); // getting result int answer = b.EndInvoke(itf); Console.WriteLine("10 + 10 is {0}", answer); Console.ReadLine(); } static void ASyncCall2() // << allows work in main thread { Console.WriteLine("*** ASync Delegate Review ***"); Console.WriteLine("Main() invoked on thread {0}", Thread.CurrentThread.ManagedThreadId); BinaryOp b = new BinaryOp(Add); //int answer = b(10, 10); // in main thread, sync mode... IAsyncResult itf = b.BeginInvoke(10, 10, null, null); while (!itf.IsCompleted) // always ask additional thread IsCompleted and works during this { Console.WriteLine("DoingMoreWorkInMain"); Thread.Sleep(1000); } Console.WriteLine("Doing more work in Main()!"); int answer = b.EndInvoke(itf); Console.WriteLine("10 + 10 is {0}", answer); Console.ReadLine(); } static void ASyncCall3() // << allows work in main thread with max time limit { Console.WriteLine("*** ASync Delegate Review ***"); Console.WriteLine("Main() invoked on thread {0}", Thread.CurrentThread.ManagedThreadId); BinaryOp b = new BinaryOp(Add); //int answer = b(10, 10); // in main thread, sync mode... IAsyncResult itf = b.BeginInvoke(10, 10, null, null); while (!itf.AsyncWaitHandle.WaitOne(1000,true)) // max time to wait //always ask additional thread IsCompleted and works during this { Console.WriteLine("DoingMoreWorkInMain"); Thread.Sleep(1000); } Console.WriteLine("Doing more work in Main()!"); int answer = b.EndInvoke(itf); Console.WriteLine("10 + 10 is {0}", answer); Console.ReadLine(); } static void AsyncCallBackExample() { Console.WriteLine("*** ASyncCallBackExample ***"); Console.WriteLine("Main() invoked on thread {0}", Thread.CurrentThread.ManagedThreadId); BinaryOp b = new BinaryOp(Add); //int answer = b(10, 10); // in main thread, sync mode... IAsyncResult itf = b.BeginInvoke( 10, // delegate param 10, // delegate param new AsyncCallback(AddComplete), // CallBack method "Main() string object added to call back method"); // some object for call back method while (!isDone) // { Console.WriteLine("DoingMoreWorkInMain"); Thread.Sleep(1000); } Console.ReadLine(); } static void AddComplete(IAsyncResult itf) { Console.WriteLine("AddComplete() invoked on thread {0} ", Thread.CurrentThread.ManagedThreadId); AsyncResult ar = (AsyncResult)itf; BinaryOp b = (BinaryOp)ar.AsyncDelegate; string msg = (string)itf.AsyncState; // could be any object not only string... Console.WriteLine("10+10 is {0}",b.EndInvoke(itf)); Console.WriteLine("message from Main " + msg); isDone = true; } } } |
Posted in C#
Comments Off on C#. Threads and delegates
C#. Dynamic
Dynamic – key word, specialized form of object. limitations – doesn’t work to lambda, doesn’t work to extension methods when to use? reflection late binding methods COM code examples
|
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 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace dynamic { class Program { static void Main(string[] args) { ChangeDynamicDataType(); Console.ReadLine(); } static void ChangeDynamicDataType() { dynamic t = "Hello"; Console.WriteLine("t is type of {0}", t.GetType()); t = false; Console.WriteLine("t is type of {0}", t.GetType()); t = 123; Console.WriteLine("t is type of {0}", t.GetType()); t = new List<int>(); Console.WriteLine("t is type of {0}", t.GetType()); t.AnyBullShitHereWillBeCompiled(); // no checks of compilator // so use try catch !!! try { t.AnyBullShitHereWillBeCompiled(); // <<< } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex) { Console.WriteLine(ex.Message); } } } // where can we use dynamic ? class SomeDynamicClass { // field private static dynamic myDynamicField; //property public dynamic DynamicProperty { get; set; } // return value public dynamic DynamicMethod(dynamic SomeDynamicParam) { dynamic dynamicLocalVar = "local var"; int myInt = 10; if (SomeDynamicParam is int) { return dynamicLocalVar; } else { return myInt; } } } } |
Late binding example – 2 examples – with dynamic … Continue reading
Posted in C#
Comments Off on C#. Dynamic
C#. Context free and context bounded types
Process includes domain Domain includes context Example
|
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 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Runtime.Remoting.Contexts; using System.Threading; namespace ContextExamples { class Program { static void Main(string[] args) { SportsCar sc = new SportsCar(); Console.WriteLine(); SportsCar sc2 = new SportsCar(); Console.WriteLine(); // will be loaded in another context SportsCarTS synchroSC =new SportsCarTS(); Console.ReadLine(); Console.ReadLine(); } } // context free class public class SportsCar { public SportsCar() { Context ctx = Thread.CurrentContext; Console.WriteLine("{0} object in context {1}", this.ToString(), ctx.ContextID); foreach (IContextProperty itf in ctx.ContextProperties) Console.WriteLine("-> Ctx Prop: {0}", itf.Name); } } // Context bound [Synchronization] public class SportsCarTS:ContextBoundObject { public SportsCarTS() { Context ctx = Thread.CurrentContext; Console.WriteLine("{0} object in context {1}", this.ToString(), ctx.ContextID); foreach (IContextProperty itf in ctx.ContextProperties) Console.WriteLine("-> Ctx Prop: {0}", itf.Name); } } } |
Posted in C#
Comments Off on C#. Context free and context bounded types
C#. Domain. SimpleExamples
Examples shows -Display domain stats -List assemblies in domain -List assemblies in domain through LINQ -EventHandling of assembly loading -Load Unload Assemblies, HandlingEvents
|
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 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Reflection; namespace domainExamples { class Program { static void Main(string[] args) { //DisplayDomainStats(); //ListAllAssembliesInAppDomain2(); CreateNewAppDomain(); Console.ReadLine(); } static void DisplayDomainStats() { AppDomain currentDomain = AppDomain.CurrentDomain; Console.WriteLine("Name of this domain: {0}", currentDomain.FriendlyName); Console.WriteLine("ID of this domain: {0}", currentDomain.Id); Console.WriteLine("Is Default Domain ?: {0}", currentDomain.IsDefaultAppDomain()); Console.WriteLine("Base directory of this domain: {0}", currentDomain.BaseDirectory); } static void ListAllAssembliesInAppDomain() { AppDomain currentDomain = AppDomain.CurrentDomain; Assembly[] loadAssemblies=currentDomain.GetAssemblies(); Console.WriteLine("Assemblies of domain {0}",currentDomain.FriendlyName); foreach (Assembly a in loadAssemblies) { Console.WriteLine("-> Name: {0}, Version {1}", a.GetName().Name, a.GetName().Version); } } static void ListAllAssembliesInAppDomain2() { AppDomain currentDomain = AppDomain.CurrentDomain; var subset = from a in currentDomain.GetAssemblies() orderby a.GetName().Name select a; Console.WriteLine("Assemblies of domain {0}", currentDomain.FriendlyName); foreach (Assembly a in subset) { Console.WriteLine("-> Name: {0}, Version {1}", a.GetName().Name, a.GetName().Version); } } //on load assembly to domain - will message on every new assembly, loaded to domain static void InitCurrentDomain() { AppDomain currentDomain = AppDomain.CurrentDomain; currentDomain.AssemblyLoad += (o, s) => { Console.WriteLine("{0} has been loaded!",s.LoadedAssembly.GetName().Name); }; } static void CreateNewAppDomain() { AppDomain currentDomain = AppDomain.CreateDomain("AnotherDomain"); //load assembly currentDomain.Load("CarLib.dll"); // will load assembly to domain // unload domain event currentDomain.DomainUnload += (o, s) => { Console.WriteLine("The second app domain has been unloaded"); }; // ListAllAssembliesInAppDomain(currentDomain); // unload domain AppDomain.Unload(currentDomain); // will unload all assemblies with domain } static void ListAllAssembliesInAppDomain(AppDomain ad) { var loadedAssemblies = from a in ad.GetAssemblies() orderby a.GetName().Name select a; Console.WriteLine("***Loaded Assemblies in {0} ***",ad.FriendlyName); foreach (Assembly a in loadedAssemblies) { Console.WriteLine("-> Name: {0}, Version {1}", a.GetName().Name, a.GetName().Version); } } } } |
Posted in C#
Comments Off on C#. Domain. SimpleExamples
С#. Domains. Processes. Threads
Domain – container for processes. Domain include processes. It is .NET technology – to make work more safety, also for multiPlatforms, more efficient with resources consumption. Process – running program, container for threads. It has PID. Thread – way of … Continue reading
Posted in C#
Comments Off on С#. Domains. Processes. Threads
С#. 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