Friday, 25 July 2014

C# da XMLdan foydalanish

Using XML in C#
XML (engliz til. eXtensible Markup Language) – XML tili XML xujat yaratishda xujjatdagi aniq struktura va strukturadagi elementlarning o’zaro aloqasini ko’rsatish uchun ishlatiladi. XML tili  1998 yil 10 fevralda W3C (World Wide Web Consortium) tashkiloti taklifi bo’yicha paydo bo’lgan (see also: http://ru.wikipedia.org/wiki/W3C , http://www.w3.org/standards/). Bunday strukturali xujjatlarni yaratish uchun “<” va “>” belgilari ichiga olingan teglardan foydalaniladi. Har bir ochilgan teg o’z o’rnida yopilishi kerak. XML qo’pol qilib aytganda berilganlarni saqlash vazifasini bajaradi(Data Base).

Masalan:
1)Quyidagi XML dokument <emails>,<email>,<to>,<form>,<header>,<content> teglaridan tashkil topgan.

<emails>

<email>
<to> x@y  </to>
<header>Salom!</header>
<content>e-mail mazmuni</content>

</email>

<emails>

2)
<users>
<user name=”User1” age=”25” role=”Admin”/>
<user name=”User2” age=”30” role=”Simple User”></user>
<user name=”User3” age=”40” role=”User”/>
</users>

XML dokumentning birinchi qatorida <?xml version="1.0" encoding="windows-1251" ?> joylashishi lozim, bu xujjatning XML ekanligini va belgilar kodirovkasini ko’rsatishda(encoding="windows-1251" yoki encoding="utf-8" kabi) ishlatiladi.
3)
<?xml version="1.0" encoding="utf-8" ?>
<Book>
    <BookName>C# Professional</BookName>
    <BookName>C# Cookbook</BookName>
    <BookName>SQL Server Book</BookName>
    <BookName>Mastering VB.Net</BookName>
    <BookName>ASP.Net Unleashed</BookName>
    <BookName>.Net Framework Essentials</BookName>
    <ReleaseYear>2001</ReleaseYear>
    <ReleaseYear>2002</ReleaseYear>
    <ReleaseYear>2003</ReleaseYear>
    <ReleaseYear>2004</ReleaseYear>
    <Publication>XYZ</Publication>
    <Publication>Microsoft Press</Publication>
    <Publication>O 'Reilly</Publication>
</Book>

Endi XML faylga yozish, o’qish, o’zgartirishni quyidagi dastur yordamida ko’rib chiqamiz:

Englizcha – Ruscha – O’zbekcha lug’at dasturi

Dasturni yaratish tartibi:
1)      Dastlab C# da Consule Application proyekt yaratamiz va unga “Data” va “Models” nomli papkalarni qo’shamiz. “Data” papkada XML fayli bilan ishlashga mo’ljallangan classlar joylashadi(DAO – Data Access Object).  “Models” papkasida esa xml fayl strukturasiga mos model classlar joylashadi.
2)      “Debug” papkasini hosil qilish uchun proyektni “built” qilamiz.
3)      Proyektdagi “Debug” papkasida Data.xml faylini yaratamiz, xml faylidagi so’zlar <words> tegida joylashadi va har bir so’z <word> tegida aniqlanadi, bunda <en> tegi inglizcha, <ru> ruscha, <key> o’zbekcha so’zlarni bildiradi (ixtiyoriy tilni shunday tartibda qo’shish mumkin):
<?xml version="1.0" encoding="utf-8"?>
<words>
  <word>
    <key>salom</key>
    <en>hello, Hi!</en>
    <ru>privet</ru>
  </word>
  <word>
    <key>kitob</key>
    <en>book</en>
    <ru>kniga</ru>
  </word>
  <word>
    <key>olma</key>
    <en>apple</en>
    <ru>yabloka</ru>
  </word>
<word>
    <key>uy</key>
    <en>house</en>
    <ru>dom</ru>
  </word>
</words>
4)      App.config fayliga yangi “key” qo’shamiz, bu “key”da xml fayli joylashgan papka manzili saqlanadi(Debug\Data.xml),  key nomi - XMLDataBasePath).
App.config.xml:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup>
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
    </startup>
  <appSettings>
    <add key="XMLDataBasePath" value="C:\Users\qmansur\Documents\visual studio 2013\Projects\ConsoleApplicationXML_CRUD\ConsoleApplicationXML_CRUD\bin\Debug\" />
  </appSettings>
</configuration>
5)  “Model” papkasida Word.cs va Words.cs sinflarini yaratamiz.
Word.cs:
namespace ConsoleApplicationXML_CRUD.Models
{
    [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
    public partial class Word
    {

        private string keyField;

        private string enField;

        private string ruField;

        /// <remarks/>
        public string key
        {
            get
            {
                return this.keyField;
            }
            set
            {
                this.keyField = value;
            }
        }

        /// <remarks/>
        public string en
        {
            get
            {
                return this.enField;
            }
            set
            {
                this.enField = value;
            }
        }

        /// <remarks/>
        public string ru
        {
            get
            {
                return this.ruField;
            }
            set
            {
                this.ruField = value;
            }
        }
    }
}
Words.cs:
namespace ConsoleApplicationXML_CRUD.Models
{
    [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
    [System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)]
    public partial class Words
    {

        private Word[] wordField;

        /// <remarks/>
        [System.Xml.Serialization.XmlElementAttribute("word")]
        public Word[] word
        {
            get
            {
                return this.wordField;
            }
            set
            {
                this.wordField = value;
            }
        }
    }
}


6)      Data papkasida DataAcsessLayer.cs va unga yordamchi Helper.cs  classlarini yaratamiz.
Helper.cs:
using System.Xml;

namespace ConsoleApplicationXML_CRUD.Data
{
    public class Helper
    {
        public static XmlElement CreateXMLElement(XmlDocument xmlDoc, string name, string value)
        {
            XmlElement xmlElement = xmlDoc.CreateElement(name);
            XmlText xmlText = xmlDoc.CreateTextNode(value);
            xmlElement.AppendChild(xmlText);
            return xmlElement;
        }
    }
}

DataAcsessLayer.cs:
using System;
using System.Collections.Generic;
using System.IO;
using System.Configuration;
using System.Xml;
using System.Xml.XPath;

namespace ConsoleApplicationXML_CRUD.Data
{
    public class DataAcsessLayer
    {
        private string strFileName = string.Empty;

        public DataAcsessLayer()
        {
            // App.confg faylidan data.xml fayli yo'lini aniqlash
            strFileName = ConfigurationManager.AppSettings["XMLDataBasePath"] + "data.xml";
        }

       
        public bool Create(Models.Word word)
        {
            try
            {
                // Fayl mavjudligini tekshirish
                if (!File.Exists(strFileName))
                {
                    XmlTextWriter textWritter = new XmlTextWriter(strFileName, null);
                    textWritter.WriteStartDocument();
                    textWritter.WriteStartElement("words");
                    textWritter.WriteEndElement();
                    textWritter.Close();
                }

                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.Load(strFileName);

                XmlElement subNode = xmlDoc.CreateElement("word");

                string strKey = word.key;
                subNode.AppendChild(Helper.CreateXMLElement(xmlDoc, "key", strKey));
                xmlDoc.DocumentElement.AppendChild(subNode);


                subNode.AppendChild(Helper.CreateXMLElement(xmlDoc, "en", word.en));
                xmlDoc.DocumentElement.AppendChild(subNode);

                subNode.AppendChild(Helper.CreateXMLElement(xmlDoc, "ru", word.ru));
                xmlDoc.DocumentElement.AppendChild(subNode);
                xmlDoc.Save(strFileName);
                return true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public bool Update(Models.Word word)
        {

            try
            {
                if (File.Exists(strFileName))
                {
                    XmlDocument objXmlDocument = new XmlDocument();
                    objXmlDocument.Load(strFileName);

                    // Xpath query dan foydalanim word.key ga mos wordni olamiz:
                    XmlNode node = objXmlDocument.SelectSingleNode("//word[key='" + word.key + "']");

                    if (node != null) //agar mavjud bo'lsa:
                    {
                        node.SelectNodes("key").Item(0).FirstChild.Value = word.key;
                        node.SelectNodes("en").Item(0).FirstChild.Value = word.en;
                        node.SelectNodes("ru").Item(0).FirstChild.Value = word.ru;
                    }
                    // Faylga yozish:
                    objXmlDocument.Save(strFileName);

                    return true;
                }
                else
                {
                    Exception ex = new Exception("App.configda aniqlangan manzil bo'yicha fayl topilmadi");
                    throw ex;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public bool Delete(string key)
        {

            try
            {
                if (File.Exists(strFileName))
                {
                    XmlDocument objXmlDocument = new XmlDocument();
                    objXmlDocument.Load(strFileName);

                    XmlNode node = objXmlDocument.SelectSingleNode("//word[key='" + key + "']");

                    if (node != null)
                    {
                        objXmlDocument.ChildNodes[1].RemoveChild(node);
                    }
                    objXmlDocument.Save(strFileName);

                    return true;
                }
                else
                {
                    Exception ex = new Exception("App.configda aniqlangan manzil bo'yicha fayl topilmadi");
                    throw ex;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public IList<Models.Word> GetAll()
        {
            try
            {
                if (File.Exists(strFileName))
                {
                    XPathDocument doc = new XPathDocument(strFileName);
                    XPathNavigator myQuery = doc.CreateNavigator();
                    // Barcha so'zlarni olish:
                    XPathExpression exp = myQuery.Compile("/words/word");

                    // key bo'yicha tartiblash
                    exp.AddSort("key", System.Xml.XPath.XmlSortOrder.Ascending, System.Xml.XPath.XmlCaseOrder.None, "",
                        System.Xml.XPath.XmlDataType.Text);

                    XPathNodeIterator iterator = myQuery.Select(exp);
                    IList<Models.Word> objWords = new List<Models.Word>();

                    while (iterator.MoveNext())
                    {
                        XPathNavigator myQuery2 = iterator.Current.Clone();

                        Models.Word objWord = new Models.Word();
                        objWord.key = myQuery2.Select("//word").Current.SelectSingleNode("key").InnerXml;
                        objWord.en = myQuery2.Select("//word").Current.SelectSingleNode("en").InnerXml;
                        objWord.ru = myQuery2.Select("//word").Current.SelectSingleNode("ru").InnerXml;

                        objWords.Add(objWord);
                    }
                    return objWords;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return null;
        }

       
        public Models.Word Get(string key)
        {
            try
            {
                if (File.Exists(strFileName))
                {
                    Models.Word objWord = new Models.Word();

                    XPathDocument doc = new XPathDocument(strFileName);
                    XPathNavigator myQuery = doc.CreateNavigator();
                    XPathNodeIterator iterator;

                    iterator = myQuery.Select("//word[key='" + key + "']");

                    while (iterator.MoveNext())
                    {
                        XPathNavigator myQuery2 = iterator.Current.Clone();

                        objWord.key = myQuery2.Select("//word").Current.SelectSingleNode("key").InnerXml;
                        objWord.en = myQuery2.Select("//word").Current.SelectSingleNode("en").InnerXml;
                        objWord.ru = myQuery2.Select("//word").Current.SelectSingleNode("ru").InnerXml;
                    }
                    return objWord;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return null;
        }
    }
}




7)      Program.cs faylida Data.xml fayliga yozish(Create),o’zgartirish(Update),o’qish(Get, GetALL) va o’chirish(Delete) amallarini Data. DataAcsessLayer classi orqali bajarishimiz mumkin:
Program.cs:
using System;
using System.Linq;
using ConsoleApplicationXML_CRUD.Data;

namespace ConsoleApplicationXML_CRUD
{
    class Program
    {
        static void Main(string[] args)
        {
            Data.DataAcsessLayer words=new DataAcsessLayer();
            //words.Create(new Word(){key = "olma", en = "apple", ru = "яблоко"});
            var x = words.GetAll().ToList();
            x.ForEach(y =>
            {
                Console.WriteLine("{0}, {1}, {2}",y.key,y.en,y.ru);
            });
            Console.ReadLine();
        }
    }
}



Dasturning Visual Studio IDEdagi ko’rinishi:



Dastur natijasi:



Shunday tartibda dasturni to’laligicha ‘Windows Forms App’ , Wpf, yoki web da yaratish mumkin

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 ...