У меня клиентское (WPF) -серверное приложение.
У меня есть список элементов, получаемых из веб-API и обновляющих элементы из клиентского приложения с помощьюpost post.
Сервисный код:
public class ValuesController : ApiController
{
public List<Employee> Employees = new List<Employee> { new Employee { EmpId=1,EmpName="ABC",Desn="TL"},
new Employee { EmpId=2,EmpName="XYZ",Desn="TL"},new Employee { EmpId=3,EmpName="PQR",Desn="TL"}};
public ValuesController()
{
}
// GET api/values
public IEnumerable<Employee> Get()
{
return Employees;
}
// POST api/values
public void Post([FromBody]Employee value)
{
Employees.Add(value);
NotificationHub.SetEmployees(Employees);
}
}
Реализация SignalR Server Hub:
public class NotificationHub : Microsoft.AspNet.SignalR.Hub
{
private static IEnumerable<Employee> _employees;
public IEnumerable<Employee> GetEmployees()
{
return _employees;
}
public static void SetEmployees(IEnumerable<Employee> employees)
{
_employees = employees;
}
}
Модель представления клиентского приложения:
namespace Presentation
{
public class TestViewModel : INotifyPropertyChanged
{
private List<Employee> employees = new List<Employee>();
private int _empid;
private string _empName;
private string _desn;
private HttpClient client;
private HubConnection hubConnection;
public ICommand Command { get; set; }
public List<Employee> Employees
{
get
{
return employees;
}
set
{
employees = value;
RaisePropertyChanged();
}
}
public int EmpId
{
get
{
return _empid;
}
set
{
_empid = value;
RaisePropertyChanged();
}
}
public string EmpName
{
get
{
return _empName;
}
set
{
_empName = value;
RaisePropertyChanged();
}
}
public string Desn
{
get
{
return _desn;
}
set
{
_desn = value;
RaisePropertyChanged();
}
}
public TestViewModel()
{
hubConnection = new HubConnection("https://localhost:44394/");
Command = new RelayCommand(p => true, p => this.ButtonClick());
client = new HttpClient();
client.BaseAddress = new Uri("https://localhost:44394/");
//client.DefaultRequestHeaders.Add("appkey", "myapp_key");
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = client.GetAsync("api/values").Result;
if (response.IsSuccessStatusCode)
{
Employees = response.Content.ReadAsAsync<IEnumerable<Employee>>().Result.ToList();
}
else
{
MessageBox.Show("Error Code" + response.StatusCode + " : Message - " + response.ReasonPhrase);
}
}
public async void ButtonClick()
{
Employee employee = new Employee { Desn = this.Desn, EmpId = this.EmpId, EmpName = this.EmpName };
// Initialization.
var response = await client.PostAsJsonAsync<Employee>("api/values/", employee).ConfigureAwait(true);
// Verification
if (response.IsSuccessStatusCode)
{
// Reading Response.
string result = response.Content.ReadAsStringAsync().Result;
var outResult = JsonConvert.DeserializeObject<List<Employee>>(result);
// Releasing.
response.Dispose();
IHubProxy notificationHubProxy = hubConnection.CreateHubProxy("notificationHub");
await hubConnection.Start();
Employees = notificationHubProxy.Invoke<IEnumerable<Employee>>("GetEmployees").Result.ToList();
hubConnection.Stop();
}
else
{
// Reading Response.
string result = response.Content.ReadAsStringAsync().Result;
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void RaisePropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
public class RelayCommand : ICommand
{
private Predicate<object> _canExecute;
private Action<object> _execute;
public RelayCommand(Predicate<object> canExecute, Action<object> execute)
{
this._canExecute = canExecute;
this._execute = execute;
}
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
public bool CanExecute(object parameter)
{
return _canExecute(parameter);
}
public void Execute(object parameter)
{
_execute(parameter);
}
}
}
Учтите, что у меня есть два клиента, при этом добавление значения сотрудника в клиенте 1 с помощью нажатия кнопки, и то же самое должно быть отражено в клиенте 2 в режиме реального времени и наоборот. Я использовал концентраторы сигналов, но он не работает должным образом.
Пожалуйста, предоставьте мне решение для достижения этой цели.