WCF for windows phone 8.1 silverlight - c#

I'm having problem using wcf with wp8.1 silverlight. I countinously getting the error The contract 'IPhoneService' contains synchronous operations, which are not supported in Silverlight. Split the operations into "Begin" and "End" parts and set the AsyncPattern property on the OperationContractAttribute to 'true'. Note that you do not have to make the same change on the server. After I changed my syncronous method to async I'm still getting the same error (I updated the service reference.). Out of curiousity I tried to use it on a console app, and it works perfectly.
Previously I did get an another error that might have something to do with it. Adding a service reference generated an app.config file, but the app needed a ServiceReferences.ClientConfig, so I simply renamed it.
For now I changed back the WCF method to syncronous:
public int GetData()
{
return 12;
}
and on my MainViewModel (I'm using MVVMLight toolkit):
public void Load()
{
var client = new ServiceReference1.PhoneServiceClient();
client.GetDataCompleted += client_GetDataCompleted;
client.GetDataAsync();
}
void client_GetDataCompleted(object sender, ServiceReference1.GetDataCompletedEventArgs e)
{
Title = e.Result.ToString();
}
and i implemeneted before the async method like this, getting the same error anyway:
public IAsyncResult BeginGetData(AsyncCallback callback, object asyncState)
{
var msg = 12;
return new CompletedAsyncResult<int>(msg);
}
public int EndGetData(IAsyncResult r)
{
CompletedAsyncResult<int> result = r as CompletedAsyncResult<int>;
return result.Data;
}
class CompletedAsyncResult<T> : IAsyncResult
{
T data;
public CompletedAsyncResult(T data)
{ this.data = data; }
public T Data
{ get { return data; } }
#region IAsyncResult Members
public object AsyncState
{ get { return (object)data; } }
public WaitHandle AsyncWaitHandle
{ get { throw new Exception("The method or operation is not implemented."); } }
public bool CompletedSynchronously
{ get { return true; } }
public bool IsCompleted
{ get { return true; } }
#endregion
}

The problem was VS2013 RC2 version. The reference wasn't generated correctly. An update solved the problem

Related

What is the equivalent of Kotlin WebSocketSession object in c#?

For a few months now I have been using the ktor framework to create servers that expose rest calls and communication via webSockets. For now I have always used clients using kotlin as a programming language (or Android App, or App Desktop).
Specifically, I had a class that was injected with the HttpClient object (from the documentation = Asynchronous client to perform HTTP requests).
Within this class I have 4 methods:
start the session: instantiate the WebSocketSession object (Represents a web socket session between two peers)
send Frame
receives Frame
close the session
In Ktor my class is something that looks a lot like this:
class WebSocketServiceImpl(
private val client: HttpClient
){
private var socket: WebSocketSession? = null
//1)
suspend fun initSession(username: String): Resource<Unit>{
socket = client.webSocketSession {
url("ws://xxx.xxx.xxx.xxx:xxxx/myRoute?username=$username")
}
//2)
suspend fun send(myObj: MyObj) {
try {
val myObjSerialized = Json.encodeToString(myObj)
socket?.send(Frame.Text(myObjSerialized ))
} catch (e: Exception) {
e.printStackTrace()
}
}
//3)
fun observePrintableMessages(): Flow<MyObj> {
return try {
socket?.incoming
?.receiveAsFlow()
?.filter { it is Frame.Text }
?.map {
val myObjString = (it as? Frame.Text)?.readText() ?: ""
val printableMessageDto = Json.decodeFromString<MyObj>(myObjString)
} ?: flow { }
} catch (e: Exception) {
e.printStackTrace()
flow { }
}
}
//4)
suspend fun closeSession() {
socket?.close()
}
}
From the C # documentation instead, I found these examples on how to use Client-side WebSockets:
//1)
const exampleSocket = new WebSocket("wss://www.example.com/socketserver", "protocolOne");
//2)
exampleSocket.send("Here's some text that the server is urgently awaiting!");
//3)
exampleSocket.onmessage = (event) => {
console.log(event.data);
}
//4)
exampleSocket.close();
Admitted and not granted that the methods I found in C # really work, to make the WebSocket object used in C # be equivalent to the WebSocketSession object in Kotlin is enough for me to do so? :
public void initSession(string username)
{
exampleSocket = new WebSocket($"wss://www.example.com/socketserver?username={username}", "");
}
Or is it some other type of object to use?
If for any reason you don't know the answer, you don't need to vote negative, you can just move on.
I used the Websocket.Client library (by Mariusz Kotas) found on NuGet
public class WebSocketService : IWebSocketService
{
public event EventHandler<MessageReceivedEventArgs> MessageReceived;
private void FireMessageReceivedEvent(Message message) => MessageReceived?.Invoke(this, new MessageReceivedEventArgs(message));
public string Url { get => "ws://192.168.1.202:8082/chat-socket"; }
private WebsocketClient webSocketClient;
public async Task<SessionResoult> InitSession(string username)
{
string usernameSession = $"?username={username}";
string urlWithUsername = $"{Url}{usernameSession}";
try
{
webSocketClient = new WebsocketClient(new Uri(urlWithUsername));
await webSocketClient.Start();
if (webSocketClient.IsRunning)
{
SubscribeNewMessages();
return new SessionResoult.Success();
}
else
{
return new SessionResoult.Error("webSocketClient is not running");
}
}
catch(Exception ex)
{
return new SessionResoult.Error(ex.Message);
}
}
private void SubscribeNewMessages()
{
webSocketClient.MessageReceived.Subscribe(m =>
{
MessageDto message = JsonConvert.DeserializeObject<MessageDto>(m.Text);
FireMessageReceivedEvent(message.ToMessage());
});
}
public async Task SendMessageAsync(string message)
{
await Task.Run(() => webSocketClient.Send(message));
}
public void CloseSession()
{
webSocketClient.Dispose();
}
}
In the code, the interesting parts are:
1) initialization of the WebsocketClient object
2) the subscription of receiving messages ( Start() method immediately after initialization)
3) observation of message subscription -> webSocketClient.MessageReceived.Subscribe
4) the 'Fire' of the event linked to the observation of messages -> FireMessageReceivedEvent
5) those who use the class must subscribe to the event of the latter ->
webSocketService.MessageReceived + = (sender, e) => {OnMessageReceived (e.MessageReceived); };
MessageReceivedEventArgs -> Class describing the Arguments of the event
SessionResoult -> Class similar to an Enum but with the possibility of passing a string or not based on which subclass it is

SignalR hub not answering to object parameter

I cannot find any resource, that would say I cannot do that.
I have all setup hub/client and tested when parameter is decimal, but once I use generic class, then the server wont react.
SignalRMessage:
public class SignalRMessage<T>
{
public SignalRMessage(T value, string text)
{
Value = value;
Text = text ?? string.Empty;
}
public T Value { get; set; }
public string Text { get; set; }
}
Hub (OnConnected gets a hit):
public class JobHeaderHub : Hub
{
public override Task OnConnectedAsync()
{
Debug.WriteLine(Clients.Caller);
return base.OnConnectedAsync();
}
public async Task JobHeaderUpdated(SignalRMessage<decimal> message)
{
await Clients.Others.SendAsync("ReceiveJobHeaderUpdated", message);
}
public async Task JobHeaderCreated(SignalRMessage<decimal> message)
{
await Clients.Others.SendAsync("ReceiveJobHeaderCreated", message);
}
}
Client:
public class JobHeaderSingalRClient
{
private HubConnection connection;
public JobHeaderSingalRClient()
{
// connection = new HubConnectionBuilder().WithUrl(#"").WithAutomaticReconnect().Build();
connection = new HubConnectionBuilder().WithUrl(#"http://localhost:5000/jobheader").WithAutomaticReconnect().Build();
connection.On<SignalRMessage<decimal>>("ReceiveJobHeaderUpdated", message => JobHeaderUpdated?.Invoke(message));
connection.On<SignalRMessage<decimal>>("ReceiveJobHeaderCreated", message => JobHeaderCreated?.Invoke(message));
}
public static async Task<JobHeaderSingalRClient> CreateConnectedClient()
{
var client = new JobHeaderSingalRClient();
await client.ConnectAsync();
return client;
}
public async Task<JobHeaderSingalRClient> ConnectAsync()
{
await connection.StartAsync();
return this;
}
public event Action<SignalRMessage<decimal>> JobHeaderUpdated;
public async Task SendJobHeaderUpdated(decimal id, string message = null)
{
await connection.SendAsync("JobHeaderUpdated", new SignalRMessage<decimal>(id, message));
}
public event Action<SignalRMessage<decimal>> JobHeaderCreated;
public async Task SendJobHeaderCreated(decimal id, string message = null)
{
await connection.SendAsync("JobHeaderCreated", new SignalRMessage<decimal>(id, message));
}
}
I have no idea why when parameter is SignalRMessage<decimal> then the methods on server are not getting hit. Anyone knows? Thanks.
I had this sort of issues too when I was using constructors with parameters. All of them disappeared after adding a default parameterless constructor.
This is most probably not related to signalR, but to the underlying JSON serialization.
The type has to be specified in order to be able to serialize the objects.
I had similar issues when using objects of type object as parameters.
To troubleshoot turn on verbose error messages in signalR and see if there are any errors logged.
services.AddSignalR(options =>
{
options.Hubs.EnableDetailedErrors = true;
});

Exception thrown: 'System.MissingMethodException'

I'm working in a WinForm app in 4 layers:
DAL (Data access)
BOL (Bussiness objects)
BAL (Bussiness access)
INT (Intermediate access).
I'm using the Intermediate layer to run any operation needed by the Presentation layer, trying to make it independent, as we can use it in a WinForm, ASP, and so.
I've created a Class that executes those operations like this:
// Clase: ProjectStatusMID
using System.Collections.Generic;
namespace Trevo.FrameWork
{
public class ProjectStatusMID
{
#region Propiedades
private ProjectStatusBOL _Data = new ProjectStatusBOL();
private ProjectStatusBAL _Operations = new ProjectStatusBAL();
private Acciones _Action = Acciones.Nada;
#endregion Propiedades
public ProjectStatusBOL Data
{
get { return _Data; }
set
{
_Data = value;
}
}
public ProjectStatusBAL Operations
{
get { return _Operations; }
set
{
_Operations = value;
}
}
public Acciones Action
{
get { return _Action; }
set
{
_Action = value;
}
}
public int IDProject
{
get { return _Data.IDProject; }
set
{
_Data.IDProject = value;
}
}
public List<Codigos> ProjectsList
{
get { return LoadProjects(); }
}
public ProjectStatusMID()
{
//Load();
}
public void Load()
{
Operations.Consultar(Data);
}
public List<Codigos> LoadProjects()
{
List<Codigos> oRet = new List<Codigos>();
MyProjectsBAL _Operations = new MyProjectsBAL();
MyProjectsBOL _Data = new MyProjectsBOL();
List<MyProjectsBOL> _MyList = _Operations.Lista(_Data);
foreach (MyProjectsBOL o in _MyList)
{
oRet.Add(new Codigos(o.IDProject, o.Project));
}
return oRet;
}
}
}
// Clase: ProjectStatusMID
At the front-end (in this case is WinForm), we are instancing this class as follows:
ProjectStatusMID OO = new ProjectStatusMID();
So, the issue comes when calling one of the methods:
parProject.DataSource = OO.LoadProjects();
Everything is referenced, the app compiles without any problems, the project that contains the class is part of the solution in a separated project (as any other layer), BUT we have the following error:
System.MissingMethodException occurred
HResult=-2146233069
Message=Método no encontrado: 'System.Collections.Generic.List`1 Trevo.FrameWork.ProjectStatusMID.LoadProjects()'.
Source=WorkLoadPresentation
StackTrace:
en Trevo.FrameWork.PS_ProjectStatus_Datos.CargarListas()
en Trevo.FrameWork.PS_ProjectStatus_Datos.PS_ProjectStatus_Datos_Load(Object sender, EventArgs e) en C:\Users\fbravo\OneDrive\Particular_Sistemas\WorkLoad\WorkLoadPresentation\ProjectStatus\PS_ProjectStatus_Datos.cs:línea 25
InnerException:
I've tried to make the class static, re-creating the entire app, deleting the GAC, and so, but a week loose trying different things.
Any help will be appreciated
Could be several issues. The most common one is that you included the DLL library which is the wrong version (e.g. without the method that's missing). Easiest thing to do is to open the exe in the decompiler (e.g. Reflector) and step through it.
Another issue could be the wrong bitness (but probably not).
You have to make sure you referenced the external project dll in your main Winforms application

ContextBoundObject with Async/Await

I have a system which uses AOP with ContextBoundObject.
This is used to intercept a method call and perform certain operations before and after the function. It all works fine until I make the 'function to be intercepted' async.
I understand that the C# compiler rewrites async methods into a state machine, which returns control to the sink as soon as 'await' is reached
So it continues into the interception and executes the code which is meant to be executed only after the Method.
I can see there is an "AsyncProcessMessage" in IMessageSink, but I can't find a way to invoke it, and I am not sure if it will work in the async/await scenario.
Is there a way to make Async/Await work with the ContextBoundObject? Is using another Aspect Oriented Programming approach the only option here?
The code sample below has the method to be intercepted decorated with the 'Audit' attribute and placed in the AuditFacade which is a ContextBoundObject. The SyncProcessMessage method in the AuditSink has the logic to be executed before and after the method.
[AuditBoundary]
public class AuditFacade : ContextBoundObject
{
[Audit]
public ResponseObject DoSomthing()
{
//Do something
return new ResponseObject();
}
/// <summary>
/// Async Method to be intercepted
/// </summary>
/// <returns></returns>
[Audit]
public async Task<ResponseObject> DoSomthingAysnc()
{
//Do something Async
await Task.Delay(10000);
return new ResponseObject();
}
}
[AttributeUsage(AttributeTargets.Method)]
public class AuditAttribute : Attribute
{
}
[AttributeUsage(AttributeTargets.Class)]
public class AuditBoundaryAttribute : ContextAttribute
{
public AuditBoundaryAttribute()
: base("AuditBoundary" + Guid.NewGuid().ToString())
{
}
public override void GetPropertiesForNewContext(IConstructionCallMessage ctorMsg)
{
ctorMsg.ContextProperties.Add(new AuditProperty());
}
}
public class AuditProperty : IContextProperty, IContributeObjectSink
{
public string Name
{
get { return "AuditProperty"; }
}
public bool IsNewContextOK(Context newCtx)
{
var p = newCtx.GetProperty("AuditProperty") as AuditProperty;
if (p == null)
return false;
return true;
}
public void Freeze(Context newContext)
{
}
public IMessageSink GetObjectSink(MarshalByRefObject obj, IMessageSink nextSink)
{
return new AuditSink(nextSink);
}
}
public class AuditSink : IMessageSink
{
private IMessageSink nextSink;
public AuditSink(IMessageSink nextSink)
{
this.nextSink = nextSink;
}
public IMessage SyncProcessMessage(IMessage msg)
{
var message = msg as IMethodCallMessage;
IMethodReturnMessage returnMessage = null;
ResponseObject response;
//Some Pre Processing happens here
var newMessage = new MethodCallMessageWrapper(message);
//Invoke the Method to be Audited
returnMessage = nextSink.SyncProcessMessage(newMessage) as IMethodReturnMessage;
response = returnMessage.ReturnValue as ResponseObject;
//Some Post Processing happens here with the "response"
return returnMessage;
}
public IMessageSink NextSink
{
get { return this.nextSink; }
}
public IMessageCtrl AsyncProcessMessage(IMessage msg, IMessageSink replySink)
{
return nextSink.AsyncProcessMessage(msg, replySink);
}
}
I don't know anything about ContextBoundObject, but I think that AsyncProcessMessage() has nothing to do with async-await and that the following should work using the normal SyncProcessMessage():
Do your preprocessing step.
Invoke the async method.
Add your postprocessing step as a continuation to the returned Task, using ContinueWith() or await.
Return the continuation Task to the caller.
If you're okay with your postprocessing executing on the thread pool, then ContinueWith() is probably simpler. If you need the postprocessing to execute on the original context, use await.
The await version could look like this:
var responseTask = (Task<ResponseObject>)returnMessage.ReturnValue;
Func<Task<ResponseObject>> postProcessTaskFunc = async () =>
{
var response = await responseTask;
// Some Post Processing happens here with the "response"
return response;
}
return new ReturnMessage(postProcessTaskFunc(), …);

Calling a WCF method from a WPF client does nothing

I have a very simple WCF service running that has a single method that returns an enum based on the result of the method.
I have tested this WCF service through a very simple console app both locally and over the internet to my server and both work perfectly fine. However once I use the, literally exact, code in my WPF application calling the method does nothing. No exception, no timeout. Testing it locally with a breakpoint at the start of the WCF method I found it does not even reach that far when calling it from WPF.
Both service reference configurations that were generated in the app.config are identical between the console and WPF application.
Edit: Had hoped to not need to put as much code in here but I'll just dump the whole thing.
In WPF the code is being called from a button in a dialog. This button triggers an Coroutine call using Caliburn.Micro. The WCF call is then being called in the Execute method from the Coroutine.
public IEnumerator<IResult> SendReport()
{
var result = new Coroutines.SubmitNewExceptionIssueResult(Exception, UserNotes, Character);
yield return result;
if (result.Result == ErrorReportResult.OK)
TryClose();
else
// TODO
}
public class SubmitNewExceptionIssueResult : IResult
{
public event EventHandler<ResultCompletionEventArgs> Completed;
private ErrorReporterClient _client = new ErrorReporterClient();
private Exception _exception { get; set; }
private string _userNotes { get; set; }
private Character _character { get; set; }
public ErrorReportResult Result { get; private set; }
public SubmitNewExceptionIssueResult(Exception ex, string userNotes, Character character)
{
_exception = ex;
_userNotes = userNotes;
_character = character;
}
public void Execute(ActionExecutionContext context)
{
Result = _client.SendErrorReport(JsonConvert.SerializeObject(_exception, new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.All
}),
_userNotes,
JsonConvert.SerializeObject(_character, new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.All
}));
Completed(this, new ResultCompletionEventArgs());
}
}
The cause was indeed threading of some sort. While not happy with the implementation it now works.
Dispatcher.CurrentDispatcher.Invoke(DispatcherPriority.Normal, new System.Action(() => { /* send report code */ }));

Categories

Resources