I want to throw exception from server to client over the network like this.... this is server cod sending exception
InvalidOperationException ex = new InvalidOperationException("Duplicate Key Found");
streamWriter.WriteLine(ex);
and in client side :
object serverResponse = streamReader.ReadLine();
i read object like this from server but whenever i display its type it say serverResponse is of Type System.String rather than InvalidOperationException please help me in this.
Console.WriteLine("Type Is:" + serverResponse.GetType());
Related
I've set up Signalr on my MVC 5 website, and most of it is working fine. For example, if I try and send a test message using Javascript like so it works great:
$.connection.hub.start().done(function () {
chat.server.send("Username", "This is a test message");
});
And my C# send method in the Hub sends the message like so:
public void Send(string username, string message)
{
string name = Context.User.Identity.Name;
Clients.Group(username).getMessages("From: " + name + " - " + message);
}
The problem arises when i try to call the Send method via C#, like this:
ChatHub ch = new ChatHub();
ch.Send("Username", "This is a test message");
When it hits the method during debugging, the Context object is null and it fails.
Essentially, a user sends a message in the View, it hits a controller method, this method calls a notification method in a separate helper class, and this separate class calls the Send method of my Signalr Hub.
Would I need to get the context in the controller, and pass it to the helper class, and then to the Hub? Or is there a better, alternative approach?
Thanks.
UPDATE
I did manage to get the username using:
string name = System.Web.HttpContext.Current.User.Identity.Name;
However, even if I do this, it now throws an exception when it hits this line:
Clients.Group(username).getMessages("From: " + name + " - " + message);
So i think there's a context issue when calling Send from C# only (not from Javascript)
So it turns out from reading this: https://stackoverflow.com/a/36988086/4181058
"If you want to send messages to clients from your own code that runs outside the Hub class, you can't do it by instantiating a Hub class instance, but you can do it by getting a reference to the SignalR context object for your Hub class."
So my solution instead of this:
ChatHub ch = new ChatHub();
ch.Send("Username", "This is a test message");
Was this:
var context = GlobalHost.ConnectionManager.GetHubContext<ChatHub>();
context.Clients.Group(username).getMessages("From: " + name + " - " + message);
I am getting this following error:
exception calling "UploadString" with "2" argument(s): "The remote server returned an error: (500)
Internal Server Error." At C:\Cinegy_Type\Helpers-Type.ps1:146 char:5 + $web.UploadString($url,
$xmlDoc.OuterXml) + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [],
MethodInvocationException + FullyQualifiedErrorId : WebException
The method is this:
function Type-UpdateVariable([string]$name, [string]$value, [string]$type = "Text", [string]$server="localhost", [int]$instance=0)
{
#make a Type PostRequest XML document using .Net XML document object
$xmlDoc = New-Object System.Xml.XmlDocument;
#add root element for request - which is a 'PostRequest' element
$xmlRootElem = $xmlDoc.AppendChild($xmlDoc.CreateElement('PostRequest'));
#create SetValue element and define variable Name, Type and Value
$xmlSetValueElem = $xmlRootElem.AppendChild($xmlDoc.CreateElement('SetValue'));
$xmlSetValueElem.SetAttribute("Name", $name);
$xmlSetValueElem.SetAttribute("Type",$type);
$xmlSetValueElem.SetAttribute("Value", $value);
#create a .Net webclient which will be used to perform the HTTP POST
$web = new-object net.webclient
#Air requires that the data is in XML format and declared properly - so add the HTTP Header to state this
$web.Headers.add("Content-Type", "text/xml; charset=utf-8")
#perform the actual HTTP post to the IP and port (which is 5521 + instance number) of the XML data
$url = "http://" + $server + ":" + (5521 + $instance) + "/postbox"
$web.UploadString($url, $xmlDoc.OuterXml)
}
Line 146 is:
$web.UploadString($url, $xmlDoc.OuterXml)
what I do not understand is that this was working yesterday.
The full code can be found here: (Do not use line number here for reference, this has 3 scripts.)
https://pastebin.com/RtisgmiB
The web server you're posting to is having a problem; see meaning of a HTTP status code 500. Unless the data passed to your function are problematic, your code looks fine. There is nothing you're missing in that Powershell error message, which would give you a clue as to the issue.
Check the error log on the web server (best option)
Output the parameters to the console with the purpose of submitting the request manually through Postman, cURL, etc.
Good luck!
I am writing client in Vertx for sending get request with two string parameters but i am receiving empty list from server. If i write request to another service which is on the same path but this service is not receiving any parameters the response is ok and the data is properly returned. The problem is with mapping the parameter on server side with .addQueryParam the parameter is not mapped well on server side. any help?
WebClient client = WebClient.create(vertx);
client
.get(80, "localhost", "/mainpath/path1")
.addQueryParam("startDate", "1459926000")
.addQueryParam("endDate", "1459926900")
.send(ar -> {
if (ar.succeeded()) {
HttpResponse<Buffer> response = ar.result();
JsonArray body = response.bodyAsJsonArray();
System.out.println("Received response with status code " + response.statusCode() + " with body " + body.toString());
} else {
System.out.println("Something went wrong " + ar.cause().getMessage());
}
});
}
I have an Azure Function that I have configured that listens for incoming messages to an Azure Service Bus. I can receive the messages without a problem. But when I try to route the request onto another service for processing, I am getting an error stating that the POST data is empty.
public static void Run(BrokeredMessage message, TraceWriter log)
{
log.Info($"C# ServiceBus queue trigger function processed message: {message.MessageId}");
if (message != null)
{
//MessageObjectEntity is a custom object
Common.Entities.MessageObjectEntity messageObject = message?.GetBody<Common.Entities.MessageObjectEntity>();
string msgType = messageObject?.MessageType;
var msgContent = messageObject?.MessageContent; // MessageContent is of type object to allow any object to be sent
using (var client = new HttpClient())
{
string url = $"http://mycompany.azurewebsites.net/api/routingtasks?formname={msgType}";
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(subscriber, token);
HttpContent content = new StringContent((string)msgContent, Encoding.UTF8, "application/json");
var response = client.PostAsync(new Uri(url), content); // at this point content is valid
// I am getting a BadRequest returned here as the target service has not received the POST data
// that was sent in via the content variable
}
log.Info("Completing message.");
}
It appears that the POST data sent in the variable content is not received despite it being sent.
UPDATE
When I inspect the JSON sent to my Azure Function in the logger it looks like this.
{"FormName":"UpdateMileage","FormData":[{"Key":"enteredmileage","Value":100},{"Key":"todaysdate","Value":"01/01/2017"}],"Profile":{"EmailAddress":"unittest#mycompany.co.uk","ID":9999999}}
Which doesn't work.
But if I hard code the following JSON from my Azure Function it works correctly (the double quotes are needed to escape the back-slashes).
"\"{\\\"FormName\\\":\\\"UpdateMileage\\\","\\\"FormData\\\":"[{\\\"Key\\\":\\\"enteredmileage\\\",\\\"Value\\\":100},"{\\\"Key\\\":\\\"todaysdate\\\",\\\"Value\\\":\\\"01/01/2017\\\"}],"\\\"Profile\\\":"{\\\"EmailAddress\\\":\\\"unittest#mycompany.co.uk\\\","\\\"ID\\\":9999999}}\""
The problem therefore appears to be the formatting of the JSON that is being sent from my Azure Function, but I don't how I would convert my JSON into this format.
The problem was caused by the fact that I was sending JSON to my ASP.NET Web API service, but sending it as a string type. This is wrong.
The following article explains the correct approach when sending JSON data as a POST request.
I'm trying to understand what's reasonable for integrating these technologies. How would I go about integrating NodeJS (currently using amqplib, but that could be changed) across RabbitMQ to EasyNetQ?
I have it sort of working, except EasyNetQ is expecting an object (I think) and Node/amqplib can only send strings.
C# code:
Bus.Subscribe<BusManifestHolla>(HollaID,
msg => {
Console.WriteLine("Received Manifest Holla ID {0}", msg.ManifestID.ToString());
Console.WriteLine("Responding with Manifest Yo ID {0}", YoID_1);
Bus.Publish(new BusManifestYo { ManifestID = msg.ManifestID, ServiceName = YoID_1 });
}
);
NodeJS code:
var b = new Buffer(JSON.stringify(new dto.BusManifestHolla(uuid.v4())));
ch.publish(Play.exchangeName, '#', b);
The result:
DEBUG: HandleBasicDeliver on consumer: a60b7760-e22f-4685-9f65-039bef19f58c, deliveryTag: 1
DEBUG: Recieved
RoutingKey: '#'
CorrelationId: ''
ConsumerTag: 'a60b7760-e22f-4685-9f65-039bef19f58c'
DeliveryTag: 1
Redelivered: False
ERROR: Exception thrown by subscription callback.
Exchange: 'RabbitMon.BusManifestHolla:RabbitMon'
Routing Key: '#'
Redelivered: 'False'
Message:
{"Guid":"a6cf174d-9b77-4558-bbda-efe9d8451dff"}
BasicProperties:
ContentType=NULL, ContentEncoding=NULL, Headers=[], DeliveryMode=0, Priority=0, CorrelationId=NULL, ReplyTo=NULL, Expiration=NULL, MessageId=NULL, Timestamp=0, Type=NULL, UserId=NULL, AppId=NULL, ClusterId=
Exception:
System.NullReferenceException: Object reference not set to an instance of an object.
at EasyNetQ.TypeNameSerializer.DeSerialize(String typeName)
at EasyNetQ.RabbitAdvancedBus.<>c__DisplayClass16.<Consume>b__15(Byte[] body, MessageProperties properties, MessageReceivedInfo messageRecievedInfo)
at EasyNetQ.Consumer.HandlerRunner.InvokeUserMessageHandler(ConsumerExecutionContext context)
Is there not a way to send an object across the bus? How do you integrate these two?
It's failing on the TypeNameSerializer.DeSerialize call. In your node code you'll need to populate BasicProperties.Type with the type that EasyNetQ should expect at the other end. This needs to be a fully qualified name including the assembly name. Just look at the name that EasyNetQ has given to your BusManifestHolla queue minus the HollaID value (and underscore).
Admittedly that error message isn't very helpful. It probably could be improved.