Forum

Uzakdaki Database i...
 
Bildirimler
Hepsini Temizle

Uzakdaki Database ile WCF aracılıgıyla iletişim kurmak

6 Yazılar
4 Üyeler
0 Likes
640 Görüntüleme
(@sinemerkan)
Gönderiler: 234
Reputable Member
Konu başlatıcı
 

arkadaşlar merhaba ;

IIS de host edilen bir web uygulamamın içinde WCF servisimiz var ve aynı lokasyonda DATABASE mevcut ,ben uzakdan bir winform uygulaması üzerinden WCF aracılıgı ile databasi nasıl sorgularım.

Not : SQL server dışarıdan erişime açık değil.

WCF metodum

public void ExcMethodWcf(string query)
    {    
        var con =new SqlConnection(RemoteConnection());
        con.Open();
        var cmd = new SqlCommand(query, con);
        cmd.ExecuteReader(CommandBehavior.CloseConnection); 
    }

public string RemoteConnection()

{

var con = new SqlConnection("Data Source=.;Initial Catalog=DBNAME;User ID=sa;Password=abc123;");

return con.ConnectionString;

}

WCF 'i windormuma referans olarak ekledim .

değerli yorumlarınızı bekliyorum .

 

 
Gönderildi : 18/04/2017 02:37

(@ErkanKilmen)
Gönderiler: 4
New Member
 

Merhaba

1- Appconfig dosyandaki aşağıdaki ayarları kontrol edebilirmisin?

2- servise ulaşmak istediğin 8000 & 80 vs.. portuna ait firewall izinleri (GET - POST) kontrol edebilirmisin?

 

<system.serviceModel>
  <behaviors>
    <serviceBehaviors>
      <behavior>
        <useRequestHeadersForMetadataAddress>
      </behavior>
    </serviceBehaviors>
  </behaviors>
</system.serviceModel>

Kolay Gelsin.

 

 
Gönderildi : 18/04/2017 23:16

(@enisciftci)
Gönderiler: 22
Eminent Member
 

Merhaba,

ilk olarak umarım yanlış anlamamışımdır. Aşağıdaki kodlarda istediğinizi bulabileceğiniz mantık var. Ben dosya taşıma ve ürün listeleme yazdım (basit haliyle). Ayrıca ACL'ye (Windows sistemlerde) eklemen gereken bir adres URL'sini unutmayalım. İlaveten binding tipini siz istediğiniz gibi düzenleyip dosyalarınızı revize edebilirsiniz.

Edit : Database tarafının dışarıya açık olmadığını yazmışsınız. Buna ilaveten bir SQL mi yoksa Windows kimliği ile mi giriş ayarlarınız var ? Domain yapısı ve diğer unsurlar, projenizde kimlik doğrulama veya yetkilendirme işlemlerinize göre de bu yapılar değişiklik gösterir.

 

Host Kısmı :

[DataContract]
public class Product
{
private int _productId;

private string _productName;

[DataMember]
public string ProductName
{
get { return _productName; }
set { _productName = value; }
}

[DataMember]
public int ProductID
{
get { return _productId; }
set { _productId = value; }
}

}

[ServiceContract]
public interface ITestService
{
[OperationContract]
List<Product> GetProductList();

[OperationContract]
byte[] GetProductById(int productID);

[OperationContract]
bool LoadProduct(byte[] product);
}

Bu konfigürasyon dosyasında localhost yerine IP yazabilirsiniz.
Konfigürasyon dosyamız :
------------------------

<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>

<system.serviceModel>
<bindings>
<wsHttpBinding>
<binding name="wsBind" allowCookies="false" bypassProxyOnLocal="false" closeTimeout="00:03:00" hostNameComparisonMode="StrongWildcard"
maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647" messageEncoding="Text" openTimeout="00:03:00" sendTimeout="00:03:00"
textEncoding="utf-8" receiveTimeout="00:03:00" useDefaultWebProxy="true">
<readerQuotas maxDepth="128" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" maxStringContentLength="2147483647"/>
<security mode="None">
<transport clientCredentialType="None" proxyCredentialType="None" realm=""/>
<message clientCredentialType="None" negotiateServiceCredential="false"/>
</security>
</binding>
</wsHttpBinding>
</bindings>

<behaviors>
<serviceBehaviors>
<behavior name="wsBehave">
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="true"/>
</behavior>
</serviceBehaviors>
</behaviors>

<services>
<service name="WpfAppHost.TestService" behaviorConfiguration="wsBehave">
<host>
<baseAddresses>
<add baseAddress="http://localhost:9002/TestService"/>
<add baseAddress="net.tcp://localhost:9003/TestService"/>
</baseAddresses>
</host>

<endpoint address="http://localhost:9002/TestService"
binding="wsHttpBinding" bindingConfiguration="wsBind"
contract="WpfAppHost.ITestService"/>

<endpoint address="net.tcp://localhost:9003/TestService"
binding="netTcpBinding"
contract="WpfAppHost.ITestService"/>

</service>
</services>

</system.serviceModel>
</configuration>

TestService Sınıfımız :
---------------------------------
public class TestService : ITestService
{
List<Product> _product = new List<Product>();

public List<Product> GetProductList()
{
_product.Add(new Product() { ProductID = 1, ProductName = "Product File 1" });
_product.Add(new Product() { ProductID = 2, ProductName = "Product File 2" });
_product.Add(new Product() { ProductID = 3, ProductName = "Product File 3" });
_product.Add(new Product() { ProductID = 4, ProductName = "Product File 4" });
_product.Add(new Product() { ProductID = 5, ProductName = "Product File 5" });

return _product;
}

public byte[] GetProductById(int productID)
{
byte[] buff = null;

if (productID == 1)
buff = File.ReadAllBytes(@"D:\TestFiles\TextFiles1.txt");
else if (productID == 2)
buff = File.ReadAllBytes(@"D:\TestFiles\TextFiles2.txt");
else if (productID == 3)
buff = File.ReadAllBytes(@"D:\TestFiles\TextFiles3.txt");
else if (productID == 4)
buff = File.ReadAllBytes(@"D:\TestFiles\TextFiles4.txt");
else if (productID == 5)
buff = File.ReadAllBytes(@"D:\TestFiles\TextFiles5.txt");

return buff;
}

public bool LoadProduct(byte[] product)
{
bool state = false;

if (product != null)
{
if (product.Length > 0)
{
MemoryStream m = new MemoryStream(product);
m.Position = 0;

if (!File.Exists(@"C:\HOST_File_only\UplodedFile.txt"))
File.Create(@"C:\HOST_File_only\UplodedFile.txt").Close();

using (FileStream f = new FileStream(@"C:\HOST_File_only\UplodedFile.txt", FileMode.Create, FileAccess.Write))
{
m.WriteTo(f);
f.Close();
m.Close();

state = true;
}
}
}
return state;
}

 

Client Kısmı :
--------------

Bir konsol uygulamasına servis referansını ekledikten sonra yazdığım kodlar.

ServiceReference1.TestServiceClient client = new ServiceReference1.TestServiceClient("WSHttpBinding_ITestService");
ServiceReference1.Product[] product = client.GetProductList();

foreach (ServiceReference1.Product p in product)
{
Console.WriteLine("Product ID : {0}", p.ProductID);
Console.WriteLine("Product Name : {0}", p.ProductName);
Console.WriteLine("\n");
}

client.LoadProduct(File.ReadAllBytes(@"D:\TestFile\TestFileFromClient.txt"));

Console.ReadLine();

Client konfigürasyon dosyam :
-----------------------------

<system.serviceModel>
<bindings>
<wsHttpBinding>
<binding name="WSHttpBinding_ITestService">
<security mode="None" />
</binding>
</wsHttpBinding>
</bindings>
<client>
<endpoint address="http://192.168.178.59:9002/TestService" binding="wsHttpBinding"
bindingConfiguration="WSHttpBinding_ITestService" contract="ServiceReference1.ITestService"
name="WSHttpBinding_ITestService" />
</client>
</system.serviceModel>

 

Saygılarımla

There is always something you miss.

 
Gönderildi : 19/04/2017 02:54

(@sinemerkan)
Gönderiler: 234
Reputable Member
Konu başlatıcı
 

yukarıda connectin stringimde sql auth. yaptıgımı belirtmişdim ,SQL mixed modda

web.config aşağıdaki gibi .

 

<configuration> 
 <system.webServer>
  <validation validateIntegratedModeConfiguration="false" />  
 </system.webServer> 
 <system.web>   
  <customErrors mode="Off" />  
  <pages>  
  </compilation>
  <httpRuntime targetFramework="4.5" />
        <trust level="Full" />
        <authentication mode="Windows" />
        <identity impersonate="false" />
 </system.web>
 <system.serviceModel>
  <behaviors>
   <serviceBehaviors>
    <behavior name="servicebehaviors">
     <serviceMetadata httpGetEnabled="true" />     
     <serviceDebug includeExceptionDetailInFaults="true" />
    </behavior>
   </serviceBehaviors>
   <endpointBehaviors>
    <behavior name="web">
     <webHttp />
    </behavior>         
  </endpointBehaviors>  
  </behaviors>  
  <services>
   <service behaviorConfiguration="servicebehaviors" name="WcfWeb.WcfWebService">
    <endpoint contract="WcfWeb.IWcfWebService" binding="basicHttpBinding" behaviorConfiguration="" />    
   </service>
  </services>
  <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
 </system.serviceModel>
</configuration>

 

Benim direk SQL üzerinde çalışmam lazım , dosya listeleme vs. degil ,burdaki herbir farklı yapı için farklı config ler gerekiyor .

Yapı basit olarak Uzakda IIS de host edilen WCF ve aynı yerde DB var , ben DB ' ye farklı lokasyonlardan WCF  ' i winform uygulamama referans ekleyerek sorgulamak ve sorgu sonuçlarını işlemek istiyorum.

 
Gönderildi : 19/04/2017 15:01

(@birolaydugan)
Gönderiler: 867
Prominent Member
 

Direk sorguyalamazsınız,sorgulasanızda bir RETURN methodu yazıp Datatable yada Dataset ile verilere erişebilirsiniz .

[ServiceContract]
public interface IWcfWebService
{

[OperationContract]
DataTable DtMethod(string query);

}

public partial class WcfWebService : IWcfWebService
{

public DataTable DtMethod(string query)
{
var dt = new DataTable();
var da = new SqlDataAdapter(query, RemoteConnection());
da.Fill(dt);
dt.TableName = "dt";
return dt;
}

public string RemoteConnection()
{
var con =ConfigurationManager.ConnectionStrings["cons"].ConnectionString;
return con.ConnectionString;
}

}

 
Gönderildi : 21/04/2017 15:08

(@sinemerkan)
Gönderiler: 234
Reputable Member
Konu başlatıcı
 

Hocam çok tşkler ,tam isabet.

 
Gönderildi : 25/04/2017 19:11

Paylaş: