23.02.2018, 17:42. Показов 4104. Ответов 20
Не получается настроить wcf service с callbackcontract-ом. Когда пытаюсь добавить на клиенте (WPF) ссылку на службу, выдаёт ошибку, показанную на прикреплённом скрине.
Очень ищу человечка который сможет мне помочь, просто я уже устал с этим бороться и от безысходности пишу сюда. Спасибо заранее всем, но очень прошу пишите ваш ответ более подробнее, а то есть вероятность, что он мне не поможет. Спасибо ещё раз.
Моя служба AuthorizationService:
| C# |
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
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
| using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Runtime.Serialization;
using System.Security.Cryptography;
using System.ServiceModel;
using System.Text;
using WCFServiceLibrary.Models;
using WCFServiceLibrary.Validators;
namespace WCFServiceLibrary.Services
{
[ServiceContract]
[ServiceKnownType(typeof(User))]
[ServiceKnownType(typeof(Validator<User>))]
[ServiceKnownType(typeof(UserInUseValidator))]
[ServiceKnownType(typeof(UserSignInValidator))]
[ServiceKnownType(typeof(IObserver))]
public interface IAuthorizationService
{
[OperationContract]
string SignIn(User u, IEnumerable<Validator<User>> validators);
[OperationContract]
void SignOut(User u);
[OperationContract]
IEnumerable<int> GetUsedUserIds();
}
[ServiceContract(SessionMode = SessionMode.Required, CallbackContract = typeof(IObserver))]
public interface IObservable
{
[OperationContract]
void AddObserver(int usedUserId);
[OperationContract]
void RemoveObserver(int usedUserId);
[OperationContract(IsOneWay = true)]
void NotifyObservers();
}
[ServiceContract]
public interface IObserver
{
[OperationContract(IsOneWay = true)]
void OnUpdate(string text, IEnumerable<int> usedUserIds);
}
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession)]
public class AuthorizationService : Service, IAuthorizationService, IObservable
{
private GenericRepository<User> UserRepository;
private GenericRepository<Log> LogRepository;
public delegate void CallbackDelegate<T>(T t, IEnumerable<int> usedUserIds);
public static CallbackDelegate<string> Update;
internal static bool ObserversHaveChanged = true;
internal static int initialLogId;
internal static List<int> UsedUserIds = new List<int>();
public AuthorizationService()
{
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
if (!config.ConnectionStrings.SectionInformation.IsProtected)
{
config.ConnectionStrings.SectionInformation.ProtectSection("DataProtectionConfigurationProvider");
config.Save();
}
UserRepository = new GenericRepository<User>(context);
LogRepository = new GenericRepository<Log>(context);
initialLogId = context.Logs.Last().Id;
}
public void Save()
{
context.SaveChanges();
}
public string SignIn(User u, IEnumerable<Validator<User>> validators)
{
StringBuilder sb = new StringBuilder();
int PasswordLength;
string buffer;
// Генерация хеша пароля с солью
u.Password = SHA512Hash.GenerateString("I aM A" + u.Password + "Lil slT");
PasswordLength = u.Password.Length;
// Отбор 32 символов из всего хеша (7 начальных, 23 центральных и 2 конечных символов)
sb.Append(u.Password, 0, 7);
sb.Append(u.Password, PasswordLength / 2, 23);
sb.Append(u.Password, PasswordLength - 2, 2);
u.Password = sb.ToString();
sb.Clear();
foreach(Validator<User> validator in validators)
{
buffer = validator.Check(u);
if (buffer != String.Empty)
{
sb.Append("● ");
sb.Append(buffer);
sb.Append("\n");
}
}
buffer = sb.ToString();
if (buffer == String.Empty)
{
LogRepository.Insert(new Log() { Event_type_id = 2, Message = "Пользователь " + u.Login + " прошёл авторизацию.", Event_time = DateTime.Now });
Save();
int UserId = UserRepository.Get(uu => uu.Login == u.Login).Select(uu => uu.Id).FirstOrDefault();
if (UserId != 0)
UsedUserIds.Add(UserId);
}
return buffer;
}
public void SignOut(User u)
{
LogRepository.Insert(new Log() { Event_type_id = 3, Message = "Пользователь " + u.Login + " вышел из учётной записи." });
Save();
UsedUserIds.Remove(u.Id);
}
public IEnumerable<int> GetUsedUserIds()
{
return UsedUserIds;
}
public void AddObserver(int usedUserId)
{
IObserver callback = OperationContext.Current.GetCallbackChannel<IObserver>();
Update += callback.OnUpdate;
//ICommunicationObject obj = (ICommunicationObject)callback;
//obj.Closed += new EventHandler(Observer_Closed);
// db.Event_types.Add(new Event_type { Name = "Авторизация пользователя" });
UsedUserIds.Add(usedUserId);
ObserversHaveChanged = true;
}
//void Observer_Closed(object sender, EventArgs e)
//{
// Update -= ((IObserver)sender).OnUpdate;
// //db.Event_types.Add(new Event_type { Name = "Выход из учётной записи" });
// ObserversHaveChanged = true;
//}
public void RemoveObserver(int usedUserId)
{
IObserver callback = OperationContext.Current.GetCallbackChannel<IObserver>();
Update -= callback.OnUpdate;
//db.Event_types.Add(new Event_type { Name = "Выход из учётной записи" });
UsedUserIds.Remove(usedUserId);
ObserversHaveChanged = true;
}
public void NotifyObservers()
{
//foreach(IObserver o in Observers)
//{
// o.Update(LogRepository.Get(orderBy: q => q.OrderByDescending(l => l.Id)).Select(l => l.Message).FirstOrDefault(), UsedUserIds);
//}
ObserversHaveChanged = false;
}
}
} |
|
Мой appconfig wcfservice (Я пытаюсь настроить пока что только AuthorizationService (<service name="WCFServiceLibrary.Services.Authori zationService">)):
| XML |
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
| <?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
</configSections>
<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
<add key="ClientSettingsProvider.ServiceUri" value="" />
</appSettings>
<system.web>
<compilation debug="true" />
<membership defaultProvider="ClientAuthenticationMembershipProvider">
<providers>
<add name="ClientAuthenticationMembershipProvider" type="System.Web.ClientServices.Providers.ClientFormsAuthenticationMembershipProvider, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" serviceUri="" />
</providers>
</membership>
<roleManager defaultProvider="ClientRoleProvider" enabled="true">
<providers>
<add name="ClientRoleProvider" type="System.Web.ClientServices.Providers.ClientRoleProvider, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" serviceUri="" cacheTimeout="86400" />
</providers>
</roleManager>
</system.web>
<!-- Во время развертывания проекта библиотеки служб содержимое файла конфигурации необходимо добавить к файлу
app.config на узле. Файлы конфигурации для библиотек не поддерживаются System.Configuration. -->
<system.serviceModel>
<diagnostics performanceCounters="Default" />
<!--<behaviors>
<serviceBehaviors>
<behavior name="ExposeMexAndThrottleBehavior">
<serviceMetadata httpGetEnabled="true" httpGetUrl="http://localhost:8733/mex" />
<serviceThrottling maxConcurrentCalls="3" maxConcurrentInstances="100" maxConcurrentSessions="100" />
</behavior>
</serviceBehaviors>
</behaviors> -->
<services>
<service name="WCFServiceLibrary.Services.AuthorizationService">
<!--behaviorConfiguration="ExposeMexAndThrottleBehavior"-->
<endpoint address="AuthorizationService" binding="netTcpBinding" contract="WCFServiceLibrary.Services.IAuthorizationService">
<identity>
<dns value="localhost" />
</identity>
</endpoint>
<endpoint address="AuthorizationServiceCallback" binding="wsDualHttpBinding" contract="WCFServiceLibrary.Services.IObservable"/>
<endpoint address="mex" binding="netTcpBinding" bindingConfiguration="" contract="IMetadataExchange" />
<endpoint address="http://localhost:8733/mex" binding="mexHttpBinding" contract="IMetadataExchange" />
<host>
<baseAddresses>
<add baseAddress="net.tcp://localhost:8523/AuthorizationService" />
<add baseAddress="http://localhost:8733"/>
</baseAddresses>
</host>
</service>
<service name="WCFServiceLibrary.Services.RegistrationService">
<endpoint address="" binding="netTcpBinding" bindingConfiguration="" contract="WCFServiceLibrary.Services.IRegistrationService">
<identity>
<dns value="localhost" />
</identity>
</endpoint>
<endpoint address="mex" binding="mexTcpBinding" bindingConfiguration="" contract="IMetadataExchange" />
<host>
<baseAddresses>
<add baseAddress="net.tcp://localhost:8523/RegistrationService" />
</baseAddresses>
</host>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="">
<serviceMetadata httpGetEnabled="false" httpsGetEnabled="false" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
<connectionStrings>
<add name="DbUsersContext" connectionString="metadata=res://*/Models.DbUsersModel.csdl|res://*/Models.DbUsersModel.ssdl|res://*/Models.DbUsersModel.msl;provider=System.Data.SqlClient;provider connection string="data source=DESKTOP-3DPP3BL;initial catalog=DbUsers;user id=DbUsersAdmin;password=DbUsersQWERTY;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
</connectionStrings>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="mssqllocaldb" />
</parameters>
</defaultConnectionFactory>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
</configuration> |
|
Если какую-то информацию мне вам нужно уточнить, то я сделаю это.