Aklımda Kalası Kelimeler

* давайте работать вместе
* Zarf ve Mazruf, Zerafet(xHoyratlık) ile aynı kökten(za-ra-fe) gelir
* Bedesten
* Suç subuta ermiştir - Suç sabit olmuştur
Serialization etiketine sahip kayıtlar gösteriliyor. Tüm kayıtları göster
Serialization etiketine sahip kayıtlar gösteriliyor. Tüm kayıtları göster

28 Nisan 2017 Cuma

Form serileştirme

Form içerisinde n tane element olan bir yapı. Form içinde topladığınız bilgileri sunucuya taşıyabilmek için HTTP paketleri kullanıyoruz. Buraya kadar hepimiz biliyoruz ;)
Bu paket başlık ve gövdeden oluşuyor ve aralarında sadece boş bir satır var. Genelde verileri gövde kısmına yükleriz. Sunucunun bu verileri parçalara ayırabilmesi(parse edebilmesi) gerekiyor. Bunu yapsın diye gövdeye yazacağımız bilgiyi iki tarafında (istemci ve sunucu) anlayabileceği şekilde oluşturmamız gerekiyor ki buna mesajın biçimi(formatı) diyoruz.
Mesaj formatlarımız neler:
  • XML
  • JSON
  • x-www-form-urlencoded
  • SOAP
  • multipart/form-data


application/x-www-form-urlencoded yapılan talebe text/html tipinde aldığımız cevap:

Encode ve Decode terimleri hep oldu hep olacak çünkü biz harf yazıyoruz ve bunu bilgisayara manyetik değer olarak kaydediyoruz. Ben bilgiyi dairesel ve çizgisel karakterler olarak ekranda görünecek şekilde kaydediyorum bir başkası video da havanın bükülerek ses dalgaları haline getirerek aktarıyor. Demek ki biz mesajları sürekli encode ediyoruz ve o mesajları okurken, dinlerken decode ediyoruz.

isim="Cem Topkaya" verisini internet ortamında transfer etmek için url'nin sonuna eklediğimizi düşünelim http://cemtopkaya.com/kullanici.php?isim=Cem Topkaya siz de farkettinizki soyisim bir boşlukla ayrıldığı için url'nin parçası olamıyor.

20 Kasım 2013 Çarşamba

Xml Serileştirmede XmlArray, XmlArrayItem, XmlAttribute, XmlSerializer, XmlType, XmlEnum, XmlIgnore, XmlInclude, IsNullable vd. incelemesi

Kodun içinde notlarım var. Örnek msdn den.

using System.IO;
using System.Xml.Serialization;

public class Run
{
    public static void Main()
    {
        Run test = new Run();
        test.SerializeDocument("books.xml");
    }

    public void SerializeDocument(string filename)
    {
        // Creates a new XmlSerializer.
        XmlSerializer s =
        new XmlSerializer(typeof(MyRootClass));

        // Writing the file requires a StreamWriter.
        TextWriter myWriter = new StreamWriter(filename);

        // Creates an instance of the class to serialize. 
        MyRootClass myRootClass = new MyRootClass();

        /* Uses a basic method of creating an XML array: Create and 
        populate a string array, and assign it to the 
        MyStringArray property. */

        string[] myString = { "Hello", "world", "!" };
        myRootClass.MyStringArray = myString;

        /* Uses a more advanced method of creating an array:
           create instances of the Item and BookItem, where BookItem 
           is derived from Item. */
        Item item1 = new Item();
        BookItem item2 = new BookItem();

        // Sets the objects' properties.
        item1.ItemName = "Widget1";
        item1.ItemCode = "w1";
        item1.ItemPrice = 231;
        item1.ItemQuantity = 3;

        item2.ItemCode = "w2";
        item2.ItemPrice = 123;
        item2.ItemQuantity = 7;
        item2.ISBN = "34982333";
        item2.Title = "Book of Widgets";
        item2.Author = "John Smith";

        // Fills the array with the items.
        Item[] myItems = { item1, item2 };

        // Sets the class's Items property to the array.
        myRootClass.Items = myItems;

        /* Serializes the class, writes it to disk, and closes 
           the TextWriter. */
        s.Serialize(myWriter, myRootClass);
        myWriter.Close();
    }
}

// This is the class that will be serialized. 
public class MyRootClass
{
    private Item[] items;

    /* Here is a simple way to serialize the array as XML. Using the
       XmlArrayAttribute, assign an element name and namespace. The
       IsNullable property determines whether the element will be 
       generated if the field is set to a null value. If set to true,
       the default, setting it to a null value will cause the XML
       xsi:null attribute to be generated. */

    /* IsNullable = true 
            <NULLveOLUSTURULacak xsi:nil="true" xmlns="http://www.IsNullable.com" /> */
    [XmlElement(ElementName = "NULLveOLUSTURULacak", IsNullable = true, Namespace = "http://www.IsNullable.com")]
    public string IsNullable_true_ornegi;

    /* IsNullable = false (değer atanmazsa da false gibi çalışır) 
            'null değeri olduğu için xml elemanı oluşturulmadı' */
    [XmlElement(ElementName = "NULLveOLUSTURULMAYAcak", IsNullable = false, Namespace = "http://www.IsNullable.com")]
    public string IsNullable_false_ornegi;
    
    
    
    [XmlArray(ElementName = "bomBosDizi", Namespace = "http://www.nullDegerliDizi.com", IsNullable = true)]
    public string[] bosDizi;
    /* IsNullable = true olan XmlArray özellikli field sonucu:
            <bomBosDizi xsi:nil="true" xmlns="http://www.nullDegerliDizi.com" />
     */

    /// <summary>
    /// 
    /// XmlArray Özelliğinin BASİT şekli
    /// 
    /// </summary>
    [XmlArray(ElementName = "MyStrings", Namespace = "http://www.cpandl.com", IsNullable = true)]
    public string[] MyStringArray;
    /* En temel haliyle XmlArray aynı tip dizi elemanları için bir xml elemanı altında toplayacaktır.
       Sonuç:
        <MyStrings xmlns="http://www.cpandl.com">
          <string>Hello</string>
          <string>world</string>
          <string>!</string>
        </MyStrings>
     */


    [XmlArray(ElementName = "Dizi_Kok_Elemani")]
    [XmlArrayItem("Eleman_Etiketi")]
    public string[] stringDizi =  { "Hello", "world", "!" };
    /*
        <Dizi_Kok_Elemani>
          <Eleman_Etiketi>Hello</Eleman_Etiketi>
          <Eleman_Etiketi>world</Eleman_Etiketi>
          <Eleman_Etiketi>!</Eleman_Etiketi>
        </Dizi_Kok_Elemani>
     */


    /// <summary>
    /// 
    /// XmlArray Özelliğinin KARMAŞIK şekli
    /// 
    /// </summary>
    [XmlArrayItem(ElementName = "Item",     IsNullable = true, Type = typeof(Item),     Namespace = "http://www.cpandl.com"),
     XmlArrayItem(ElementName = "BookItem", IsNullable = true, Type = typeof(BookItem), Namespace = "http://www.cohowinery.com")]
    [XmlArray]
    public Item[] Items
    {
        get { return items; }
        set { items = value; }
    }
    /*
     Items propertysi Item cinsinden bir dizi alır.
     Yani hem Item, hem BookItem türü verileri alabilir.
     Serileştirilecek nesnenin Items elemanı hem Item hem de BookItem 
     türünde iki nesne alacağı için dizi içindeki eleman türüne göre serileştirme çalışacak
     Sonuç:
      <Items>
        <Item xmlns="http://www.cpandl.com">
          <OrderItem>Widget1</OrderItem>
          <ItemCode>w1</ItemCode>
          <ItemPrice>231</ItemPrice>
          <ItemQuantity>3</ItemQuantity>
        </Item>
        <BookItem xmlns="http://www.cohowinery.com">
          <ItemCode>w2</ItemCode>
          <ItemPrice>123</ItemPrice>
          <ItemQuantity>7</ItemQuantity>
          <Title>Book of Widgets</Title>
          <Author>John Smith</Author>
          <ISBN>34982333</ISBN>
        </BookItem>
      </Items> 
     */


    [
        XmlArrayItem(Type = typeof (BookItem)),
        XmlArrayItem(Type = typeof (string)),
        XmlArrayItem(Type = typeof (int))
    ] 
    public object[] KarisikTipler =
    {
        "Bu", 1, new BookItem()
                 {
                     Author = "Cem",
                     ISBN = "93845934",
                     ItemCode = "item kod 10",
                     ItemName = "item adı",
                     ItemPrice = 1.2m,
                     ItemQuantity = 10,
                     Title = "Başlık şu, bu, o"
                 }
    };
    /* Her dizi elemanı string, int ve BookItem tipindeyse serileştirilecek değilse istisna fırlatacak.
        <KarisikTipler>
          <string>Bu</string>
          <int>1</int>
          <BookItem>
            <OrderItem>item adı</OrderItem>
            <ItemCode>item kod 10</ItemCode>
            <ItemPrice>1.2</ItemPrice>
            <ItemQuantity>10</ItemQuantity>
            <Title>Başlık şu, bu, o</Title>
            <Author>Cem</Author>
            <ISBN>93845934</ISBN>
          </BookItem>
        </KarisikTipler>
     */

    /// 
    /// xml çıktısı:
    ///     <EmpStatus>Triple</EmpStatus>
    /// 
    public EmployeeStatus EmpStatus=EmployeeStatus.Three;
}

public enum EmployeeStatus
{
    [XmlEnum(Name = "Single")]
    One,
    [XmlEnum(Name = "Double")]
    Two,
    [XmlEnum(Name = "Triple")]
    Three
}


public class Item
{
    [XmlElement(ElementName = "OrderItem")]
    public string ItemName;
    public string ItemCode;
    public decimal ItemPrice;
    public int ItemQuantity;
}

public class BookItem : Item
{
    public string Title;
    public string Author;
    public string ISBN;
}


/// <summary>
/// Şu nesne için:
/// 
///    public KitapItem kit = new KitapItem()
///                           {
///                               Author = "Kitapçı Cem",
///                               ISBN = "---1---",
///                               ItemCode = "item kodum oldu",
///                               ItemName = "item adım yok oldu",
///                               ItemPrice = 10.2m,
///                               ItemQuantity = 23,
///                               Title = "illa başlık, hep başlık"
///                           };
/// 
/// 
/// xml sonucu:
/// 
///  <kit d2p1:baslik="illa başlık, hep başlık" xmlns:d2p1="attribute_nameSpeysi">
///    <OrderItem xmlns="kitapNameSpace">item adım yok oldu</OrderItem>
///    <ItemCode xmlns="kitapNameSpace">item kodum oldu</ItemCode>
///    <ItemPrice xmlns="kitapNameSpace">10.2</ItemPrice>
///    <ItemQuantity xmlns="kitapNameSpace">23</ItemQuantity>
///    <Author xmlns="kitapNameSpace">Kitapçı Cem</Author>
///    <ISBN xmlns="kitapNameSpace">---1---</ISBN>
///  </kit>
/// 
/// </summary>
[XmlType(TypeName = "KitapEleman", Namespace = "kitapNameSpace")]
public class KitapItem : Item
{
    [XmlAttribute(Namespace = "attribute_nameSpeysi", AttributeName = "baslik", DataType = "normalizedString")]
    public string Title;
    public string Author;
    public string ISBN;
}

<?xml version="1.0" encoding="utf-8"?>
<MyRootClass xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <NULLveOLUSTURULacak xsi:nil="true" xmlns="http://www.IsNullable.com" />
  <bomBosDizi xsi:nil="true" xmlns="http://www.nullDegerliDizi.com" />
  <MyStrings xmlns="http://www.cpandl.com">
    <string>Hello</string>
    <string>world</string>
    <string>!</string>
  </MyStrings>
  <Items>
    <Item xmlns="http://www.cpandl.com">
      <OrderItem>Widget1</OrderItem>
      <ItemCode>w1</ItemCode>
      <ItemPrice>231</ItemPrice>
      <ItemQuantity>3</ItemQuantity>
    </Item>
    <BookItem xmlns="http://www.cohowinery.com">
      <ItemCode>w2</ItemCode>
      <ItemPrice>123</ItemPrice>
      <ItemQuantity>7</ItemQuantity>
      <Title>Book of Widgets</Title>
      <Author>John Smith</Author>
      <ISBN>34982333</ISBN>
    </BookItem>
  </Items>
</MyRootClass>

XmlAttribute bir yerde tanımlıysa, o field ya da property nin tipindeki(class,struct vs.) [XmlType(......)] bir işe yaramaz.
KitapItem sınıfının Title fieldı için farklı bir namespace tanımladık (attribute_namepseysi) ve bunun için d2p1 oluşturulup özelliğin önüne konulduğuna dikkat edelim emi...

Enum gösterimi için [XmlEnum (Name = "enumGorunecekAdi")] kullanılır


XmlIgnore ile serileştirilmesini istemediğimiz field, prop vs. seçilir


XmlInclude ile hangi tiplerin serileştirilip serileştirilmeyeceği belirlenir

1 Temmuz 2013 Pazartesi

Serileştirme, Serialization, C#

Temel olarak serileştirme aşağıdaki kod ile anlaşılabilir ancak birazcık daha detaylı bilgi için biraz daha aşağıdaki kod yardımcı olacaktır.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
using Newtonsoft.Json;

namespace ConsoleApplication1
{
    [Serializable]
    public class Ornek
    {
        public string Adi { get; set; }

        public void calis()
        {
        }
    }

    class Program
    {
        public static Ornek o = new Ornek() { Adi = "cem" };
        private static void Main(string[] args)
        {
            json();
        }


        public static void json()
        {
            string json = JsonConvert.SerializeObject(o);
            Console.WriteLine(json);
        }

        public static void binary()
        {
            BinaryFormatter formatter = new BinaryFormatter();
            FileStream stream = File.Create("c:\\temp\\test.txt");
            Console.WriteLine("Serializing vector");
            formatter.Serialize(stream, o);
            stream.Close();

        }

        public static void xml(){
            XmlSerializer x = new XmlSerializer(o.GetType());
            x.Serialize(Console.Out, o);
        }
    }
}


/* ÇIKTILARIMIZ:
 * XML
 
 <?xml version="1.0" encoding="ibm857"?>
<Ornek xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://w
ww.w3.org/2001/XMLSchema">
  <Adi>cem</Adi>
</Ornek>
 
 * 
 * BINARY
 
      ÿÿÿÿ             JConsoleApplication1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null      ConsoleApplication1.Ornek     <Adi>k__BackingField           cem 
 * 
 * JSON
 
 {"Adi":"cem"}
 */

Kodumuz şöyle olacak:
using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization.Formatters.Soap;
using System.Xml.Serialization;

namespace ConsoleApplication7
{
    [Serializable]
    public class Basit
    {
        public char c = 'a';
        public byte b = (byte)'a';
        private char privateAmaBinaryFormatterSerilestirir_SoapFormatterSerilestirmez = (char)65;

        [XmlElement(DataType = "string", ElementName="ADI")] // XSD tanımlamaları
        public string Adi = "isimsiz";

        [NonSerialized] // BinaryFormatter private'a bakmaksızın serileştirdiği için [NonSerialized] ile işaretliyoruzki, serileştirmesin
        private byte NonSerialized_isaretli_BinaryFormatter_Serilestirmez = 1;
    }

    public class Example
    {
        public static void Main()
        {
            var b = BinaryFormatla_seri_deseri_lestir();
            var s = SoapFormatla_seri_deseri_lestir();
            var x = XML_seri_deseri_lestir();
            /*
             * Binary Serialization
             * Serialization can be defined as the process of storing the state of an object to a storage medium. 
             * During this process, 
             *   the public and private fields of the object 
             *   and the name of the class, 
             *   including the assembly containing the class, 
             * are converted to a stream of bytes, which is then written to a data stream. 
             * When the object is subsequently deserialized, an exact clone of the original object is created.
             * When implementing a serialization mechanism in an object-oriented environment, you have to make a number of tradeoffs between ease of use and flexibility. 
             * The process can be automated to a large extent, provided you are given sufficient control over the process. 
             */

            /*
             * XML and SOAP Serialization
             * XML serialization converts (serializes) the public fields and properties of an object, 
             * or the parameters and return values of methods, 
             * into an XML stream that conforms to a specific XML Schema definition language (XSD) document. 
             * XML serialization results in strongly typed classes with public properties and fields that are converted to a serial format (in this case, XML) for storage or transport.
             */
        }

        private static Basit XML_seri_deseri_lestir()
        {
            Type t = Type.GetType("ConsoleApplication7.Basit");
            XmlSerializer ser = new XmlSerializer(t);
            FileStream fs = new FileStream("XmlSer.xml",FileMode.OpenOrCreate);
            ser.Serialize(fs,new Basit());
            fs.Close();

            Basit x = (Basit) ser.Deserialize(new FileStream("XmlSer.xml", FileMode.Open));
            return x;
        }

        private static Basit SoapFormatla_seri_deseri_lestir()
        {
            SoapFormatter soapFmt = new SoapFormatter();
            FileStream fs = new FileStream("basit.xml", FileMode.OpenOrCreate);
            soapFmt.Serialize(fs, new Basit());
            fs.Close();

            FileStream fs1 = new FileStream("basit.xml", FileMode.Open);
            Basit s = (Basit)soapFmt.Deserialize(fs1);
            return s;
        }

        private static Basit BinaryFormatla_seri_deseri_lestir()
        {
            BinaryFormatter binaryFmt = new BinaryFormatter();
            FileStream fs = new FileStream("basit.bin", FileMode.OpenOrCreate);
            binaryFmt.Serialize(fs, new Basit());
            fs.Close();

            FileStream fs1 = new FileStream("basit.bin", FileMode.Open);
            Basit b = (Basit)binaryFmt.Deserialize(fs1);
            return b;
        }
    }
}
ve çıktılardan önce dönen değişkenler şöyle:
Dosyalardaki çıktılar ise: BINARY Formatlı Çıktının HEX Görünümü:
SOAP XML Çıktısı:
<SOAP-ENV:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:clr="http://schemas.microsoft.com/soap/encoding/clr/1.0" SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
<SOAP-ENV:Body>
<a1:Basit id="ref-1" xmlns:a1="http://schemas.microsoft.com/clr/nsassem/ConsoleApplication7/ConsoleApplication7%2C%20Version%3D1.0.0.0%2C%20Culture%3Dneutral%2C%20PublicKeyToken%3Dnull">
<c>a</c>
<b>97</b>
<privateAmaBinaryFormatterSerilestirir_SoapFormatterSerilestirmez>A</privateAmaBinaryFormatterSerilestirir_SoapFormatterSerilestirmez>
<Adi id="ref-3">isimsiz</Adi>
</a1:Basit>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
XML Çıktısı:
<?xml version="1.0"?>
<Basit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <c>97</c>
  <b>97</b>
  <ADI>isimsiz</ADI>
</Basit>

18 Aralık 2011 Pazar

XML Serileştirmede NonSerialized ve XmlIgnore farkı

Ref: How to ignore a field/property during serialization

The first attribute, [NonSerialized], should be applied to field members and informs the standard serialization methods to ignore the field. The second attribute, [System.Xml.Serialization.XmlIgnore], should be applied to public properties and informs the Xml Serializer to ignore the property. The combination of the two should be enough to stop the field from being serialized regardless of the serializer the client chooses to use.
Quick pseudo example:

[NonSerialized],
private SomeUnFriendlyType myType:

[System.Xml.Serialization.XmlIgnore]
public SomeUnFriendlyType MyType()


Benim takıldığım durumda:
[Serializable]
    public class KurumBilgileri:MedulaServisleri
    {
        public string SaglikTesisKodu;
        public string SaglikTesisSifresi;
        public string BransKodu;
        public string TedaviTuru;
        public string TedaviTipi;
        /// 
        /// 
        /// 
        public string ProvizyonTipi;

        private string m_XmlFileName = "SaglikTesisBilgileri.xml";

        public KurumBilgileri()
        {
        }

Tabi MedulaServislerinide görmek gerek:
[Serializable]
    public class MedulaServisleri
    {

        //[NonSerialized]
        [XmlIgnore]
        public HastaKabulIslemleriService hki;

        public MedulaServisleri()
        {
            hki = new HastaKabulIslemleriService();
        }
    }

Eğer ata sınıftaki(MedulaServisleri) hki değişkenini protected yaparsam hata fırlatılmıyordu. Çünkü [NonSerialized] özelliğini kullanıyordum. Ama public yaptığımda gümlüyordu. Bu kezde [XmlIgnore] özelliği imdada yetişiyor. Tamda yukarıda makalesini verdiğim elemanın dediği gibi.

12 Ekim 2009 Pazartesi

IFormatter ve Serialization

Referans: MSDN
Örnek: chsarpnedir.com
The SoapFormatter and BinaryFormatter classes implement the IRemotingFormatter interface to support remote procedure calls (RPCs), and the IFormatter interface (inherited by the IRemotingFormatter) to support serialization of a graph of objects. The SoapFormatter class also supports RPCs with ISoapMessage objects, without using the IRemotingFormatter functionality.

During RPCs, the IRemotingFormatter interface allows the specification of two separate object graphs: the graph of objects to serialize, and an additional graph containing an array of header objects that convey information about the remote function call (for example, transaction ID or a method signature).

RPCs that use the BinaryFormatter separate into two distinct parts: method calls, which are sent to the server with the remote object containing the method called, and method responses, which are sent from the server to the client with the status and response information from the called method.

During serialization of a method call the first object of the object graph must support the IMethodCallMessage interface. To deserialize a method call, use the Deserialize method with the HeaderHandler parameter. The remoting infrastructure uses the HeaderHandler delegate to produce an object that supports the ISerializable interface. When the BinaryFormatter invokes the HeaderHandler delegate, it returns the URI of the remote object with the method that is being called. The first object in the graph returned supports the IMethodCallMessage interface.

The serialization procedure for a method response is identical to that of a method call, except the first object of the object graph must support the IMethodReturnMessage interface. To deserialize a method response, use the DeserializeMethodResponse method. To save time, details about the caller object are not sent to the remote object during the method call. These details are instead obtained from the original method call, which is passed to the DeserializeMethodResponse method in the IMethodCallMessage parameter. The first object in the graph returned by the DeserializeMethodResponse method supports the IMethodReturnMessage interface.