Saturday, 13 September 2014

Reflections in CSharp


Using Reflections in C#

       Tip ekzemplyarini dnamik yaratishda, tipnig mavjud ob’yekt bilan aloqasini ta’minlashda, mavjud ob’yektning tipini aniqlashda va uning metodlarini ishlatishda(chaqirishda) yoki uning maydonlari va xususiyatlariga dostup olishda Reflectiondan foydalaniladi.
Masalan,
string myStringValue=”Learning reflections in C#”;
System.Type type= myStringValue.GetType();
System.Console.WriteLine(type);
Natija: Sytem.String
Ushbu misolda GetType orqali reflection ishlatildi va ob’yektning tipi aniqlandi
     Reflection – shunday jarayonki unda dastur vaziyatga qarab o’z struktura va ko’rinishini o’zgartirishi mumkin.
Question 1: Dastur ishlayotgan vaqtda biror string tipidagi o’zgaruvchining faqat nominigina bilgan holda uning qiymatini qanday o’zgartirish mumkin?
Answer:
class Program
    {
        private static string a="test1", b="test2", c="test3";
        private static string s = "test string";
        static void Main(string[] args)
        {
            Console.WriteLine("O'zgaruvchi nomini kiriting:");
            string varName = Console.ReadLine();
            Console.WriteLine("O'zgaruvchi yangi qiymatini kiriting:");
            string newValue = Console.ReadLine();
            Type t = typeof(Program);
            FieldInfo fieldInfo=t.GetField(varName,BindingFlags.NonPublic|BindingFlags.Static);
            if (fieldInfo != null)
            {
                string varInfo1 = string.Format("{0} o'zgaruvchining joriy qimati:{1}",fieldInfo.Name,fieldInfo.GetValue(null));
                Console.WriteLine(varInfo1);
                fieldInfo.SetValue(null,newValue);
                string varInfo2 = string.Format("{0} o'zgaruvchining yangi qimati:{1}", fieldInfo.Name, fieldInfo.GetValue(null));
                Console.WriteLine(varInfo2);
            }
            else Console.WriteLine("Bunday o'zgaruvchi aniqlanmagan!");
           
            Console.ReadLine();
        }
    }

Joriy koddagi assembly(project, ya'ni assemblyni build qilganda .exe yoki .dll fayl ko'rinishga o'tadi) tiplarni(projectdagi classlar, interfacelar,…) aniqlash
Projectda quyidagilar aniqlangan bo’lsin:
namespace xyz.Test1.fullinfo
{
    public class ClassTest
    {
       //…
    }
}
namespace ReflactionTest
{
    abstract class AbstractClassTest
    {
       //…
    }
}
namespace ReflactionTest
{
    interface Interface1
    {
       //…
    }
}
Barcha assembly tiplar ro’yxatini quyidagi kod yordamida aniqlash mumkin:
namespace ReflactionTest
{
    class Program
    {
        static void Main(string[] args)
        {
            Assembly assembly = Assembly.GetExecutingAssembly();
            Type[] assemblyTypes = assembly.GetTypes();
            foreach (Type t in assemblyTypes)
                Console.WriteLine(t.Name);
            Console.ReadLine();
        }
    }
}
Natija:
ClassTest
ArstractClassTest
Interface1

Sinf nomi orqali undagi metodni Reflection yordamida ishlatish:
using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;

namespace ReflectionTest
{
    class Program
    {
        static void Main(string[] args)
        {
            Type testType = typeof(TestClass);
            ConstructorInfo ctor = testType.GetConstructor(System.Type.EmptyTypes);
            if(ctor != null)
            {
                object instance = ctor.Invoke(null);
                MethodInfo methodInfo = testType.GetMethod("TestMethod");
                Console.WriteLine(methodInfo.Invoke(instance, new object[] { 20 }));
            }
            Console.ReadKey();
        }
    }

    public class TestClass
    {
        private int testValue = 35;

        public int TestMethod(int numberToAdd)
        {
            return this.testValue + numberToAdd;
        }
    }
}

Question 2: Base Calss “bolalari”ni qanday aniqlash mumkin?
Answer 1:
Masalan, BaseClass nomi BasePerson b.sa:
 var result = AppDomain.CurrentDomain.GetAssemblies()
                       .SelectMany(assembly => assembly.GetTypes())
                       .Where(type => type.IsSubclassOf(typeof(BasePerson)));
            foreach (Type item in result)
            {
                var personObject = Activator.CreateInstance(item);
                MethodInfo methodInfo = item.GetMethod("<Person sinfidagi metod nomi>");
                //ParameterInfo[] parameters = methodInfo.GetParameters();
                object[] parameters = new object[] { parametr1,parametr2,…,parametrN };
                var methodResult = methodInfo.Invoke(personObject, parameters);
                     …
            }
Answer 2:
BaseLogic sinfi abstract shaklda aniqlangan va u check(column1,column2) metodiga ega, undan inherities olgan barcha sinflardning check metodi natijalarini olish:
` var logicList = new List<BaseLogic>();
                var types = Assembly.GetExecutingAssembly().GetTypes();
                foreach (var type in types)
                {
                    if (type.IsSubclassOf(typeof(BaseLogic)))
                    {
                        logicList.Add((BaseLogic)Activator.CreateInstance(type));
                    }
                }
Ishlatishda:
logicList.Where(w=>w.Weight<=weight).ToList().ForEach(logic=>
            {
                primeryKeyColumn.Parent = _tables.Find(f => f.ID == primeryKeyColumn.ParentID);
                forignKeyColumn.Parent = _tables.Find(f => f.ID == forignKeyColumn.ParentID);
                var relationship = logic.Check(primeryKeyColumn,forignKeyColumn);
}

Kabi bo’ladi

Used LINKS:

Thursday, 11 September 2014

CSharpda Abstract class, Interface va Collectionlardan foydalanish


Using Abstract class, Interface, Collections in C#

       Abstract class – bu class ob’yektini yaratib bo’lmaydigan class turi, uni base class sifatida ishlatish mumkin. Abstract classda abstract yoki abstract bo’lmagan metodlar va memberlardan foydalanish mumkin. Abstract classda maydon(field)ni abstract qilib yaratish MUMKIN EMAS, property(get;set;) va metodlarni abstract qilib yaratish MUMKIN.
Masalan:
 public  abstract class MyClass
{
                public abstract string Name{get;set;}      //Mumkin
                public abstract string ColumnName;       //Mumkin emas, chunki bu FIELD
                public abstract void GetValue()              //Mumkin
{
                //…
}
}

Question 1: Abstract classda aniqlangan abstract metod(yoky property) va abstract bo’lmagan metodning(yoki property) qanday farqi bor?

Answer: abstract classdan inheritance olgan classda abstract classdagi abstract metodlar(propertylar) override qilinib qayta aniqlanishi shart. Abstract metod(yoki property) lar Abstract classda faqatgina e’lon qilinadi uning nima ish bajarishi esa Abstract classdan inheritance olgan classda aniqlanadi.

Masalan:

1)      Methods
public abstract class A
{
public string Name;
public abstract string GetName1();//Bu metodni GetName1(){…} kabi aniqlash mumkin emas
public string GetName2()
{
                return “This is GetName2 method’s result”
}
}
public class B:A
{
//Bu yerda A classdagi GetName1 metodi override qlinib qayta aniqlanishi shart chunki u abstract metod, aks holda  //xatolik yuz beradi.
public override string GetName1()
{
                return “This is GetName1() method’s result”;
}
}
2) abstract properieslarni ishlatish:

abstract class A
{
    protected int myNumber;
    public abstract int numbers
    {
        get;
        set;
    }
}
class B: A
{
    // abstract propertylarni Implement qilamiz 
    public override int numbers
    {
        get
        {
            return myNumber;
        }
        set
        {
            myNumber = value;
        }
    }
}

Question 2: Abstract classning interfacedan  farqi ?

Answer: Abstract sinf abstract memberlardan va abstract bo’lmagan memberlardan iborat bo’lishi mumkin, interfaceda esa barcha memberlar abstract bo’lib, har bir child sinfda override qilinishi shart! Ya’ni interfaceda abstract bo'lmagan member yaratib bo’lmaydi.

interface iSampleInterface
{
  //Betta barcha memberlar avtomatik abstract yaratilvotti
  int AddNumbers(int Num1, int Num2);
  int MultiplyNumbers(int Num1, int Num2);
}

Abstract sinfda abstract memberlarni yaratish interfacedagi kabi bir xil effect beradi
Endi quyidagi CODE yordamida abstract class va interfaceni ishlatamiza:

Task: Ishchi (Worker), Programmist(Programmer), O’qituvchi(Teacher) sinflarini ulardagi logika bo’yicha yaratish

Soluation:
1)      Dastlab IBaseWorker interfaceini yaratamiz:

public interface IBaseWorker : IDisposable
    {
        List<string> GetResume(); //Har bir ishchiga mos RESUME
    }

2)      BaseWorker sinfini abstract ko’rinishda yaratamiz(chunki uning ob’yektini yasash mumkin bo’lmasligi lozim):

public abstract class BaseWorker : IBaseWorker
    {
        public BaseWorker()
        {
            BeforeInit();

            //TODO

            AfterInit();
        }

        public Guid Id { get; set; }

        public string FullName { get; set; }
        public string AddinationalInfo { get; set; }
        public string PhoneNumber { get; set; }

        public int Age { get; set; }
        public string WorkExperience { get; set; }
        public double Salary { get; set; }

        public virtual void AfterInit() { }

        public virtual void BeforeInit()
        {
            Id = Guid.NewGuid();//Initdan oldin har bir workerga ID berish
        }
        public abstract List<string> GetResume();
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
                //Bu yerda DISPOSE class ob’yekti qilinadi
            }
        }
    }

3)      Programmer sinfini yaratamiz, bu BaseWorkerning “bolasi” bo’lishi lozim:

public class Programmer:BaseWorker
    {
        public string ProgrammingLanguages { get; set; }
        public string DataBases { get; set; }
        public string ProjectsInfo { get; set; }
//Quyida GetResume metodi override qilinyapdi chunki u Base classda abstract //qilib e’lon qilingan
        public override List<string> GetResume()
        {
            var resume = new List<string>();
            resume.Add("Full Name:" + FullName);
            resume.Add("Age:" + Age);
            resume.Add("Phone Number:" + PhoneNumber);
            resume.Add("Learning Programming Languages:"+ProgrammingLanguages);
            resume.Add("Using Data Bases:" + DataBases);
            resume.Add("Succesfully projects:" + ProjectsInfo);
            resume.Add("Work Expriense (Ishlagan joylari):" + WorkExperience);
            return resume;
        }
    }

4)      Teacher sinfini yaratamiz(Bu sinf ham BaseWorker sinfinig “bolasi” sifatida yaratiladi):

public class Teacher:BaseWorker
    {
        public string Specialty { get; set; }//Mutaxasisligi
        public int Category { get; set; } //Toifasi
        public string Degree { get; set; }
        public override List<string> GetResume()
        {
            var resume = new List<string>();
            resume.Add("Full Name:" + FullName);
            resume.Add("Age:" + Age);
            resume.Add("Phone Number:" + PhoneNumber);
            resume.Add("Specialty:" + Specialty);
            resume.Add("Category:" + Category);
            resume.Add("Degree:" + Degree);
            resume.Add("Work Expriense (Ishlagan joylari):" + WorkExperience);
            return resume;
        }
    }

5)      Programmers kolleksiya sinfini yaratamiz, bu sinf ob’yektida barcha Programmer sinfi ob’yektlari saqlanadi:

public class Programmers:List<Programmer>
   {
   }

6)      Teachers kolleksiya sinfini yaratamiz:
public class Teachers:List<Teacher>
   {
   }

Yuqorida yaratilgan sinflardan foydalanish:

namespace AbstractClassInterfaceCollectionTestByMansur
{
    class Program
    {
        static void Main(string[] args)
        {
            var teachers=GetTeachers();
            var programmers = GetProgrammers();
            var resumes = new List<string>();
            Console.WriteLine("> Programmers resume:");
            programmers.ForEach(f =>
                {
                    f.GetResume().ForEach(r =>
                        Console.WriteLine(r));
                    Console.WriteLine("_".PadRight(50,'_'));
                });
            Console.WriteLine("> Teachers resume:");
            teachers.ForEach(f =>
            {
                f.GetResume().ForEach(r =>
                    Console.WriteLine(r));
                Console.WriteLine("_".PadRight(50, '_'));
            });
           
            Console.ReadLine();
          }

        private static Teachers GetTeachers()
        {
            var teachers = new Teachers();
            teachers.Add(new Teacher()
            {
                FullName = "Qosimov A.",
                Degree = "dotsent",
                Category = 1,
                AddinationalInfo = "Buxoro city",
                Salary = 2000,
                Specialty = "Mathmatics",
                WorkExperience = "year1 - year2. Work exp.1; year2-year3. Work exp2;"
            });
            teachers.Add(new Teacher()
            {
                FullName = "Axmedov H.",
                Degree = "dotsent",
                Category = 1,
                AddinationalInfo = "Jondor city",
                Salary = 1500,
                Specialty = "Mathmatics",
                WorkExperience = "year1 - year2. Work exp.1; year2-year3. Work exp2;"
            });
            return teachers;
        }
        private static Programmers GetProgrammers()
        {
            var programmers = new Programmers();
            programmers.Add(new Programmer()
            {
                FullName = "Hayotov Hayot Rahmonovich",
                Age = 28,
                DataBases = "MS Sql 2005,2008,2012, Oracle, Postgres",
                ProgrammingLanguages ="C#, Java",
                Salary =1500000,
                WorkExperience = "2013-2014, Tashkent West Minster University; 2014 - ..., Sunet;",
                ProjectsInfo = "Document oborot, Buxgalteriya",
                PhoneNumber = "123-45-67",
                AddinationalInfo = "Lives in Uzb.,Tashkent"
            });
            programmers.Add(new Programmer()
            {
                FullName = "Eshonqulov Hamza",
                Age = 28,
                DataBases = "MS Sql 2005,2008,2012",
                ProgrammingLanguages = "C#, Java, Pascal",
                Salary = 1000000,
                WorkExperience = "2010-..., Bukhara State University;",
                ProjectsInfo = "Avtomatlashtirilgan Ijro intizomi tizimi, Buxgalteriya",
                PhoneNumber = "123-45-67",
                AddinationalInfo = "Lives in Uzb.,Bukhara city"
            });
            return programmers;
        }
    }

}

Tasks and Threads

  Differences Between Task And Thread: 1. The Thread class is used for creating and manipulating a thread in Windows.  2. A Task represents ...