I am looking to implement async coding for some web services.
I came across a tutorial and tried to follow it and implement it however one specific section I am having trouble with.
My example
public void CalculatePricingAsync(QuoteInput obj)
{
AsyncManager.OutstandingOperations.Increment();
var apiService = new ApiService();
ApiService.CalculatedPricingCompleted += (sender, e) =>
{
AsyncManager.Parameters["Pricing"] = e.Value;
AsyncManager.OutstandingOperations.Decrement();
};
ApiService.CalculatedPricing(obj);
}
public JsonResult CalculatePricingCompleted(string[] pricing)
{
var jr = new JsonResult { Data = new { pricing } };
return jr;
}
The following line taken from the first method above does not exist in the ApiService class. Can someone explain what this expression is doing and what it means. Do I just create a method of this name in that ApiService class and leave it blank, does it somehow work with the second method. I am little unclear what its doing and where the method should be declared and what exactly should be in it.
ApiService.CalculatedPricingCompleted += (sender, e) =>
{
AsyncManager.Parameters["Pricing"] = e.Value;
AsyncManager.OutstandingOperations.Decrement();
};
this > (CalculatedPricingCompleted) in the line above is showing red in visual studio, it is clearly looking to be defined somewhere.
CalculatedPricingCompleted is a delegated method inside the ApiService. You need to look into the service class and add it. Having said this, I highly recommend using async / await for asynchronous operations in .NET. If you are on .NET 4.0+ there is no excuse not to use it.
Related
Can anyone suggest a how to perform unit test(s) against a method which has an API call in it?
My xamarin application has rest call as follows:
var result = await Rest.Get(uri)
.WithTrackingIndicator(RestCall.GetChecklistHistoryByStorage)
.WithConnectivityPrecheck(true, res => { res.ResultObject = new ChecklistList { Checklist = _checklistMapper.Map(_checklistStorageService.Find(instanceIdentifier, StorageKeyType.PrimaryKey), true) }; })
.ExecuteAsync();
If you abstract your API call behind an interface then you can Mock the behaviour with a framework such as Moq
Something like this:
public interface IRest
{
Task<Result> Get(Uri uri);
}
Then you could set something up like:
var restMock = new Mock<IRest>();
restMock(rest => rest.Get(uri))
.Returns(new Result());
There will obviously be some further complexities getting around your WithTrackingIndicator and WithConnectivityPrecheck methods but this should hopefully give you a good starting point.
Im working on a website that integrates with Dynamics 365 with the Dynamics SDK. We have seen errors in the logs such as “Cannot access a disposed object”. Upon further investigation we found out that the SDK methods are not thread safe so needed to refactor the code to take this into account.
We had a method such as follows that would create or update a Contact entity depending on whether it already exists:
public Guid? SetProfile(IProfile profile)
{
using (var xrm = new XrmServiceContext(_organizationService))
{
//check whether account already exists
var crmProfile = GetContact(xrm, profile.UserId);
if (crmProfile == null)
{
//create new account if required
{
crmProfile = new Contact
{
EMailAddress1 = profile.Username,
//lots of properties hidden to make for easier code example
};
}
xrm.AddObject(crmProfile);
}
else
{
//update existing account
crmProfile.new_Title = profile.Title.HasValue ? new OptionSetValue(profile.Title.Value) : null;
//lots of properties hidden to make for easier code example
xrm.UpdateObject(crmProfile);
}
var response = xrm.SaveChanges();
return crmProfile.Id;
}
}
When this method was executed concurrently by 2 or more users the error "Cannot access a disposed object" would be thrown, referring to the XrmServiceContext object.
I therefore knew that I needed to make this method thread-safe, but also it needs to be Synchronous as our UI depends on having the return value of the method. I played around with different threading methods:
Task.Factory.StartNew(() => delegate
new Thread()
However, with both of these methods I wasn't able to get the method to execute synchronously, so I ended up with:
public Guid? SetProfile(IProfile profile)
{
var task = new Task<Guid?>(() =>
{
using (var xrm = new XrmServiceContext(_organizationService))
{
//check whether account already exists
var crmProfile = GetContact(xrm, profile.UserId);
if (crmProfile == null)
{
//create new account if required
{
crmProfile = new Contact
{
EMailAddress1 = profile.Username,
//lots of properties hidden to make for easier code example
};
}
xrm.AddObject(crmProfile);
}
else
{
//update existing account
crmProfile.new_Title = profile.Title.HasValue ? new OptionSetValue(profile.Title.Value) : null;
//lots of properties hidden to make for easier code example
xrm.UpdateObject(crmProfile);
}
var response = xrm.SaveChanges();
return crmProfile.Id;
}
});
task.RunSynchronously();
return task.Result;
}
Everything I seemed to read online suggested I should use the StartNew method, however this is geared towards Asynchronous calls with I could not allow, and it also seemed that it doesnt guarantee a new thread - from what I've read I understand it is clever enough to know when it needs to create a new thread - however in my instance I have to be certain a new thread is used for the call to Dynamics.
Questions:
Anything wrong with the approach I've taken for a Web application?
If I can't use Asynchronous calls, is there any advantage whatsoever to using the StartNew method?
Many thanks for your time in advance
Kind regards
dotdev
public static void CacheUncachedMessageIDs(List<int> messageIDs)
{
var uncachedRecordIDs = LocalCacheController.GetUncachedRecordIDs<PrivateMessage>(messageIDs);
if (!uncachedRecordIDs.Any()) return;
using (var db = new DBContext())
{
.....
}
}
The above method is repeated regularly throughout the project (except with different generics passed in). I'm looking to avoid repeated usages of the if (!uncachedRecordIDs.Any()) return; lines.
In short, is it possible to make the LocalCacheController.GetUncachedRecordIDs return the CacheUncachedMessageIDs method?
This will guarantee a new data context is not created unless it needs to be (stops accidentally forgetting to add the return line in the parent method).
It is not possible for a nested method to return from parent method.
You can do some unhandled Exception inside GetUncachedRecordIDs, that will do the trick, but it is not supposed to do this, so it creates confusion. Moreover, it is very slow.
Another not suggested mechanic is to use some goto magic. This also generates confusion because goto allows unexpected behaviour in program execution flow.
Your best bet would be to return a Result object with simple bool HasUncachedRecordIDs field and then check it. If it passes, then return. This solution solves the problem of calling a method, which is Any() in this case.
var uncachedRecordIDsResult = LocalCacheController.GetUncachedRecordIDs<PrivateMessage>(messageIDs);
if(uncachedRecordIDsResult.HasUncachedRecordIDs) return;
My reasoning for lack of this feature in the language is that calling GetUncachedRecordIDs in basically any function would unexpectedly end that parent function, without warning. Also, it would intertwine closely both functions, and best programming practices involve loose coupling of classes and methods.
You could pass an Action to your GetUncachedRecordIDs method which you only invoke if you need to. Rough sketch of the idea:
// LocalCacheController
void GetUncachedRecordIDs<T>(List<int> messageIDs, Action<List<int>> action)
{
// ...
if (!cached) {
action(recordIds);
}
}
// ...
public static void CacheUncachedMessageIDs(List<int> messageIDs)
{
LocalCacheController.GetUncachedRecordIDs<PrivateMessage>(messageIDs, uncachedRecordIDs => {
using (var db = new DBContext())
{
// ...
}
});
}
In C#, when I call a method, I want to be able to detect if it will (or could potentially) call something with a certain attribute.
For example, when, TheProgram.Run() get's called, I want to know that it will call a MyClass.DoTheWork, which has an attribute [IsRegistered], which calls a private method FormatTheResult() which also has the attribute [IsRegistered].
I've been thinking about it for a while and can't think how it could be achieved. I'm thinking, something like the invert of a stack trace, or registering components with an attribute or aspect, or perhaps leaning on MEF.
Is this possible?
This detection could happen at compile time or a run time, but ideally before the method with the attribute is executed.
Mocking frameworks can do this. It is useful for behavioural tests.
For example, given this setup:
public class Calculator {
private IHelpers _helperMethods;
public Calculator(IHelpers helper) {
_helperMethods = helper;
}
public int Add(int a, int b) {
if (_helperMethods.AboveZero(a) && _helperMethods.AboveZero(b)) {
return a + b;
}
throw new Exception("Argument not above zero");
}
}
public interface IHelpers {
bool AboveZero(int i);
}
Using Moq, you can verify (via a behavioural unit test) that IHelpers.AboveZero is called when calling the Add method like so:
[TestMethod]
public void When_Add_Called_Verify_AboveZero_Called_Too() {
// Arrange
var helperMock = new Mock<IHelpers>();
helperMock.Setup(x => x.AboveZero(It.IsAny<int>())).Returns(true);
var calc = new Calculator(helperMock.Object);
// Act
var result = calc.Add(1, 2);
// Assert
helperMock.Verify(x => x.AboveZero(It.IsAny<int>())); // verify that AboveZero was called.
}
The attributes are a different story though..
Is this what you were after?
(Please excuse any compiler errors.. this was typed by hand :/)
What you are probably looking for is Roslyn.
http://msdn.microsoft.com/en-au/vstudio/roslyn.aspx
What you can do with this is analize the syntax tree directly, so for your method in question you could access from the syntax tree all method calls that occur. Then you can follow that and check the method being called has that attribute.
Is pretty complex stuff, so I wont attempt a code sample for your particular scenario but I have used it before to analize multiple solitions and inject code.
It's pretty awesome here is a sample from the docs.
namespace GettingStartedCS
{
class Program
{
static void Main(string[] args)
{
SyntaxTree tree = SyntaxTree.ParseCompilationUnit(
#"using System;
using System.Collections;
using System.Linq;
using System.Text;
namespace HelloWorld
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(""Hello, World!"");
}
}
}");
var root = (CompilationUnitSyntax)tree.GetRoot();
var firstMember = root.Members[0];
var helloWorldDeclaration = (NamespaceDeclarationSyntax)firstMember;
var programDeclaration = (TypeDeclarationSyntax)helloWorldDeclaration.Members[0];
var mainDeclaration = (MethodDeclarationSyntax)programDeclaration.Members[0];
var argsParameter = mainDeclaration.ParameterList.Parameters[0];
}
}
}
Resharper does kind of what you want. Execute the menu command Resharper -> Inspect -> Outgoing calls, and then expand tree nodes ad infinitum until you reach the desired method. If you're using reflection or stuff like that, you're out of luck, I guess. The picture below is an example of how it works.
This is the way I've found to do it:
public static IList<MethodBase> GetCalledMethods(MethodBase methodBase)
{
IList<MethodBase> calledMethods = new List<MethodBase>();
var body = methodBase.GetMethodBody();
Module module = Assembly.GetExecutingAssembly().ManifestModule;
byte[] bytes = body.GetILAsByteArray();
using (var stream = new MemoryStream(bytes))
{
long streamLength = stream.Length;
using (var reader = new BinaryReader(stream))
{
while (reader.BaseStream.Position < streamLength)
{
byte instruction = reader.ReadByte();
if (instruction == OpCodes.Call.Value
|| instruction == OpCodes.Callvirt.Value
|| instruction == OpCodes.Newobj.Value)
{
int token = reader.ReadInt32();
var method = module.ResolveMethod(token);
calledMethods.Add(method);
}
}
}
}
return calledMethods;
}
I'd like to list all the methods that are called from a specific method. E.g. if I have the following code:
public void test1() {
test2();
test3();
}
The list should contain test2() and test3(). It would be great if methods of the same class but also methods of another class could be listed.
Additionaly I'd like to find a way to detect which fields are used of a method:
public class A {
private String test1 = "";
private String test2 = "";
public void test() {
Console.WriteLine(test1);
}
}
Should therefore list test1.
I tried this using Mono.Cecil, but unfortunately I couldn't find lot of documentation about the project. So does anybody know how to do that?
Edit: I'd like to do it with Mono.Cecil because over its API I can directly use the results in my application. If I use built in tools in Visual Studio or similar, it's quite difficult to furhter process the results.
I haven't really worked with Cecil but the HowTo page shows how to enumerate the types, your problem only seems to require looping over the instructions for the ones your after: Call and Load Field. This sample code seems to handle the cases you mentioned but there may be more to it, you should probably check the other Call instructions too. If you make it recursive make sure you keep track of the methods you've already checked.
static void Main(string[] args)
{
var module = ModuleDefinition.ReadModule("CecilTest.exe");
var type = module.Types.First(x => x.Name == "A");
var method = type.Methods.First(x => x.Name == "test");
PrintMethods(method);
PrintFields(method);
Console.ReadLine();
}
public static void PrintMethods(MethodDefinition method)
{
Console.WriteLine(method.Name);
foreach (var instruction in method.Body.Instructions)
{
if (instruction.OpCode == OpCodes.Call)
{
MethodReference methodCall = instruction.Operand as MethodReference;
if(methodCall != null)
Console.WriteLine("\t" + methodCall.Name);
}
}
}
public static void PrintFields(MethodDefinition method)
{
Console.WriteLine(method.Name);
foreach (var instruction in method.Body.Instructions)
{
if (instruction.OpCode == OpCodes.Ldfld)
{
FieldReference field = instruction.Operand as FieldReference;
if (field != null)
Console.WriteLine("\t" + field.Name);
}
}
}
This can't be done simply using the reflection API within C#. Really you would need to parse the original source code which is probably not the kind of solution you're looking for. But for example this is how Visual Studio gets this kind of info to do refactoring.
You might get somewhere analysing the IL - along the lines of what Reflector does but that would be a huge piece of work I think.
you can use .NET Reflector tool if you want to pay. you could also take a look at this .NET Method Dependencies it gets tricky though, as you're going to be going into the IL. A third possible would be to use the macro engine in VS, it does have a facility to analyze code,CodeElement, I'm not sure if it can do dependencies though.