powered by simpleCommunicator - 2.0.59     © 2025 Programmizd 02
Целевая тема:
Создать новую тему:
Автор:
Закрыть
Цитировать
Форумы / WCF, Web Services, Remoting [игнор отключен] [закрыт для гостей] / WCF и несколько классов
25 сообщений из 25, страница 1 из 1
WCF и несколько классов
    #35124174
Фотография webus
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Начинаю строить WCF сервис для WinForms. Стоит следующая задача. Имеется сборка бизнес - логики. Она состоит из нескольких классов(бизнес объектов). Клиент WCF должен работать с этимим классами прозрачно. На сколько я знаю клиентское ПО будет общаться с WCF сервисом используя заранее известный интерфейс. Интерфейс используется для реализации от него только одного класса. Т.е. что имеем:

Вот наша бизнес логика:

Код: plaintext
1.
2.
3.
4.
5.
6.
public class BusinessObjectOne {
 /*тут реализуем поля,свойства,методы*/
}
public class BusinessObjectTwo {
 /*тут реализуем поля,свойства,методы*/
}

Как прозрачно хотим использовать их на клиенте:
Код: plaintext
1.
2.
BusinessObjectOne bo1 = new BusinessObjectOne();
BusinessObjectTwo bo2 = new BusinessObjectTwo();

Для реализации WCF определяем интерфейс
Код: plaintext
1.
2.
3.
public interface IBusinessObject {
/*вот тут вопрос как тут объявить те два класса?*/
}

Вопрос в чем. Можно ли это как то реализовать для WCF? И использовать с WCF.
Пока что делаю общий интерфейс где названия методов различаю, подставляя впереди названия метода, название класса.
...
Рейтинг: 0 / 0
WCF и несколько классов
    #35124277
Фотография Нахлобуч
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Неправильно. Правильно бизнес-классы сложить в одну кучу, бизнес-логику -- в другую. То есть:

Код: plaintext
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
public class Document : BusinessObject
{
}

public interface IDocumentApprovalService
{
	void ApproveDocument(Document document);
	void RevokeApproval(Document document);
}


И уже IDocumentApprovalService надо делать доступным через WCF.
...
Рейтинг: 0 / 0
WCF и несколько классов
    #35124297
Фотография webus
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
НахлобучНеправильно. Правильно бизнес-классы сложить в одну кучу, бизнес-логику -- в другую. То есть:

Код: plaintext
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
public class Document : BusinessObject
{
}

public interface IDocumentApprovalService
{
	void ApproveDocument(Document document);
	void RevokeApproval(Document document);
}


И уже IDocumentApprovalService надо делать доступным через WCF.

Не понял что у тебя делают эти методы:
Код: plaintext
1.
2.
void ApproveDocument(Document document);
void RevokeApproval(Document document);

И как я смогу видеть БО если в IDocumentApprovalService они не определены ?

Локально с приложением сборку с БО таскать не катит. Хочется централизованно бизнес логику обновлять.
...
Рейтинг: 0 / 0
WCF и несколько классов
    #35124367
Фотография Нахлобуч
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
webusИ как я смогу видеть БО если в IDocumentApprovalService они не определены ?
Поясни, не понял.
webus
Локально с приложением сборку с БО таскать не катит. Хочется централизованно бизнес логику обновлять.
Я ж и говорю -- объекты и логику держи отдельно. Клиент и сервер оперируют одним и тем же набором бизнес-объектов, а вся логика сосредоточена на сервере и доступ к ним осуществляется через эти самые интерфейсы.

Пример, который я показал, -- просто пример. Есть класс "документ", его можно "утверждать". Вся логика утверждения вынесена из класса Document в сервис IDocumentApprovalService.
...
Рейтинг: 0 / 0
WCF и несколько классов
    #35125471
ВМоисеев
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
>webus
> ...Имеется сборка бизнес - логики ...
Может попытаться так - сборка бизнес-логики содержит класс реализации интерфейсов. Бизнес-логика реализуется в методах соответствующих классов. Для каждого класса бизнес-логики свой интерфейс. Имеется в сборке и класс, реализующий сервис - все методы всех классов бизнес-логики (класс переходов). Здесь каждый метод, не более чем вызов требуемого метода соответствующего класса бизнес-логики.

Код: plaintext
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
namespace ns_ЦУС {
  //-- Определяем множество интерфейсов 
  //-- например по одному для каждого бизнес-класса
  [ServiceContract]
  public interface IОбработкаЗапроса {
    [OperationContract]
    byte[] ОбработкаЗапроса(byte[] bv);
  }
  [ServiceContract]
  public interface IКриптоСервер  {
    [OperationContract]
    byte[] ЧтениеЗапросаКриптоСервером(byte id);
    [OperationContract]
    byte[] ЗаписьОтветаКриптоСервером(byte[] bv);
    [OperationContract]
    byte[] ЗаписьОтветаКриптоСерверомСтоп(byte[] bv);
    [OperationContract]
    byte[] ПолучитьПараметрыНастройки(byte id);
    [OperationContract]
    void УстановитьВремяОжиданияОтвета(byte[] bv);
  }
  [ServiceContract]
  public interface ITimeOut {
    [OperationContract]
    void УстановитьРазмерСтраницы(byte[] bv);
    [OperationContract]
    void TimeOut();
  }

  [ServiceContract]
  public interface IЦУС_Impl:IОбработкаЗапроса,IКриптоСервер,ITimeOut {} 
  
  //-- А это определение класса сервиса
  //-------------------------------------------------------- 
  //-- Сервис управления взаимодействием с клиентом
  [ServiceBehavior(
    InstanceContextMode = InstanceContextMode.Single,
    ConcurrencyMode = ConcurrencyMode.Multiple)
  ]
  //public class ЦУС_Impl : IОбработкаЗапроса, IКриптоСервер, ITimeOut {
  public class ЦУС_Impl : IЦУС_Impl {
  ...
На уровне клиентского приложения можно работать с интерфейсами, которые реализует класс сервиса. Каждый метод класса сервиса вызывает метод соответствующего класса бизнес-логики.
Классы бизнес-логики создаются в конструкторе класса сервиса

С уважением, Владимир.
...
Рейтинг: 0 / 0
WCF и несколько классов
    #35125517
Фотография bured
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
А в чём напряг создать 2 сервиса?
Сервис
Код: plaintext
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
62.
63.
64.
65.
66.
67.
68.
69.
70.
71.
72.
73.
74.
75.
76.
77.
78.
79.
80.
81.
82.
83.
84.
85.
86.
87.
88.
89.
90.
91.
92.
93.
94.
95.
96.
97.
98.
99.
100.
101.
102.
103.
104.
105.
106.
107.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

// A WCF service consists of a contract (defined below as IService).
namespace BusinessServiceContracts
{

    [ServiceContract]
    public interface IAdmin
    {
        [OperationContract]
        string AdminOperation1();
        [OperationContract]
        string AdminOperation2();
    }
    [ServiceContract]
    public interface IServiceA
    {
        [OperationContract]
        string Operation1();
        [OperationContract]
        string Operation2();
    }
    [ServiceContract]
    public interface IServiceB
    {
        [OperationContract]
        string Operation3();
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

/* a class which implements IService (see Service),
 * and configuration entries that specify behaviors associated with 
 * that implementation (see <system.serviceModel> in web.config)*/
using BusinessServiceContracts;

namespace BusinessServices
{

    
    public class ServiceA : IServiceA, IAdmin
    {
        string IServiceA.Operation1()
        {
            return "IServiceA.Operation1() invoked.";
        }
        string IServiceA.Operation2()
        {
            return "IServiceA.Operation2() invoked.";
        }
        string IAdmin.AdminOperation1()
        {
            return "IAdmin.AdminOperation1 invoked.";
        }
        string IAdmin.AdminOperation2()
        {
            return "IAdmin.AdminOperation2 invoked.";
        }


    }
    
    public class ServiceB : IServiceB, IAdmin
    {
        string IServiceB.Operation3()
        {
            return "IServiceB.Operation3() invoked.";
        }
        string IAdmin.AdminOperation1()
        {
            return "IAdmin.AdminOperation1 invoked.";
        }
        string IAdmin.AdminOperation2()
        {
            return "IAdmin.AdminOperation2 invoked.";
        }
    }


}
<services>
<service name="BusinessServices.ServiceA" behaviorConfiguration="ServiceBehavior">
				<!-- Service Endpoints -->
				<endpoint address="http://localhost/WCF/MultiContractService/ServiceA.svc" binding="wsHttpBinding" contract="BusinessServiceContracts.IServiceA"/>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
        <endpoint address="http://localhost/WCF/MultiContractService/ServiceA.svc" contract="BusinessServiceContracts.IAdmin"
		  binding="wsHttpBinding" />
			</service>
		
    <service name="BusinessServices.ServiceB" behaviorConfiguration="ServiceBehavior">
      <!-- Service Endpoints -->
      <endpoint address="http://localhost/WCF/MultiContractService/ServiceB.svc" binding="wsHttpBinding" contract="BusinessServiceContracts.IServiceB"/>
      <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
      <endpoint address="http://localhost/WCF/MultiContractService/ServiceB.svc" contract="BusinessServiceContracts.IAdmin"
		  binding="wsHttpBinding" />
    </service>
    </services>
Клиент
Код: plaintext
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
62.
63.
64.
65.
66.
67.
68.
69.
70.
71.
72.
73.
74.
75.
76.
77.
78.
79.
80.
81.
82.
83.
84.
85.
86.
87.
88.
89.
90.
91.
92.
93.
94.
95.
96.
97.
98.
99.
100.
101.
102.
103.
104.
105.
106.
107.
108.
109.
110.
111.
112.
113.
114.
115.
using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml.Linq;
using System.ServiceModel;


[ServiceContract]
public interface IAdmin
{
    [OperationContract]
    string AdminOperation1();
    [OperationContract]
    string AdminOperation2();
}
[ServiceContract]
public interface IServiceA
{
    [OperationContract]
    string Operation1();
    [OperationContract]
    string Operation2();
}
[ServiceContract]
public interface IServiceB
{
    [OperationContract]
    string Operation3();
}

public partial class _Default : System.Web.UI.Page 
{
    
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        string s; 
        EndpointAddress ep1 = new EndpointAddress("http://localhost/WCF/MultiContractService/ServiceA.svc");
        IServiceA proxyA = ChannelFactory<IServiceA>.CreateChannel(new WSHttpBinding(), ep1);
        
        using (proxyA as IDisposable)
        {
            
            s = proxyA.Operation1();
            ListBox1.Items.Add(s);
            s = proxyA.Operation2();
            ListBox1.Items.Add(s);
        }
        EndpointAddress ep2 = new EndpointAddress("http://localhost/WCF/MultiContractService/ServiceB.svc");
        IServiceB proxyB = ChannelFactory<IServiceB>.CreateChannel(new WSHttpBinding(), ep2);
        using (proxyB as IDisposable)
        {

            s = proxyB.Operation3();
            ListBox1.Items.Add(s);
           
        }
        //EndpointAddress ep = new EndpointAddress("http://localhost/WCF/MultiContractService/ServiceA.svc");
        IAdmin proxyAA = ChannelFactory<IAdmin>.CreateChannel(new WSHttpBinding(), ep1);

        using (proxyAA as IDisposable)
        {

            s = proxyAA.AdminOperation1();
            ListBox1.Items.Add(s);
            s = proxyAA.AdminOperation2();
            ListBox1.Items.Add(s);
        }
        //ep = new EndpointAddress("http://localhost/WCF/MultiContractService/ServiceB.svc");
        IAdmin proxyBB = ChannelFactory<IAdmin>.CreateChannel(new WSHttpBinding(), ep2);
        using (proxyBB as IDisposable)
        {

            s = proxyBB.AdminOperation1();
            ListBox1.Items.Add(s);
            s = proxyBB.AdminOperation2();
            ListBox1.Items.Add(s);

        }
          
            
        
    }
}
<client>
			<endpoint address="http://localhost/WCF/MultiContractService/ServiceA.svc" binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_IServiceA" contract="ServiceReference.IServiceA" name="WSHttpBinding_IServiceA">
				<identity>
					<servicePrincipalName value="host/Т-1000-ПК"/>
				</identity>
			</endpoint>
      <endpoint address="http://localhost/WCF/MultiContractService/ServiceA.svc" binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_IServiceA" contract="ServiceReference.IAdmin" name="WSHttpBinding_IServiceA">
        <identity>
          <servicePrincipalName value="host/Т-1000-ПК"/>
        </identity>
      </endpoint>
			<endpoint address="http://localhost/WCF/MultiContractService/ServiceB.svc" binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_IServiceB" contract="ServiceReference1.IServiceB" name="WSHttpBinding_IServiceB">
				<identity>
					<servicePrincipalName value="host/Т-1000-ПК"/>
				</identity>
			</endpoint>
      <endpoint address="http://localhost/WCF/MultiContractService/ServiceB.svc" binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_IServiceB" contract="ServiceReference1.IAdmin" name="WSHttpBinding_IServiceB">
        <identity>
          <servicePrincipalName value="host/Т-1000-ПК"/>
        </identity>
      </endpoint>
		</client>_____________________________________________
Death to Videodrome, long live the New Flesh!
...
Рейтинг: 0 / 0
WCF и несколько классов
    #35125526
Фотография bured
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Внимательно глянь мой пример. Каждый сервис реализует 2 интерфейса. И проксю можно создавать от каждого. Возможно это тебя устроит.
_____________________________________________
Death to Videodrome, long live the New Flesh!
...
Рейтинг: 0 / 0
WCF и несколько классов
    #35125849
Фотография webus
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
buredВнимательно глянь мой пример. Каждый сервис реализует 2 интерфейса. И проксю можно создавать от каждого. Возможно это тебя устроит.
_____________________________________________
Death to Videodrome, long live the New Flesh!

Да ты прав. Твой пример мне подходит. Спасибо!
...
Рейтинг: 0 / 0
WCF и несколько классов
    #35126106
ВМоисеев
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
>bured
>Внимательно глянь мой пример...
Может быть в этом случае совсем отказаться от размещения в сборке 2-х сервисов?
Каждый сервис - одна сборка.

С уважением, Владимир.
...
Рейтинг: 0 / 0
WCF и несколько классов
    #35127858
Фотография bured
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
2 ВМоисеев

Иерархию контрактов лучше делать в одной сборке.
_____________________________________________
Death to Videodrome, long live the New Flesh!
...
Рейтинг: 0 / 0
WCF и несколько классов
    #35128223
ВМоисеев
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
>bured
>Иерархию контрактов ...
Можно чуть поподробнее. Я не сталкивался с подобными задачами.

С уважением, Владимир.
...
Рейтинг: 0 / 0
WCF и несколько классов
    #35128235
Фотография bured
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Иерархия в смысле наследование контрактов.
Сервер
Код: plaintext
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

/* a class which implements IService (see Service),
 * and configuration entries that specify behaviors associated with 
 * that implementation (see <system.serviceModel> in web.config)*/
[ServiceContract]
interface ISimpleCalculator
{
    [OperationContract]
    int Add(int arg1, int arg2);
}
[ServiceContract]
interface IScientificCalculator : ISimpleCalculator
{
    [OperationContract]
    int Multiply(int arg1, int arg2);
}

public class Service : IScientificCalculator
{
    public int Add(int arg1, int arg2)
	{
        return arg1 + arg2;
	}
    public int Multiply(int arg1, int arg2)
    {
        return arg1 * arg2;
    }
	
}
/////////////////
<services>
			<service name="Service" behaviorConfiguration="ServiceBehavior">
				<!-- Service Endpoints -->
				
        <endpoint address="" binding="wsHttpBinding" contract="IScientificCalculator"/>
				<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
			</service>
		</services>
клиент
Код: plaintext
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
62.
63.
64.
65.
66.
67.
68.
69.
70.
71.
72.
73.
74.
75.
76.
77.
78.
79.
80.
81.
82.
83.
84.
85.
86.
87.
88.
89.
90.
91.
92.
93.
94.
95.
96.
97.
98.
99.
100.
101.
102.
103.
104.
using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml.Linq;
using System.ServiceModel;
using System.ServiceModel.Channels;

[ServiceContract]
public interface ISimpleCalculator
{
    [OperationContract]
    int Add(int arg1, int arg2);
}
[ServiceContract]
public interface IScientificCalculator : ISimpleCalculator
{
    [OperationContract]
    int Multiply(int arg1, int arg2);
}
public partial class MySimpleClient : ClientBase<ISimpleCalculator>, ISimpleCalculator
{
    public MySimpleClient()
    { }
    public MySimpleClient(string endpointName)
        : base(endpointName)
    { }
    public MySimpleClient(Binding binding, EndpointAddress remoteAddress) :
        base(binding, remoteAddress)
    { }
    /* Additional constructors */

    public int Add(int arg1, int arg2)
    {
        return Channel.Add(arg1, arg2);
    }
    
}

public partial class MyScientificClient : ClientBase<IScientificCalculator>, IScientificCalculator
{
    public MyScientificClient()
    { }
    public MyScientificClient(string endpointName)
        : base(endpointName)
    { }
    public MyScientificClient(Binding binding, EndpointAddress remoteAddress) :
        base(binding, remoteAddress)
    { }
    /* Additional constructors */

    
    public int Multiply(int arg1, int arg2)
    {
        return Channel.Multiply(arg1, arg2);
    }
    public int Add(int arg1, int arg2)
    {
        return Channel.Add(arg1, arg2);
    }

}

public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        
        MySimpleClient proxy1 = new MySimpleClient();

        int Addresult = proxy1.Add(2, 3);

        MyScientificClient proxy2 = new MyScientificClient();

        int Addresult2 = proxy2.Add(2, 3);
        int Multiplyresult =  proxy2.Multiply(2, 3);

        
        Response.Write("Add result proxy1: " + Addresult.ToString() + " Add result proxy2: " + Addresult2.ToString() +" Multiply result: " + Multiplyresult.ToString());
        
    }
}
/////////////////////
<client>
			<endpoint address="http://localhost/WCF/ContractInheritanceService/Service.svc" binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_ISimpleCalculator" contract="ISimpleCalculator" name="WSHttpBinding_ISimpleCalculator">
				<identity>
					<servicePrincipalName value="host/Т-1000-ПК"/>
				</identity>
			</endpoint>
      <endpoint address="http://localhost/WCF/ContractInheritanceService/Service.svc" binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_IScientificCalculator" contract="IScientificCalculator" name="WSHttpBinding_IScientificCalculator">
        <identity>
          <servicePrincipalName value="host/Т-1000-ПК"/>
        </identity>
      </endpoint>
</client>	
_____________________________________________
Death to Videodrome, long live the New Flesh!
...
Рейтинг: 0 / 0
WCF и несколько классов
    #35128985
ВМоисеев
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
>bured
>Иерархия в смысле наследование контрактов.
Спасибо за представлннную информацию.

С уважением, Владимир.
...
Рейтинг: 0 / 0
WCF и несколько классов
    #35237077
2 bured
Спасибо, очень полезные примеры.
...
Рейтинг: 0 / 0
WCF и несколько классов
    #35237298
Фотография bured
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Примеры взяты из этой книги. Кстати, вроде бы на русском скоро должна выйти.
...
Рейтинг: 0 / 0
WCF и несколько классов
    #35387483
Фотография bured
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Всё проще оказывается, если классы отнаследованы от базового.

Сервис

Код: plaintext
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
62.
63.
64.
65.
66.
67.
68.
69.
70.
71.
72.
73.
74.
75.
76.
77.
78.
79.
80.
81.
82.
83.
84.
85.
86.
87.
88.
89.
90.
91.
92.
93.
94.
95.
96.
97.
98.
99.
100.
101.
102.
103.
104.
105.
106.
107.
108.
109.
110.
111.
112.
113.
114.
115.
116.
117.
118.
119.
120.
121.
122.
123.
124.
125.
126.
127.
128.
129.
130.
131.
[ServiceContract]
public interface IService
{

	[OperationContract]
    TeamMember GetData(string who);

	// TODO: Add your service operations here
}

// Use a data contract as illustrated in the sample below to add composite types to service operations.
[DataContract]
[KnownType(typeof(Player))]
[KnownType(typeof(Coach))]
public class TeamMember
{
    
    string firstName;
    string secondName;
    int gamesCount;
    

    [DataMember]
    public string FirstName
    {
        get { return firstName; }
        set { firstName = value; }
    }

    [DataMember]
    public string SecondName
    {
        get { return secondName; }
        set { secondName = value; }
    }
    [DataMember]
    public int GamesCount
    {
        get { return gamesCount; }
        set { gamesCount = value; }
    }
}

[DataContract]
public class Player : TeamMember
{
    int goals;
    
    [DataMember]
    public int Goals
    {
        get { return goals; }
        set { goals = value; }
    }
}

[DataContract]
public class Coach : TeamMember
{
    int wins;


    [DataMember]
    public int Wins
    {
        get { return wins; }
        set { wins = value; }
    }
}

public class Service : IService
{
    public TeamMember GetData(string who)
	{
        switch (who)
        {
            
        case "coach":
                {
                    Coach coach = new Coach();
                    coach.FirstName = "Hiddink";
                    coach.SecondName = "Guus";
                    coach.GamesCount=4;
                    coach.Wins = 3;
                    return (TeamMember)coach;
                    break;
                }

            case "player":
                {
                    Player player = new Player();
                    player.FirstName = "Arshavin";
                    player.SecondName = "Andrey";
                    player.GamesCount=2;
                    player.Goals = 2;
                    return (TeamMember)player;
                    break;
                }
            default:
                {
                    TeamMember teamMember = new TeamMember();
                    teamMember.FirstName = "Unknow";
                    teamMember.SecondName = "Unknow";
                    teamMember.GamesCount = 0;
                    return teamMember;
                    break;
                }

                
        }
	}

    
}
///////////////////////////////
<services>
			<service name="Service" behaviorConfiguration="ServiceBehavior">
				<!-- Service Endpoints -->
				<endpoint address="" binding="wsHttpBinding" contract="IService">
					<!-- 
              Upon deployment, the following identity element should be removed or replaced to reflect the 
              identity under which the deployed service runs.  If removed, WCF will infer an appropriate identity 
              automatically.
          -->
					<identity>
						<dns value="localhost"/>
					</identity>
				</endpoint>
				<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
			</service>
</services>

Клиент
Код: plaintext
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
62.
63.
64.
65.
66.
67.
68.
69.
70.
71.
72.
73.
74.
75.
76.
77.
78.
79.
80.
81.
82.
83.
84.
85.
86.
87.
88.
89.
90.
91.
92.
93.
94.
95.
96.
97.
98.
99.
100.
101.
102.
103.
104.
105.
106.
107.
108.
109.
110.
111.
112.
113.
114.
115.
116.
117.
118.
[ServiceContract]
public interface IService
{

    [OperationContract]
    TeamMember GetData(string who);

    // TODO: Add your service operations here
}

// Use a data contract as illustrated in the sample below to add composite types to service operations.
[DataContract]
[KnownType(typeof(Player))]
[KnownType(typeof(Coach))]
public class TeamMember 
{
    
    string firstName;
    string secondName;
    int gamesCount;
   

    [DataMember]
    public string FirstName
    {
        get { return firstName; }
        set { firstName = value; }
    }

    [DataMember]
    public string SecondName
    {
        get { return secondName; }
        set { secondName = value; }
    }
    [DataMember]
    public int GamesCount
    {
        get { return gamesCount; }
        set { gamesCount = value; }
    }
}

[DataContract]

public class Player : TeamMember
{
    int goals;
    
    [DataMember]
    public int Goals
    {
        get { return goals; }
        set { goals = value; }
    }
}

[DataContract]
public class Coach : TeamMember
{
    int wins;


    [DataMember]
    public int Wins
    {
        get { return wins; }
        set { wins = value; }
    }
}
public partial class MyContractClient : ClientBase<IService>, IService
{
    public MyContractClient()
    { }
    public MyContractClient(string endpointName)
        : base(endpointName)
    { }
    public MyContractClient(Binding binding, EndpointAddress remoteAddress) :
        base(binding, remoteAddress)
    { }
    /* Additional constructors */

    public TeamMember GetData(string who)
    {
        return Channel.GetData(who);
    }
    
}

public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {
        


    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        
        MyContractClient proxy = new MyContractClient("MyEndpoint");
        Player player = new Player();
        player = (Player)proxy.GetData("player");
        Label1.Text = player.FirstName + " " + player.SecondName+" Games: "+player.GamesCount.ToString()+" Goals: "+player.Goals.ToString();
        Coach coach = new Coach();
        coach = (Coach)proxy.GetData("coach");
        Label2.Text = coach.FirstName + " " + coach.SecondName + " Games: " + coach.GamesCount.ToString() + " Wins: " + coach.Wins.ToString();
        proxy.Close();
    }
}
///////////////////////////
<client>
			<endpoint address="http://t-1000/my/WCF/WCFServiceSQLru/Service.svc" binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_IService" contract="IService" name="MyEndpoint">
				<identity>
					<dns value="localhost"/>
				</identity>
			</endpoint>
</client>
...
Рейтинг: 0 / 0
WCF и несколько классов
    #35387484
Фотография bured
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
P.S. webus поставь для меня песенку
...
Рейтинг: 0 / 0
WCF и несколько классов
    #35524912
Фотография flashslash
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
buredА в чём напряг создать 2 сервиса?
Сервис
Код: plaintext
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
62.
63.
64.
65.
66.
67.
68.
69.
70.
71.
72.
73.
74.
75.
76.
77.
78.
79.
80.
81.
82.
83.
84.
85.
86.
87.
88.
89.
90.
91.
92.
93.
94.
95.
96.
97.
98.
99.
100.
101.
102.
103.
104.
105.
106.
107.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

// A WCF service consists of a contract (defined below as IService).
namespace BusinessServiceContracts
{

    [ServiceContract]
    public interface IAdmin
    {
        [OperationContract]
        string AdminOperation1();
        [OperationContract]
        string AdminOperation2();
    }
    [ServiceContract]
    public interface IServiceA
    {
        [OperationContract]
        string Operation1();
        [OperationContract]
        string Operation2();
    }
    [ServiceContract]
    public interface IServiceB
    {
        [OperationContract]
        string Operation3();
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

/* a class which implements IService (see Service),
 * and configuration entries that specify behaviors associated with 
 * that implementation (see <system.serviceModel> in web.config)*/
using BusinessServiceContracts;

namespace BusinessServices
{

    
    public class ServiceA : IServiceA, IAdmin
    {
        string IServiceA.Operation1()
        {
            return "IServiceA.Operation1() invoked.";
        }
        string IServiceA.Operation2()
        {
            return "IServiceA.Operation2() invoked.";
        }
        string IAdmin.AdminOperation1()
        {
            return "IAdmin.AdminOperation1 invoked.";
        }
        string IAdmin.AdminOperation2()
        {
            return "IAdmin.AdminOperation2 invoked.";
        }


    }
    
    public class ServiceB : IServiceB, IAdmin
    {
        string IServiceB.Operation3()
        {
            return "IServiceB.Operation3() invoked.";
        }
        string IAdmin.AdminOperation1()
        {
            return "IAdmin.AdminOperation1 invoked.";
        }
        string IAdmin.AdminOperation2()
        {
            return "IAdmin.AdminOperation2 invoked.";
        }
    }


}
<services>
<service name="BusinessServices.ServiceA" behaviorConfiguration="ServiceBehavior">
				<!-- Service Endpoints -->
				<endpoint address="http://localhost/WCF/MultiContractService/ServiceA.svc" binding="wsHttpBinding" contract="BusinessServiceContracts.IServiceA"/>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
        <endpoint address="http://localhost/WCF/MultiContractService/ServiceA.svc" contract="BusinessServiceContracts.IAdmin"
		  binding="wsHttpBinding" />
			</service>
		
    <service name="BusinessServices.ServiceB" behaviorConfiguration="ServiceBehavior">
      <!-- Service Endpoints -->
      <endpoint address="http://localhost/WCF/MultiContractService/ServiceB.svc" binding="wsHttpBinding" contract="BusinessServiceContracts.IServiceB"/>
      <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
      <endpoint address="http://localhost/WCF/MultiContractService/ServiceB.svc" contract="BusinessServiceContracts.IAdmin"
		  binding="wsHttpBinding" />
    </service>
    </services>
Клиент
Код: plaintext
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
62.
63.
64.
65.
66.
67.
68.
69.
70.
71.
72.
73.
74.
75.
76.
77.
78.
79.
80.
81.
82.
83.
84.
85.
86.
87.
88.
89.
90.
91.
92.
93.
94.
95.
96.
97.
98.
99.
100.
101.
102.
103.
104.
105.
106.
107.
108.
109.
110.
111.
112.
113.
114.
115.
using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml.Linq;
using System.ServiceModel;


[ServiceContract]
public interface IAdmin
{
    [OperationContract]
    string AdminOperation1();
    [OperationContract]
    string AdminOperation2();
}
[ServiceContract]
public interface IServiceA
{
    [OperationContract]
    string Operation1();
    [OperationContract]
    string Operation2();
}
[ServiceContract]
public interface IServiceB
{
    [OperationContract]
    string Operation3();
}

public partial class _Default : System.Web.UI.Page 
{
    
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        string s; 
        EndpointAddress ep1 = new EndpointAddress("http://localhost/WCF/MultiContractService/ServiceA.svc");
        IServiceA proxyA = ChannelFactory<IServiceA>.CreateChannel(new WSHttpBinding(), ep1);
        
        using (proxyA as IDisposable)
        {
            
            s = proxyA.Operation1();
            ListBox1.Items.Add(s);
            s = proxyA.Operation2();
            ListBox1.Items.Add(s);
        }
        EndpointAddress ep2 = new EndpointAddress("http://localhost/WCF/MultiContractService/ServiceB.svc");
        IServiceB proxyB = ChannelFactory<IServiceB>.CreateChannel(new WSHttpBinding(), ep2);
        using (proxyB as IDisposable)
        {

            s = proxyB.Operation3();
            ListBox1.Items.Add(s);
           
        }
        //EndpointAddress ep = new EndpointAddress("http://localhost/WCF/MultiContractService/ServiceA.svc");
        IAdmin proxyAA = ChannelFactory<IAdmin>.CreateChannel(new WSHttpBinding(), ep1);

        using (proxyAA as IDisposable)
        {

            s = proxyAA.AdminOperation1();
            ListBox1.Items.Add(s);
            s = proxyAA.AdminOperation2();
            ListBox1.Items.Add(s);
        }
        //ep = new EndpointAddress("http://localhost/WCF/MultiContractService/ServiceB.svc");
        IAdmin proxyBB = ChannelFactory<IAdmin>.CreateChannel(new WSHttpBinding(), ep2);
        using (proxyBB as IDisposable)
        {

            s = proxyBB.AdminOperation1();
            ListBox1.Items.Add(s);
            s = proxyBB.AdminOperation2();
            ListBox1.Items.Add(s);

        }
          
            
        
    }
}
<client>
			<endpoint address="http://localhost/WCF/MultiContractService/ServiceA.svc" binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_IServiceA" contract="ServiceReference.IServiceA" name="WSHttpBinding_IServiceA">
				<identity>
					<servicePrincipalName value="host/Т-1000-ПК"/>
				</identity>
			</endpoint>
      <endpoint address="http://localhost/WCF/MultiContractService/ServiceA.svc" binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_IServiceA" contract="ServiceReference.IAdmin" name="WSHttpBinding_IServiceA">
        <identity>
          <servicePrincipalName value="host/Т-1000-ПК"/>
        </identity>
      </endpoint>
			<endpoint address="http://localhost/WCF/MultiContractService/ServiceB.svc" binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_IServiceB" contract="ServiceReference1.IServiceB" name="WSHttpBinding_IServiceB">
				<identity>
					<servicePrincipalName value="host/Т-1000-ПК"/>
				</identity>
			</endpoint>
      <endpoint address="http://localhost/WCF/MultiContractService/ServiceB.svc" binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_IServiceB" contract="ServiceReference1.IAdmin" name="WSHttpBinding_IServiceB">
        <identity>
          <servicePrincipalName value="host/Т-1000-ПК"/>
        </identity>
      </endpoint>
		</client>_____________________________________________
Death to Videodrome, long live the New Flesh!

А считаю, что примеры предоставлены с ошибками!
1-е - это почему у хоста address="" а у клиента address="http://localhost/WCF/MultiContractService/ServiceA.svc"
такое в принципе не должно работать вместе.
2. если на хосте так и оставить как есть такой урезанный конфиг, то работать тоже не будет.
при билде компилятор будет ругаться на неизвестный интерфейс
IMetadataExchange

короче ничего не работает.. автор топика либо сам додумался, либо знал как настроить конфиги хоста и клиента.
...
Рейтинг: 0 / 0
WCF и несколько классов
    #35525219
Мля
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
За такой оверквотинг поубывал бы.
...
Рейтинг: 0 / 0
WCF и несколько классов
    #35525240
Фотография flashslash
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
МляЗа такой оверквотинг поубывал бы.
иди и поубивай
...
Рейтинг: 0 / 0
WCF и несколько классов
    #35525300
Мля
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
flashslash МляЗа такой оверквотинг поубывал бы.
иди и поубивай
Уже. Колесо.
...
Рейтинг: 0 / 0
WCF и несколько классов
    #35525636
Фотография bured
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Убивают люди которые ни хрена не умеют, а только звездят.
Держи, дядя не жадный. У меня хостилось на IIS.
...
Рейтинг: 0 / 0
WCF и несколько классов
    #35525642
Фотография bured
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
2 ФлэшСлэш
Могу ещё выслать. Пиши письма.
...
Рейтинг: 0 / 0
WCF и несколько классов
    #35525789
Фотография bured
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Упс, я и не посмотрел с кем разговариваю.
Думаю разговор окончен.
...
Рейтинг: 0 / 0
WCF и несколько классов
    #35525791
Фотография bured
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
это какая-то web-версия Композитума.
...
Рейтинг: 0 / 0
25 сообщений из 25, страница 1 из 1
Форумы / WCF, Web Services, Remoting [игнор отключен] [закрыт для гостей] / WCF и несколько классов
Найденые пользователи ...
Разблокировать пользователей ...
Читали форум (0):
Пользователи онлайн (0):
x
x
Закрыть


Просмотр
0 / 0
Close
Debug Console [Select Text]