I'm wondering if anyone can help me. I have a wcf service running over TCP which will make use of a duplex service. currently this service calls a business object which in turn does some processing. While this processing is happening on a background thread I wish the UI to be updated at certain points. I've attached my code below. TestStatus should be broken up into six parts and the service should update the windows forms UI each time this changes.
The class Scenariocomponent is a singleton (following).
public void BeginProcessingPendingTestCases()
{
ThreadPool.QueueUserWorkItem(new WaitCallback(ProcessPendingTestCases));
}
public void BeginProcessingPendingTestCases()
{
ThreadPool.QueueUserWorkItem(new WaitCallback(ProcessPendingTestCases));
}
private void ProcessPendingTestCases(object state)
{
while (this.IsProcessingScenarios)
{
ProcessNextPendingTestCase();
}
}
private void ProcessNextPendingTestCase()
{
while (this.ServiceStatus == Components.ServiceStatus.Paused)
{
//Wait.
}
var testOperation = this.PendingTestCases.Dequeue();
if (testOperation.OperationStatus == TestStatus.Pending)
{
throw new NotImplementedException(); //TODO : Handle test.
if (testOperation.OperationStatus != TestStatus.Failed)
{
testOperation.OperationStatus = TestStatus.Processed;
}
this.CompletedTestCases.Enqueue(testOperation);
}
}
Initially I was using MSMQ to update the UI as it worked sufficiently however this is no longer acceptable due to client restrictions.
My Service is as follows:
public class TestHarnessService : ITestHarnessService
{
public bool Ping()
{
return true;
}
public bool IsProcessingScenarios()
{
return ScenarioComponent.Instance.IsProcessingScenarios;
}
public void BeginProcessingScenarios(string xmlDocument, Uri webServiceUri)
{
var doc = new XmlDocument();
doc.LoadXml(xmlDocument);
var scenarios = ScenarioComponent.Deserialize(doc);
ScenarioComponent.Instance.EnqueueScenarioCollection(scenarios, webServiceUri);
ScenarioComponent.Instance.BeginProcessingPendingTestCases();
}
public void ValidateScenarioDocument(string xmlDocument)
{
var doc = new XmlDocument();
doc.LoadXml(xmlDocument);
ScenarioComponent.ValidateScenarioSchema(doc);
}
ITestOperationCallBack Callback
{
get
{
return OperationContext.Current.GetCallbackChannel<ITestOperationCallBack>();
}
}
Now I need the UI to update each time a testoperation changes or completes but I am unsure how to accomplish this. Any feedback would be greatly appreciated.
Thank you!
Instead of using WinForms, you could use WPF and binding, which would handle the updating for you.
Related
In experimenting with Service Fabric remoting I have some data types that are not serialized correctly. This is causing me many issues.
From the documentation it appears that everything needs to be decorated with [DataContract]. After using this on some test types it does appear that they serialize correctly.
However I frankly don't want to have to decorate everything. That would be a huge step backwards for me. I would prefer to use custom serialization all the way around.
This documentation seems to suggest that it is possible to register a custom serializer however it appears to only be for stateful services. I am primarily using remoting with stateless services.
The current remoting stack requires that your types use DataContract. Supposedly the team is close to releasing a new remoting stack in the near future that contains the ability to plug in custom serialization and a lot of improvements on the performance side but this is not available yet.
In the meantime, a workaround (not a very nice one mind you) is to make all of your proxies receive string or byte[] or something like that and take care of serialization/deserialization manually using something like JSON.Net. Personally I'd bite the bullet and make your types Data Contract Serializable until the new remoting bits are available.
With the release of Service Fabric V2 Remoting, this is now possible. See here for further details. Below
Here is an implementation of MessagePack remoting serializer I have used, but in your case the JSON example in the docs would probably suffice.
public class MessagePackMessageFactory : IServiceRemotingMessageBodyFactory
{
public IServiceRemotingRequestMessageBody CreateRequest(string interfaceName, string methodName, int numberOfParameters)
{
return new MessagePackRemotingRequestMessageBody(numberOfParameters);
}
public IServiceRemotingResponseMessageBody CreateResponse(string interfaceName, string methodName)
{
return new MessagePackServiceRemotingResponseMessageBody();
}
}
[MessagePackObject]
public class MessagePackRemotingRequestMessageBody : IServiceRemotingRequestMessageBody
{
[Key(0)]
public object Value;
public MessagePackRemotingRequestMessageBody()
{
}
public MessagePackRemotingRequestMessageBody(int parameterInfos)
{
}
public void SetParameter(int position, string paramName, object parameter)
{
Value = parameter;
}
public object GetParameter(int position, string paramName, Type paramType)
{
return Value;
}
}
[MessagePackObject]
public class MessagePackServiceRemotingResponseMessageBody : IServiceRemotingResponseMessageBody
{
[Key(0)]
public object Response;
public object Get(Type paramType)
{
// ignore paramType?
return Response;
}
public void Set(object response)
{
Response = response;
}
}
public class ServiceRemotingResponseMessagePackMessageBodySerializer : IServiceRemotingResponseMessageBodySerializer
{
public OutgoingMessageBody Serialize(IServiceRemotingResponseMessageBody responseMessageBody)
{
if (!(responseMessageBody is MessagePackServiceRemotingResponseMessageBody body))
{
return new OutgoingMessageBody(new[] { new ArraySegment<byte>(new byte[0]) });
}
var bytes = MessagePackSerializer.Serialize(body, ServiceFabricResolver.Instance);
return new OutgoingMessageBody(new[] { new ArraySegment<byte>(bytes) });
}
public IServiceRemotingResponseMessageBody Deserialize(IncomingMessageBody messageBody)
{
using (var stream = messageBody.GetReceivedBuffer())
{
if (stream.Length == 0)
{
return new MessagePackServiceRemotingResponseMessageBody();
}
var body = MessagePackSerializer.Deserialize<MessagePackServiceRemotingResponseMessageBody>(stream, ServiceFabricResolver.Instance);
return body;
}
}
}
public class ServiceRemotingMessagePackSerializationProvider : IServiceRemotingMessageSerializationProvider
{
public IServiceRemotingRequestMessageBodySerializer CreateRequestMessageSerializer(Type serviceInterfaceType,
IEnumerable<Type> requestBodyTypes)
{
return new ServiceRemotingRequestMessagePackMessageBodySerializer();
}
public IServiceRemotingResponseMessageBodySerializer CreateResponseMessageSerializer(Type serviceInterfaceType, IEnumerable<Type> responseBodyTypes)
{
return new ServiceRemotingResponseMessagePackMessageBodySerializer();
}
public IServiceRemotingMessageBodyFactory CreateMessageBodyFactory()
{
return new MessagePackMessageFactory();
}
}
public class ServiceRemotingRequestMessagePackMessageBodySerializer : IServiceRemotingRequestMessageBodySerializer
{
public OutgoingMessageBody Serialize(IServiceRemotingRequestMessageBody serviceRemotingRequestMessageBody)
{
if (serviceRemotingRequestMessageBody == null) return null;
if (!(serviceRemotingRequestMessageBody is MessagePackRemotingRequestMessageBody body))
{
return new OutgoingMessageBody(new[] { new ArraySegment<byte>(new byte[0]) });
}
var bytes = MessagePackSerializer.Serialize(body, ServiceFabricResolver.Instance);
return new OutgoingMessageBody(new[] { new ArraySegment<byte>(bytes) });
}
public IServiceRemotingRequestMessageBody Deserialize(IncomingMessageBody messageBody)
{
using (var stream = messageBody.GetReceivedBuffer())
{
if (stream.Length == 0)
{
return new MessagePackRemotingRequestMessageBody();
}
var body = MessagePackSerializer.Deserialize<MessagePackRemotingRequestMessageBody>(stream, ServiceFabricResolver.Instance);
return body;
}
}
}
I haven't found a clear answer on this. so if there is already a question about this, my bad.
I have a WCF service that pushes data via a callback method to connected clients. this callback method is oneway. so everytime there is new data I loop over the connected users and push the data.
The problem I have right now is when a client disconnects it throws an error and the channel becomes faulted.
I always thought that oneway didn't care if the message arrives at the destination. So if there's no client, then bad luck. but no exception.
but there is an exception and that exception faults the channel.
Now I've read somewhere that if you enable reliable sessions, that the exception won't fault the channel. Is this true?
How can I prevent that the channel goes into faulted state when an exception happens on a oneway call?
The list of registered and avaiable clients you can store in some resource such as List. Create another interface which exposes Connect/Disconnect methods. Connect is invoked when application starts off and within method client is added to the list. Disconnect in turn is invoked when application shuts down in order to get rid client of list. OnStartup/OnClosing events or their equivalents, depending on what kind of application client is, refer to moment when application is launched and closed. Such a solution ensures that resource stores only users avaiable to be reached.
[ServiceContract]
interface IConnection
{
[OperationContract(IsOneWay = true)]
void Connect();
[OperationContract(IsOneWay = true)]
void Disconnect();
}
[ServiceContract]
interface IServiceCallback
{
[OperationContract(IsOneWay = true)]
void CallbackMethod();
}
[ServiceContract(CallbackContract = typeof(IServiceCallback))]
interface IService
{
[OperationContract]
void DoSth();
}
class YourService : IConnection, IService
{
private static readonly List<IServiceCallback> Clients = new List<IServiceCallback>();
public void Connect()
{
var newClient = OperationContext.Current.GetCallbackChannel<IServiceCallback>();
if (Clients.All(client => client != newClient))
Clients.Add(newClient);
}
public void Disconnect()
{
var client = OperationContext.Current.GetCallbackChannel<IServiceCallback>();
if (Clients.Any(cl => cl == client))
Clients.Remove(client);
}
public void DoSth()
{
foreach(var client in Clients)
client.CallbackMethod();
}
}
At the end expose another endpoint with IConnection so that client can create proxy meant to be used only for connection/disconnection.
EDIT:
I know it has been a while since I posted an answear but I did not find in order to prepare an example. The workaround is to let service's interface derive IConnection and then expose only service as an endpoint. I attach simple example of WCF and WPF app as client. Client's application violates MVVM pattern but in this case it is irrelevant. Download it here.
To add on what Maximus said.
I've implemented this pattern in a class where clients can subscribe to get updates of internal states of a system, so a monitoring client can show graphs and other clients do other stuff like enabling/disabling buttons if some state is active.
It removes faulted channels from the list when they fail. Also all current states are sent when a client connects.
here's the code, hope it helps!
[ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Multiple)]
public class Publish : IPublish
{
private struct SystemState
{
public string State;
public string ExtraInfo;
}
private static Dictionary<Key<string>, IPublishCallback> mCallbacks = new Dictionary<Key<string>, IPublishCallback>();
private static Dictionary<string, SystemState> mStates = new Dictionary<string, SystemState>();
public void RegisterClient(string name, string system)
{
lock (mCallbacks)
{
IPublishCallback callback = OperationContext.Current.GetCallbackChannel<IPublishCallback>();
Key<string> key = new Key<string>(name, system);
if (!mCallbacks.ContainsKey(key))
{
mCallbacks.Add(key, callback);
}
else
{
mCallbacks[key] = callback;
}
foreach (KeyValuePair<string, SystemState> s in mStates)
{
mCallbacks[key].ServiceCallback(s.Key, s.Value.State, s.Value.ExtraInfo);
}
}
}
public void UnregisterClient(string name)
{
lock (mCallbacks)
{
outer: foreach (var key in mCallbacks.Keys)
{
if (key.Key1 == name)
{
mCallbacks.Remove(key);
goto outer;
}
}
}
}
public void SetState(string system, string state, string extraInfo)
{
lock (mCallbacks)
{
List<Key<string>> toRemove = new List<Key<string>>();
SystemState s = new SystemState() { State = state, ExtraInfo = extraInfo };
SystemState systemState;
if (!mStates.TryGetValue(system, out systemState))
mStates.Add(system, s);
else
mStates[system] = s;
foreach (KeyValuePair<Key<string>, IPublishCallback> callback in mCallbacks)
{
try
{
callback.Value.ServiceCallback(system, state, extraInfo);
}
catch (CommunicationException ex)
{
toRemove.Add(new Key<string>(callback.Key.Key1, callback.Key.Key2));
}
catch
{
toRemove.Add(new Key<string>(callback.Key.Key1, callback.Key.Key2));
}
}
foreach (Key<string> key in toRemove)
mCallbacks.Remove(key);
}
}
}
I am having one Application based on XamarinForms.
One background service I have created in Android project and that service would like to send data to ContentPage(which is in PCL) which is displayed to user.
How could I pass data to ContentPage(From xx.Droid project to PCL)?
One solution is:
To Create class in PCL with static variable(e.g. var TEMP_VAR), which will be accessed from xxx.Droid project.
Update value of that static variable(TEMP_VAR) from the service class from the xxx.Droid project.
Need to create Notifier on that static variable(TEMP_VAR)
Update the content page using MessageCenter Mechanism if require.
If there is any better solution, could you please provide me?
This can be achieved using the concept of C#
Dependency service
Event
Need to have 4 classes for such an implementation:
Interface in PCL(e.g. CurrentLocationService.cs) with event handlers defined in it.
namespace NAMESPACE
{
public interface CurrentLocationService
{
void start();
event EventHandler<PositionEventArgs> positionChanged;
}
}
Implementation of interface of PCL in xxx.Droid project (e.g. CurrentLocationService_Android.cs) using Dependency service
class CurrentLocationService_Android : CurrentLocationService
{
public static CurrentLocationService_Android mySelf;
public event EventHandler<PositionEventArgs> positionChanged;
public void start()
{
mySelf = this;
Forms.Context.StartService(new Intent(Forms.Context, typeof(MyService)));
}
public void receivedNewPosition(CustomPosition pos)
{
positionChanged(this, new PositionEventArgs(pos));
}
}
ContentPage in PCL - which will have object of implementation of interface.
Object can be obtained by
public CurrentLocationService LocationService
{
get
{
if(currentLocationService == null)
{
currentLocationService = DependencyService.Get<CurrentLocationService>();
currentLocationService.positionChanged += OnPositionChange;
}
return currentLocationService;
}
}
private void OnPositionChange(object sender, PositionEventArgs e)
{
Debug.WriteLine("Got the update in ContentPage from service ");
}
Background service in xxx.Droid project. This service will have reference of implementation of dependency service CurrentLocationService.cs
[Service]
public class MyService : Service
{
public string TAG = "MyService";
public override IBinder OnBind(Intent intent)
{
throw new NotImplementedException();
}
public override StartCommandResult OnStartCommand(Android.Content.Intent intent, StartCommandFlags flags, int startId)
{
Log.Debug(TAG, TAG + " started");
doWork();
return StartCommandResult.Sticky;
}
public void doWork()
{
var t = new Thread(
() =>
{
Log.Debug(TAG, "Doing work");
Thread.Sleep(10000);
Log.Debug(TAG, "Work completed");
if(CurrentLocationService_Android.mySelf != null)
{
CustomPosition pos = new CustomPosition();
pos.update = "Finally value is updated";
CurrentLocationService_Android.mySelf.receivedNewPosition(pos);
}
StopSelf();
});
t.Start();
}
}
Note : PositionEventArgs class need to be created as per usage to pass on data between service and ContentPage.
This works for me like charm.
Hope so this would be helpful to you.
I'm having newbie problems testing an async method. I've read a few other posts, including How to correct write test with async methods?, and I think I'm doing things correctly, but I'm clearly missing something.
Here's the code I'm trying to test:
/// <summary>
/// Temporary method used to simulate the time required to generate a report.
/// </summary>
public virtual async Task GenerateTestReportAsync()
{
++ActiveTaskCounter;
await Task.Delay(2000);
--ActiveTaskCounter;
}
And here's the test (yes, I could/should improve it by storing the ActiveTaskCounter values in a list, but that's beside the point):
[TestMethod]
public async Task GenerateTestReportAsyncUpdatesActiveTaskCounter()
var bayViewModel = CreateBayViewModel();
var invocationCount = 0;
bayViewModel.PropertyChanged += (sender, args) =>
{
if (args.PropertyName == "ActiveTaskCounter")
{
++invocationCount;
}
};
await bayViewModel.GenerateTestReportAsync();
//Thread.Sleep(2100); // TODO: Why is this needed?
Assert.AreEqual(2, invocationCount);
Assert.AreEqual(0, bayViewModel.ActiveTaskCounter);
}
The test always passes with the Thread.Sleep uncommented. It always fails with the Thread.Sleep commented, as shown above. Why is this? I assumed the code below the "await bayViewModel.GenerateTestReportAsync()" wouldn't even execute until GenerateTestReportAsync was really finished.
BTW, I'm using:
Microsoft Visual Studio Ultimate 2012
Version 11.0.51106.01 Update 1
Microsoft .NET Framework
Version 4.5.50709
Thanks for any help you can provide! This has me stumped :-|
EDIT: Here's a minimal repro of the view model class...
using System.ComponentModel;
using System.Threading.Tasks;
public class BayViewModel : INotifyPropertyChanged
{
public BayViewModel()
{
PropertyChanged = (sender, args) => { };
}
public event PropertyChangedEventHandler PropertyChanged;
private int _activeTaskCounter;
public int ActiveTaskCounter
{
get
{
return _activeTaskCounter;
}
set
{
_activeTaskCounter = value;
PropertyChanged(this, new PropertyChangedEventArgs("ActiveTaskCounter"));
}
}
public virtual async Task GenerateTestReportAsync()
{
++ActiveTaskCounter;
await Task.Delay(2000);
--ActiveTaskCounter;
}
}
I have written an Sdk that is used by a WPF client, and takes care of calling WCF services and caching. These WCF services are called using the ChannelFactory, so I don't have service references. To do that, I created a factory that handles opening and closing ChannelFactory and ClientChannel as follows:
public class ProjectStudioServiceFactory : IDisposable
{
private IProjectStudioService _projectStudioService;
private static ChannelFactory<IProjectStudioService> _channelFactory;
public IProjectStudioService Instance
{
get
{
if (_channelFactory==null) _channelFactory = new ChannelFactory<IProjectStudioService>("ProjectStudioServiceEndPoint");
_projectStudioService = _channelFactory.CreateChannel();
((IClientChannel)_projectStudioService).Open();
return _projectStudioService;
}
}
public void Dispose()
{
((IClientChannel)_projectStudioService).Close();
_channelFactory.Close();
}
}
And each request I call like:
using (var projectStudioService = new ProjectStudioServiceFactory())
{
return projectStudioService.Instance.FindAllCities(new FindAllCitiesRequest()).Cities;
}
Although this works, it's slow because for every request the client channel and factory is opened and closed. If I keep it open, it's very fast. But I was wondering what the best practise would be? Should I keep it open? Or not? How to handle this in a correct way?
Thanks Daniel, didn't see that post. So I guess that the following may be a good approach:
public class ProjectStudioServiceFactory : IDisposable
{
private static IProjectStudioService _projectStudioService;
private static ChannelFactory<IProjectStudioService> _channelFactory;
public IProjectStudioService Instance
{
get
{
if (_projectStudioService == null)
{
_channelFactory = new ChannelFactory<IProjectStudioService>("ProjectStudioServiceEndPoint");
_projectStudioService = _channelFactory.CreateChannel();
((IClientChannel)_projectStudioService).Open();
}
return _projectStudioService;
}
}
public void Dispose()
{
//((IClientChannel)_projectStudioService).Close();
//_channelFactory.Close();
}
}