9 Temmuz 2010 Cuma

out ile ref'i farkı

Bu iki komut da value type'ların bir methoda parametre olarak verilip, içerisinde değiştirilmesi halinde, yapılan değişikliklerin metod dışında da geçerli olmasını sağlar.

Bunların tek farkı; "out" anahtar kelimesi, betimlediği parametrenin fonksiyonda kullanılmadan önce initialize edilmesinin zorunlu olmamasıdır.

public void demo1(ref param1)
{
param1 = 5;
}
public void demo2(out param1)
{
param1 = 5;
}

demo2 metodu aşağıdaki şekilde kullanılabilirken,
...
int p2;
demo2(p2);

demo1 metodu şu şekilde kullanılmalıdır:
...
int p1 = 0;
demo1(p1);

19 Mart 2010 Cuma

The maximum nametable character count quota (16384)

Merhaba,

Servislerinizi WCF ile oluşturuyorsanız, method sayınız günden güne artıyorsa karşılaşabileceğiniz olası bir problem ve çözümünden bahsedeceğim.

Visual Studio içerisinden Add Service Reference veya Update Service Reference dediğiniz zaman, svcutil.exe ile istemci sınıfı oluştururken aşağıdaki hatayı alabilirsiniz.

Cannot obtain Metadata from net.tcp://localhost:8090/MyService/Mex If this is a Windows (R) Communication Foundation service to which you have access, please check that you have enabled metadata publishing at the specified address. For help enabling metadata publishing, please refer to the MSDN documentation at http://go.microsoft.com/fwlink/?LinkId=65455.WS-Metadata Exchange Error URI: net.tcp://localhost:8090/MyService/Mex Metadata contains a reference that cannot be resolved: 'net.tcp://localhost:809/MyService/Mex'. There is an error in the XML document. The maximum nametable character count quota (16384) has been exceeded while reading XML data. The nametable is a data structure used to store strings encountered during XML processing - long XML documents with non-repeating element names, attribute names and attribute values may trigger this quota. This quota may be increased by changing the MaxNameTableCharCount property on the XmlDictionaryReaderQuotas object used when creating the XML reader.

Bu hatanın sebebi WCF servisinde çok fazla metot veya operasyon olmasıdır.

Çözüm:
Servisin web.config ve svcutil.exe' nin config dosyalarında aşağıdaki güncellemeleri yapmamız gerekiyor.

Service web.config:

    <bindings>
      <netTcpBinding>
        <binding name="GenericBinding" maxBufferPoolSize="2147483647"
             maxReceivedMessageSize="2147483647" >
          <readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647"
             maxArrayLength="2147483647" maxBytesPerRead="2147483647"
             maxNameTableCharCount="2147483647" />
          <security mode="None"/>
        </binding>
      </netTcpBinding>
      <wsHttpBinding>
        <binding name="SecureBinding" maxBufferPoolSize="2147483647"
             maxReceivedMessageSize="2147483647" >
          <readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647"
             maxArrayLength="2147483647" maxBytesPerRead="2147483647"
             maxNameTableCharCount="2147483647" />
          <security mode="Message">
            <transport clientCredentialType="Windows" />
          </security>
        </binding>
      </wsHttpBinding>
    </bindings>


    <services>
      <service behaviorConfiguration="MyService.NetTcpService" name="MyService.NetTcpService">
        <endpoint address="mex" name="net.tcp" binding="netTcpBinding" bindingConfiguration=""
        contract="IMetadataExchange" />
        <endpoint address="NetTcpService" binding="netTcpBinding" bindingConfiguration="GenericBinding" name="TCPEndpoint"
          contract="MyService.INetTcpService" />
        <host>
          <baseAddresses>
               <add baseAddress="net.tcp://localhost/MyService" />
          </baseAddresses>
        </host>
      </service>
      <service
        behaviorConfiguration="MyService.WsHttpService" name="MyService.WsHttpService">
        <endpoint address="mex" name="http" binding="wsHttpBinding" bindingConfiguration="" contract="IMetadataExchange"/>
        <endpoint address="WsHttpService" binding="wsHttpBinding" bindingConfiguration="SecureBinding" name="httpEndpoint"
          contract="MyService.IWsHttpService" />
        <host>
          <baseAddresses>                         
            <add baseAddress="http://localhost:8095/MyService" />
          </baseAddresses>
        </host>
      </service>
    <services>


Svcutil.exe.config: (C:\Program Files\Microsoft SDKs\Windows\v6.0A\Bin)
Aşağıdaki içeriğin tümü ile varolan dosya güncellenmeli.

   <configuration>
      <system.serviceModel>
       <client>
          <endpoint name="net.tcp" binding="netTcpBinding" bindingConfiguration="GenericBinding"
              contract="IMetadataExchange" />
          <endpoint name="http" binding="wsHttpBinding" bindingConfiguration="SecureBinding" contract="IMetadataExchange" />
       </client>
       <bindings>
        <netTcpBinding>
          <binding name="GenericBinding" maxBufferPoolSize="2147483647"
             maxReceivedMessageSize="2147483647" >
            <readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647"
             maxArrayLength="2147483647" maxBytesPerRead="2147483647"
             maxNameTableCharCount="2147483647" />
            <security mode="None"/>
          </binding>
        </netTcpBinding>
        <wsHttpBinding>
          <binding name="SecureBinding" maxBufferPoolSize="2147483647"
             maxReceivedMessageSize="2147483647" >
            <readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647"
             maxArrayLength="2147483647" maxBytesPerRead="2147483647"
             maxNameTableCharCount="2147483647" />
            <security mode="Message">
              <transport clientCredentialType="Windows" />
            </security>
          </binding>
        </wsHttpBinding>
      </bindings>
     </system.serviceModel>
   </configuration>



Servis config ve svcutil configteki binding isimlerinin aynı olması önemlidir.
Bu değişikliklerin ardından svcutil.exe kullanılarak istemci proxy sınıfları üretebiliriz.

Ancak halen bir sorunumuz var; Visual Studio içerisinden Add Service Reference dediğimiz zaman aynı hatayı alıyoruz. Bunun çözümü de oldukça basit. svcutil.exe.config dosyasında yaptığımız değişikliği, devenv.exe.config (C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE) dosyasında da yapmamız sorunumuzu çözecektir.

11 Mart 2010 Perşembe

Hayatı kolaylaştıran bazı C# kısayolları

1. ? Operatörü
Bu operatör if-then-else koşullarını, "soru ? positif cevap : negatif cevap" pattern' ı sayesinde tek satırda yazmamızı sağlıyor.
Örnek:
if (x > y)
   max = x;
else
   max = y;

Yukarıdaki kodun yerine aşağıdaki kod yazılabilir.
int max = (x > y) ? x : y;

2. ?? Operatörü
Hepimiz sıklıkla bir nesnenin null olup olmadığını kontrol eden kodlar yazıyoruz. ?? operatörü ile bu tip kontrollerimizi tek satırda yapabiliyoruz.
Örnek:
object cache = null;
object d = new object();
object e;
if (c != null)
   e = c;
else
   e = d;

Yukarıdaki kodu yerine ? operatörü ile yazarsak.
object cache = null;
object d = new object();
object e = (c != null) ? c : d;

?? ile biraz daha kısaltalım,
object cache = null;
object d = new object();
object e = c ?? d;

3. Nesne Oluşturma
Yeni bir nesne yarattıktan sonra bir çok özelliğine değer atamamız gerekir. Bunu nesneyi yaratırken de yapabiliriz.
Örnek:
Customer c = new Customer();
c.Name = "James";
c.Address = "204 Lime Street";

Yukarıdaki kodu şöyle de yazabilirdik.
Customer c = new Customer { Name="James", Address = "204 Lime Street" };

4. Using Statement
Nesne yarattık, kullandık ancak dispose komutunu çalıştırmayı unuttuk ve bellek/kaynak sorunlarına yol açtık. IDisposable interface' inden üretilen nesneleri using statement ile kullanırsak dispose işlemini .Net Framework bizim için yönetir.
Örnek:
// 1. Allocation of the object
Font font1 = new Font("Arial", 10.0f);
try
{
// 2. The bit where we use the resource
}
finally
{
// 3. Disposal of the object
   if (font1 != null)
      ((IDisposable)font1).Dispose();
}

Yukarıdaki kod yerine,
// Allocate the resource
using (Font font1 = new Font("Arial", 10.0f))
{
// The bit where we use the resource
}
// Disposal is automatic

5. Uzun Namespace veya Tip isimleri için Alias
Uzun namespace veya tip bilgileri için alias tanımlayıp sınıfları bu alias ile çağırabiliriz. Alias tanımlamak için using anahtar kelimesi kullanılır.
Örnek:
using Word = Microsoft.Office.Interop.Word;
...
Word.Application = new Word.Application() { Visible = True; }

6. Nullable Nesneler
.Net 2.0 ile null değeri alamayan değişkenler nullable olarak tanımlanabilmekte ve null değeri alabilmektedir. Bunu aşağıdaki syntax ile sağlayabiliriz.
Örnek:
Nullable x = null;
int? x = null;

7. Otomatik Özellikler (Properties)
En sevdiğim özelliklerden birisi. .Net 3.0 ile birlikte gelmiştir. Private değişken tanımlayıp get/set property'sini uzun uzun oluşturmak yerine tek satırda yazmamıza olanak veriyor.
Örnek:
public class Person
{
   private string _firstName;
   public string FirstName
   {
      get { return _firstName; }
      set { _firstName = value; }
   }
}

public class Person
{
   public string Firstname { get; set; }
}

4 Mart 2010 Perşembe

LinqToSql vs Entity Framework

Hangisini neden seçmeliyim?



Linq To Sql
Linq To Entity (ADO.Net Entity Framework)

DB
SQL Server
Her türlü ADO.Net data provider
Aynı anda desteklenen şema, protocol sayisi
1
N
Many To Many Relation desteği
M-M tablolar birer entitiy olarak
tanımlanmalı
Var
Relation Multiplicity Ayarı
-
Var
Map etme şekli
1 table - 1 classN table - 1 class
Hedef Projeler
Çabuk, hızlı projeler
Kurumsal yazılımlar
Kompleks tiplerin yaratılması (örneğin
adres diye bir tip oluşturulabilmesi)
-
Var
Data Source
Veritabanı tabloları
Veritabanı tabloları, replication,
Reporting Services, BI, vbl.
Sorgulama
1. Linq to Sql
1. Linq to sql



2. Data Context
2. Entity Sql (inheritance destekliyor)


3. Entity Client
Veritabanı değişince senkronize
edebilme desteği
-
Var
Performans
çok yavaş
linq to sql'den daha iyi
Geliştirilme Durumu
Durduruldu
Devam Ediyor
Data Model'den veritabanı üretilmesi
-
VS2010'da mümkün olacak

Entity Framework'ün VS2008SP1 üzerinde Kısıtları (Osellus Blogs'dan alıntıdır)

1.) Contains metodu runtime'da hata verecektir. Örnek:
         from p in context.Yard_Projects
         where p_projectIDs.Contains(p.ProjectID)
         select p

2.) Entity Type tipinde dönüş yapmayan procedure'ler için metod generate edilmeyecektir.
(Stored Procedure'leri çalıştırmak için Entity Client'a ihtiyacımız var.)

3.) Tablodaki her kolon map edilmek zorundadır. Aksi takdirde compile error alacağız.

4.) Birçok tablodan veri dönen bir stored procedure'e referans kullanan bir metod yaratmak istiyorsak,
.edmx file'ı içinde yer alan "SSDL" bölümünü elle değiştirmemiz gerekmektedir.