WCF client goes to faulted immediately - wcf-client

I have the following code for recreating a WCf client in a non opened state
if (client.State != CommunicationState.Opened)
{
client.Abort();
client = null;
Trace.WriteLine("Client object in non opened state. Recreating object");
client = new <WCFClient>("NetTcpBindingEndpoint", ConfigurationManager.AppSettings["ServiceEndPointAddress"]);
client.Open();
}
For some reason though, as soon as this routine returns and I try to call client.Somemethod(), I get an exception and when I catch it, I see the client in a faulted state. I don't understand how this happened so quickly.
Thanks for any help in advance.
Subbu

Can you show us when you're trying to call client.SomeMethod() ?
I don't see what you're trying to achieve with the client.Open() here..... that really doesn't make any sense at all - just call the method you want to call!
try
{
var client = new <WCFClient>("NetTcpBindingEndpoint", ConfigurationManager.AppSettings["ServiceEndPointAddress"]);
client.SomeMethod();
client.Close();
}
catch(FaultException<T> exc)
{
// handle it
client.Abort();
}
catch(CommunicationException exc)
{
// handle it
client.Abort();
}
catch(EndpointNotFoundException exc)
{
// handle it
client.Abort();
}
catch(TimeoutException exc)
{
// handle it
client.Abort();
}
and maybe add some try.....catch magic around it to make it safer.... but that's really all you need - no need to first .Open() the client.....

Related

Track non-HTTP requests with Application Insights

As mentioned in this link, on .net core2.1 web.api application implemented the below code to track non-HTTP requests(i.e, redis calls) using Application Insights
private ReviewModel<T> GetCachedData<T>(string id)
{
try
{
var obj = default(RedisValue);
_retryPolicy.Execute(() =>
{
using (var getReviewsOperation = _telemetryClient.StartOperation<DependencyTelemetry>("RedisCall"))
{
obj = _database.StringGet(id); // external call to redis server
}
});
var review = string.IsNullOrEmpty(obj) || !obj.HasValue ?
default(ReviewModel<T>) : _serializer.Deserialize<ReviewModel<T>>(obj );
return review;
}
catch (Exception ex)
when (ex is RedisException)
{
//how to log the exception cases in dependency table of application insights log?
_log.LogError($"Redis exception occurred : ", {ex.Message});
return null;
}
}
The above code successfully log the redis call details on "dependency" table of application insights log. But how to log redis call details on "dependency" table of application insights log on exception scenarios with success property value as "false"?
You can use TrackDependency for this. TrackDependency is used to track the response times and success rates of calls to an external piece of code. The results appear in the dependency charts in the portal. The code snippet below needs to be added wherever a dependency call is made:
var success = false;
var startTime = DateTime.UtcNow;
var timer = System.Diagnostics.Stopwatch.StartNew();
try
{
success = dependency.Call();
}
catch(Exception ex)
{
success = false;
telemetry.TrackException(ex);
throw new Exception("Operation went wrong", ex);
}
finally
{
timer.Stop();
telemetry.TrackDependency("DependencyType", "myDependency", "myCall", startTime, timer.Elapsed, success);
}

restrict concurrent request + node.js

I have an api exposed using node.js. I have to restrict the API call only once at a time. I tried the following approach.
app.js
globals.consumed = false;
routes.js
app.get("/route1", checkForAlreadyConsumed,controller.method);
controller.method
globals.consumed = true;
//Business logic goes here
//After all the stuff is done
globals.consumed = false;
checkForAlreadyConsumed
checkForAlreadyConsumed() {
if(consumed == false) {
next();
} else {
retrun res.send(403);
}
}
So by above logic i am try to make nobody should consume that API if its already doing its process. But by the above approach if i do 2 concurrent calls , the second call is waiting for the first call to finish so the 403 code is sent as response to frotend. Plz share your ideas.

Angular 5 will not run more than one method on ngOnInit?

I have attached a screenshot of what I am trying to do. This is so basic yet so frustrating. I have to run a data parse after retrieving the array of objects from the first method being called but I can't add my method to the one inside ngOnInit or directly after it inside ngOnInit. Either way the method just simply doesn't run. Any ideas?
Image
ngOnInit() {
this.getSiteContent(this.route.snapshot.params['id']);
//Doesnt work
this.addUpdatedPages();
}
//in use
getSiteContent(id) {
this.http.get('/site-content/'+id).subscribe(data => {
this.siteContent = data;
});
//Doesn't show..
console.log('End of getSiteContent');
}
addUpdatedPages(){
//Doesn't show
console.log('Adding pages...');
for (var i = 0; i < this.siteContent.length; i++) {
this.checkNull(this.siteContent[i].SiteID, this.siteContent[i].SitePageID);
console.log(this.nullCheck[0].SiteID);
if (this.nullCheck.length > 0) {
this.siteContent[i].SitePageContent = this.nullCheck[0].SitePageContent;
}
}
}
Everything points to an unhandled exception when you call this.http.get. You should check your browsers console, that would show it if there was one. One likely reason is that http was not injected or is undefined.
ngOnInit() {
this.getSiteContent(this.route.snapshot.params['id']);
// if the above throws an exception anything below would not be called
this.addUpdatedPages();
}
getSiteContent(id) {
this.http.get('/site-content/'+id).subscribe(data => {
this.siteContent = data;
});
// If the call above to this.http.get throws an exception the code below would not be called
console.log('End of getSiteContent');
}
That being said the method addUpdatedPages should be called in the subscribe of the http.get because you want it to occur after the data base been retrieved. Modify the getSiteContent so that the line is moved into the callback for the observable's subscribe call.
this.http.get('/site-content/'+id).subscribe(data => {
this.siteContent = data;
this.addUpdatedPages();
});

Azure DocumentDB stored procedure exception not being caught

I have this in my DocumentDB stored proc:
function mySproc(doc) {
let context = getContext();
let collection = context.getCollection();
let collectionLink = collection.getSelfLink();
try {
if (!collection.createDocument(collectionLink, doc, handler))
return;
numCreated++;
} catch (e) {
// Never happens.
}
}
Unfortunately, if I intentionally throw within the handler callback, it doesn't get caught in the catch block. It ends up halting the entire stored proc execution. Is that expected--does the callback have its own scope of some sort?
In an async environment like JavaScript, you generally pass any of your error control back to the callback (aka handler in your terminology) via the first parameter. If you throw within your handler, it will completely terminate and return the error package to the client. It never sees your catch block.
If you want more help please show your handler.

Handle NodeJS error event?

I have a worker class that has lots of different utility methods, and emits error messages when there's a problem anywhere in the execution. Due to NodeJS magic, error messages are special, and if nothing is listening to them, they're turned into thrown Errors, so I currently do:
var myWorkerFunction = function(input) {
var w = myFactory();
try {
w.dothis();
w.dothat(input);
w.hokeypokey();
return w.finalize();
} catch(e) {
return false;
}
}
What I wonder though, is it possible to avoid the try/catch block entirely? NodeJS's documentation seems to indicate it's best to avoid not re-throwing a caught exception (I'm doing no checks here to see that it really was my worker's logic that threw the exception and not a critical fault from Node).
So I'd like to do something like:
var myWorkerFunction = function(input) {
var w = myFactory();
w.on('error', function() {
// How to tell caller of myWorkerFunction() I failed,
// and stop the rest of the myWorkerFunction function? (return false)
});
w.dothis();
w.dothat(input);
w.hokeypokey();
return w.finalize();
}
But how to trigger that "return" for myWorkerFunction inside that event listener function? I could have myWorkerFunction emit an "error" message too, but that just kicks the can to the next layer, and doesn't stop the execution of the worker script (i.e. if dothis() fails, don't keep going and call dothat(input)). Is there a programming pattern for situations like this?
EDIT: The one solution I could come up with is something like:
var myWorkerFunction = function(input) {
var w = myFactory();
var hasFailed = false;
w.on('error', function() {
hasFailed = true;
});
w.dothis();
if (hasFailed) return fa;se
w.dothat(input);
if (hasFailed) return false;
w.hokeypokey();
if (hasFailed) return false;
var out = w.finalize();
if (hasFailed) return false;
return out;
}
Which is not very elegant having to constantly check if we've failed or not before every line of code.
A couple thoughts on this. First you might want to take a look at Caolan McMahon's fine async nodejs library because it feels like you're reinventing flow control that would be handled quite well with 'async.waterfall'.
If you don't feel it's a good fit you - following the pattern you've adopted you could opt to post events on completion of each step (see the 'done' events in the sample below). This would allow you to listen for those events as indication that no error has occurred and that it makes sense to move onto the next step. Let 'finalize' take an optional error to allow your worker to differentiate normal vs abnormal completion. This is not tested but here's what something like that might look like:
var myWorkerFunction = function(input) {
var w = myFactory();
w.on('error', function(error) {
// Handle error, log whatever - and finalize with an error?
w.finalize(error);
});
w.on('doneWithThis', function() {
w.dothat(input);
});
w.on('doneWithThat', function() {
w.hokeypokey();
});
w.on('doneWithHokeypokey', function() {
w.finalize();
});
w.dothis(); //starts the ball rolling.
}

Resources