File.ReadAllText with a lambda-based retry wrapper on Try Catch - c#

Trying to find the most elegant solution for a situation when I get a "IOException: Sharing violation" on loading a JSON file because it is being saved at the same time by another application.
Using a "try Catch' with some form of recursion when loading, though inelegant, makes sense.
So after searching came across this C# solution which gets a lot of up votes
Cleanest way to write retry logic?
The actual function call where my load occurs is
private static T LoadData<T>(string filePath)
{
return JsonUtility.FromJson<T>(File.ReadAllText(filePath));
}
However not sure how to implement using the above linked solution (Retry.Do) which doesn't seem to allow passed arguments in the function call ie
Retry.Do(SomeFunctionThatCanFail, TimeSpan.FromSeconds(1));
Can anyone help?

You need to create a closure.
The simplest way is to use a lambda expression:
YourType data = Retry.Do(() => LoadData<YourType>("somefilepath"), TimeSpan.FromSeconds(1));

Related

Push new values after creation

Reading IntroToRx website, it discourages using of Subject in favour of Observable.Create helper method.
As I can see, the OnNext method can be called only into subscribe method, because it's the only part I have access Observer object.
What if I would like to push new values after it's creation?
Am I "forced" to use a Subject?
If you are just exploring Rx, go for it - use Subjects, go nuts, see how they work, discover their pros and cons for yourself, then come back here and read the questions discussing why Subject is frowned upon.
Subjects offer a much easier way of "quickly bootstrapping" ideas and complicated Rx scenarios without needing to replicate the actual source conditions.
That said, they do inject state into what is kinda-sorta-supposed-to-be a stateless chain of operations, so be careful not to rely on them.
So, to sum up: if you are trying to generate sequences to test/learn how rx works or how you might make query X, use those subjects. If you find yourself using them intra-query, there is a CHANCE there is a better way.
Edit: realized I missed something:
Also, you ask if there is another way of raising stream events post-creation...the answer is yes; you might declare a stream via Create or Return or Generate that returns any old IObservable-based object that you define, which can also expose methods to inject events...or heck, have a lambda that spins a thread that checks a shared list that is routed to the return stream....I guess what I'm saying is that the possibilities are endless. There are something like a dozen "create a sequence of events" methods declared on Observable - try them all!
EDIT 2:
An example? Sure, let's throw something together using Observable.Create that mimics a really inefficient Subject:
var running = true;
var values = new ConcurrentQueue<int>();
var query = Observable.Create<int>(obs =>
{
var body = Task.Factory.StartNew(()=>
{
while(running)
{
int nextValue;
if(values.TryDequeue(out nextValue))
{
obs.OnNext(nextValue);
}
Thread.Yield();
}
});
return Disposable.Create(() =>
{
try
{
running = false;
body.Wait();
obs.OnCompleted();
}
catch(Exception ex)
{
obs.OnError(ex);
}
});
});
using(query.Subscribe(Console.WriteLine))
{
values.Enqueue(1);
values.Enqueue(2);
values.Enqueue(3);
values.Enqueue(4);
Console.ReadLine();
}
Note that this is just quick-and-extremely-dirty example code. :)
It depends on what you are trying to do. There are cases for Subjects, but just not as many as one thinks when they first start out with Rx.
How will the new data enter your sequence? Will it be from another event? Perhaps a message from a communications framework? Maybe polling a file?
Depending on these answers you will normally find that you already have some sort of event source, and you are just converting to Rx from another pattern (Events, Polling, Callbacks etc...)
You also don't just have to use Observable.Create. You could use Observable.Timer/Interval to set up a polling sequence, Observable.FromEventPattern to leverage an existing Event, Observable.Start for a one off async task style calculation etc...
As Rx (or even Linq) can be quite abstract, asking abstract questions can often lead to very broad answers. If you give an indication of a problem you are trying to solve, that might help provide you with an even better answer.
If you are receiving data from external device, you have no intention of signaling errors with IObserver.OnError (you assume your stream is endless and/or any problems with communications are within message itself), you poll at some rate, the only problem with Subject is that you will probably start polling this device even before anyone subscribes (but added benefit is that handling your state is pretty obvious, you created one object, it opened COM port, it communicates and publishes values)
Using Observable.Create or Observable.Timer/Interval might be better - but laziness is main reason, you will manage state anyway. And you will probably need to use Publish().RefCount() to prevent second subscription from opening port.

Multiple calls wait on the same async task

Basically I have a lot of places in my app where in order to do something I need to make sure a product image is downloaded. I want to centralize this call into one place so I make sure to only download it once. I'm trying to do like this in my class:
private IAsyncOperation<bool> _downloadCoverTask;
internal IAsyncOperation<bool> DownloadCoverAsync()
{
if (this._downloadCoverTask == null)
{
this._downloadCoverTask = this._cloudProduct.Image.DownloadAsync();
}
return this._downloadCoverTask;
}
_cloudProduct.Image.DownloadAsync() is a method which actually does the image downloading (it also happens to be in a library that I don't control).
So in my code where I need to download the image, I do
await product.DownloadCoverAsync();
// do stuff with the image
This works ok the first time I call it, but the second time it's called I get the exception "A delegate was assigned when not allowed." I don't get any stack trace or anything either.
This would get called a bunch of places, but I'm hoping that they would all wait on the same task, and then continue when it's complete. If it's already completed I hope it would just return right away. It's possible that I'm misunderstanding and that's just not how it works?
(Yes, I posted this before, but wasn't able to get an answer and I think this question summarizes the issue better. There is also this question, but that uses TPL and seems to have a much more complex goal.)
Try to use a Task<bool> instead of an IAsyncOperation<bool>. You can get a task using the AsTask extension method.

Logging in C#: Getting the class/method name performance

I've recently been tasked with adding logging statements to every method call in a solution. These log entries need to contain the class and method name.
I know I can use MethodBase.GetCurrentMethod() and the StackFrame.GetMethod() methods. Which is better? Is there a better (or more performant) way to get the class and method name?
Well, the best/fastest way is to include a string in every function. That may not appear the most practical solution, but MethodBase.GetCurrentMethod() requires coding inside every method that using it anyway. i.e. You can write
string funcName = "MyClass.MyFunction(int, int)";
or you can write
string funcName = MethodBase.GetCurrentMethod().Name
Now, if you want to get the Name of the function that called the current function (i.e., you want to do this in one spot in your logging function), then your only option is reading through the StackFrame.
I have two suggestions:
Use ready-made AOP frameworks (like http://www.sharpcrafters.com/ ) they can handle this easily
Do a custom prebuild action where you replace some kind of stub in the beginning of every method:
void PerformSomeAction()
{
//PUT_LOGGING_HERE
}
then in custom tool replace those stubs with method names. This is guaranteed fastest method, but requires some investments.
this.getType().toString() should get you the class
About the method it seems stackFrame and methodbase are the most obvouis solutions, I cant comment on which is more efficient.

Reflection, invoke

I have a dll file, and I took an object from it and called the functions inside this dll by the object, like this:
Command testClass = (Command)assembly.CreateInstance(creatObject);
testClass.Execute();
I used reflection for some reason. So I need to use invoke function & set values for variables, then calling the basic function Execute.
Previously I wrote the following:
object returnValue = objectType.GetMethod("setValues").Invoke(classObject, arguments);
testClass.Execute();
but it wasn't useful for me.
I used the following:
object returnValue = objectType.GetMethod("setValues").Invoke(classObject, arguments);
object returnValue1 = objectType.GetMethod("Execute").Invoke(classObject, null);
I just want to ask if this is right, to calling the execute in this way, and by the way it works!
Calling methods using Reflection the way you use it is "okay" as long as you know what you're doing. There are quite a few things to consider when using Reflection:
It is unsafe - you can very easily make a mistake - if you change the method name, you won't be notified by the compiler and you'll discover that at runtime
It is slow - Reflection is simply inefficient - calling a method is slower by orders of magnitude.
If you need to do this only rarely, then it may be fine. However, your initial approach using a shared base class Command appears to be a much better idea to me. Could you clarify why you decided to use Reflection, so that we can (perhaps) suggest a better way?
If you need dynamic invocation, you could also consider using C# 4.0 dynamic, which does all this stuff behind the scene for you and is more efficient than simple Reflection. However, you should still have a very good reason for doing this.
It's not right, why do you use Reflection, provide a common interface and call the method directly. If you don't know why you use reflection then it's wrong :)
If you are implementing a extensible system, perhaps MEF would be better?
Thanks for your answers, sure i know why i used Reflection.
Because i need to set the values for a function setValues(i, j..etc) in run time, and these parameters and their names are different from dll to another.
then i have to invoke this function with its current values, & finally run another function named Execute() with the same current values, which could be changed from execute to another for the program!
so when i just used:
object returnValue = objectType.GetMethod("setValues").Invoke(classObject, arguments);
testClass.Execute();
the execute didnt work with the run time values which been entered.
But by this :
object returnValue = objectType.GetMethod("setValues").Invoke(classObject, arguments);
object returnValue1 = objectType.GetMethod("Execute").Invoke(classObject, null);
it works.
So i just want to be sure, that my work is right and not only suitable for my case!

Hooking all function calls in JavaScript?

My intuitive response to this question would be ,"This is so stupid that I can't continue having this conversation." However:
Is there any way to hook all javascript function calls within my module? I'd like to find a convenient way of showing "loading blah...", "done..." messages when performing AJAX calls without having to explicitly place a call to a notification method in every AJAX method.
Also, is there any convenient way to set up a global exception handler in javascript?
It's perfectly possible, of course, to eliminate the need for either of these things by performing correct exception handling in every applicable method, but it would be nice to have a global "Whoops!" method to happily catch anything that managed to slip through due to programmer (ie, me) error.
Working in C#/ASP.NET if it matters or if there's a server-side gadget that could make this easier.
window.onerror will catch all of the errors. That's how Firebug and others work.
As for "every ajax method" you should just have 1 reusable ajax method, and have it be in charge of updating your status message.
If you only have ajax calls actually being made in one place, where the open and send commands are, then you can put in some logging, or notification there.
If you are using jquery, or some library that supports selectors, you can bind to the events of many objects.
The exception part was already answered.
You can look at all objects via
function show_props(obj, obj_name) { var result = "" for (var i in obj) result = obj_name "." i " = " obj[i] "\n" return result; }
That is from http://www.memestreams.net/users/acidus/blogid10323750/
I suggest that you use jQuery AOP plugin. I have used it for a large library.

Categories

Resources