AsyncCallback with completed event - c#-4.0

I am Creating a library using Facebook C# SDK for windows phone.Facebook SDK Library version is 6.0.10.0. Facebook C# SDK contains asynchronous function calls only.
In which there is a postCompleted event handler which takes object and FacebookApiEventArgs as arguments and return type is void.
I am using two classes one is UI class and other is Businesslogic class. from UI i want to call the BusinessLogic class(s) PostWall function which will simply return the last message id.
I want to create a function something like this
public string PostWall(string accessToken, string message)
{
var fb = new FacebookClient(accessToken);
fb.PostCompleted += (o, args) =>
{
if (args.Error != null)
{
return;
}
var result = (IDictionary<string, object>)args.GetResultData();
_lastMessageId = (string)result["id"];
};
var parameters = new Dictionary<string, object>();
parameters["message"] = message;
fb.PostAsync("me/feed", parameters);
}
I do not know how to implement this. Is this functionality achievable or not.
Any help appreciated
Thanks in Advance

you can check out the wp7 sample at at https://github.com/facebook-csharp-sdk/facebook-windows-phone-sample.
What you are doing is already correct.

Related

Revit API: Material Asset Parameters get and set

I am trying to access via RevitAPI the data that is contained for particular asset. For instance I want to manipulate the Identity Data and get and eventually set some data for Manufacturer, Model, Cost and URL.
How can I achieve the same for the other Assets?
I am reading the Materials:
public IEnumerable<Material> GetMaterials(Document doc)
{
collector = new FilteredElementCollector(doc);
return collector.OfClass(typeof(Material)).OfType<Material>();
}
And then the Parameters:
public IEnumerable<Parameter> GetMaterialParameters(Material material)
{
List<Parameter> parameters = new List<Parameter>();
var localParameters = material.ParametersMap;
foreach (Parameter localParameter in localParameters)
{
parameters.Add(localParameter);
}
return parameters;
}
but still can't find where those properties are exposed.
What you really need is the Visual Materials API that was introduced in Revit 2018.1, the newest update:
Revit 2018.1 and the Visual Materials API
It is much harder and maybe impossible to achieve what you want in earlier versions.
Here are pointers to some more or less futile attempts:
Material Assets and FBX
Read Material Asset Parameter
Rendering Assets
Material Asset Textures
Finally this is how I managed to edit the parameters.
private void AssignProductData_OnClick(object sender, RoutedEventArgs e)
{
var material = (MaterialItem)MaterialsCombo.SelectedItem;
using (var transaction = new Transaction(doc))
{
transaction.Start("ChangeName");
var parameterManufacturer = material.Material.get_Parameter(BuiltInParameter.ALL_MODEL_MANUFACTURER);
parameterManufacturer.Set("Brand New Product");
var parameterCost = material.Material.get_Parameter(BuiltInParameter.ALL_MODEL_COST);
parameterCost.Set(1099.99);
var parameterModel = material.Material.get_Parameter(BuiltInParameter.ALL_MODEL_MODEL);
parameterModel.Set("R1223123KJNSDAS9089");
var parameterUrl = material.Material.get_Parameter(BuiltInParameter.ALL_MODEL_URL);
parameterUrl.Set("http://www.site.no/products/R1223123KJNSDAS9089");
transaction.Commit();
}
}

Gmail Api Java Client - Use mockito/powermock example to mock Gmail API calls

We are using the Gmail API Java Client version 1.19.0. Is there anyone that has implemented successfully a working mock object that could be used for stubing requests such as:
gmailClient.users().history().list("me").setStartHistoryId(startHistoryId).setPageToken(pageToken).execute();
Essentially, we would like to stub the above call and create a specific response, to test different business scenarios.
Please check below a working example of the above question. No need to use powermock. Mockito is only needed.
#Before
public void init() throws Exception{
ListHistoryResponse historyResponse = new ListHistoryResponse();
historyResponse.setHistoryId(BigInteger.valueOf(1234L));
List<History> historyList = new ArrayList<>();
History historyEntry = new History();
Message message = new Message();
message.setId("123456");
message.setThreadId("123456");
List<Message> messages = new ArrayList<>();
messages.add(message);
historyEntry.setMessages(messages);
historyList.add(historyEntry);
mock = mock(Gmail.class);
Gmail.Users users = mock(Gmail.Users.class);
Gmail.Users.History history = mock(Gmail.Users.History.class);
Gmail.Users.History.List list = mock(Gmail.Users.History.List.class);
when(mock.users()).thenReturn(users);
when(users.history()).thenReturn(history);
when(history.list("me")).thenReturn(list);
when(list.setStartHistoryId(BigInteger.valueOf(123L))).thenReturn(list);
when(list.setPageToken(null)).thenReturn(list);
when(list.execute()).thenReturn(historyResponse);
}
you can mock the classes are long as they're not final, etc. what's the limitation here? (haven't looked at the source code for the Google java client libraries but shouldn't be gmail-specific--if you've found someone doing it for another Google java client API you should be able to re-use it).
There is also MockHttpTransport helper class for such a scenario. Please consult with documentation chapter HTTP Unit Testing
HttpTransport transport = new MockHttpTransport() {
#Override
public LowLevelHttpRequest buildRequest(String method, String url) throws IOException {
return new MockLowLevelHttpRequest() {
#Override
public LowLevelHttpResponse execute() throws IOException {
MockLowLevelHttpResponse response = new MockLowLevelHttpResponse();
response.addHeader("custom_header", "value");
response.setStatusCode(404);
response.setContentType(Json.MEDIA_TYPE);
response.setContent("{\"error\":\"not found\"}");
return response;
}
};
}
};

How to Return Null value from method using FakeItEasy

I have a service faked using FakeitEasy and i am trying to call its method. Here is the Code
var client = container.Resolve<MyService>();
A.CallTo(() => client.GetUserProfile(userName)).Returns(null);
The method GetUserProfile returns some object in actual implementation. but for some reason i want this method to return null. I am using above code to acomplish this purpose but its returning Fake object instead of null.
Here is the Test Setup i am using
[Test]
public void MyTest(string sitecollectionGuid, string customerName)
{
var mockHttpContext = SetupHttpContext(sitecollectionGuid, customerName);
var client = container.Resolve<MyService>();
A.CallTo(() => client.GetUserProfile(userName)).Returns(null);
var controllerContext = new ControllerContext(mockHttpContext, new RouteData(), A.Fake<ControllerBase>());
controller.ControllerContext = controllerContext;
var result = controller.CheckUsername(userName);
Assert.IsNotNull(result, "Result is not as expected");
}
Production Method looks like the following
public UserDAO GetUserProfile(string userName)
{
UserDAO objUserProfile = new UserDAO();
IUsers objUsers = (IUsers)Global.Container["Users"];
IUser objUser = objUsers.GetByUserName(userName);
if (objUser == null)
{
return null;
}
else
{
objUserProfile = AutoMapper.Mapper.Map<IUser, UserDAO>(objUser);
objUserProfile.FirstName = objUser.FirstName;
objUserProfile.MiddleName = objUser.MiddleName;
objUserProfile.LastName = objUser.LastName;
....................
....................
<setting other properties>
....................
....................
return objUserProfile;
}
}
Any help will be appreciated
Thanks
Try and type your (null) reference.
UserDAO returnValue = null;
var client = container.Resolve<MyService>();
A.CallTo(() => client.GetUserProfile(userName)).Returns(returnValue);
In order to configure a method, it has to be virtual, abstract, or defined on an interface that you're faking. However,
public UserDAO GetUserProfile(string userName)
is neither virtual nor abstract, so unless you're creating a fake from an interface, this will not work. However, A.CallTo will raise an error when trying to configure either a non-virtual method or a method on a concrete (not faked) object, and you've not mentioned either of these things happening.
From your code, we still can't tell
where client came from (I know, the container, but how did it get there?),
whether controller uses the same client, and
what the connection between controller.CheckUsername and client.GetUserProfile is
My guesses at this point are
whatever controller is using to CheckUsername, it's not the same client that the test has, or
client.GetUserProfile is being called with the wrong userName (although you use the same one in controller.CheckUsername(userName), so that seems less likely)
If you're unable or unwilling to connect the dots, I suggest checking the value of userName at all points, and making sure that when client is called in the production code, it's a faked object (debug in and examine the type—it should be clear whether its your type or the faked one).
or you could just cast the null to the type in context.
var client = container.Resolve<MyService>();
A.CallTo(() => client.GetUserProfile(userName)).Returns((UserDAO) returnValue);

mvvm light async call in viewmodel constructor

I'm developing a win phone 8 app using portable version of mvvmlight.
In the creation of a ViewModel I have to do a call to a service that read data from a Azure Mobile Service using the Azure Mobile Service Sdk.
Sdk apis use async /await to do the work, and I can't do async calls in the ViewModel or in Service costructor.
The code is like this:
public ListaArtiModel(INavigate navigationService)
{
_navigationService = navigationService;
ArtiMarzialiService artiService = new ArtiMarzialiService();
List<ArteMarziale>risultato = await artiService.ListaArti();
}
and the compiler tells
Error 1 The 'await' operator can only be used within an async method. Consider marking this method with the 'async' modifier and changing its return type to 'Task'.
How can I solve this?
thanks,
Luca
I have a "task notifier" type in my AsyncEx library that is essentially an INotifyPropertyChanged wrapper for Task<T>. You can use it like this:
public ListaArtiModel(INavigate navigationService)
{
_navigationService = navigationService;
ArtiMarzialiService artiService = new ArtiMarzialiService();
Arti = NotifyTaskCompletion.Create(LoadArti(artiService));
}
private async Task<ObservableCollection<ArtiMarziali>> LoadArti(ArtiMarzialiService artiService)
{
return new ObservableCollection<ArtiMarziali>(await artiService.ListaArti());
}
public INotifyTaskCompletion<ObservableCollection<ArtiMarziali>> Arti { get; private set; }
Then your databinding code can use Arti.Result, Arti.IsFaulted, Arti.ErrorMessage, etc.
You should redesign your ViewModel to have a LoadDataAsync() or InitializeAsync() method that is used to set up the ViewModel
In general, class constructors should be kept as simple as possible and you should avoid doing any long running or potentially exception-prone work in the constructor
I think i found a better solution:
declared the service interface this way:
void ListaArti(Action<List<ArtiMarziali>, Exception> callback);
implemented it this way:
public async void ListaArti(Action<List<ArtiMarziali>, Exception> callback)
{
Exception err = null;
List<ArtiMarziali> risultato = null;
try
{
risultato = await MobileService.GetTable<ArtiMarziali>().ToListAsync();
}
catch (Exception ex)
{
err = ex;
}
callback(risultato, err);
}
called the service in the viewmodel constructor this way:
IArtiMarzialiService artiService = new ArtiMarzialiService();
artiService.ListaArti((arti, err) =>
{
if (err != null)
{
/// if there is an error should create a property and bind to it for better practices
System.Diagnostics.Debug.WriteLine(err.ToString());
}
else
{
/// set the property
Arti = new ObservableCollection<ArtiMarziali>(arti);
}
});
using an async function that returns a void I don't have to use the await statement in the caller, and I use the callback to set the property in the viewmodel when the data are available.

Attempting ValidationAttribute in MVC4 that is asynchronous using Async, Task and Await

I am attempting to write a Validation attribute in MVC4.
The purpose is to check for the existence of an application reference (just a string that represents a key I wish to prevent a duplicate for).
My data is accessed via WebAPI and because I am using 4.5 I wish to make this asynchronous if possible.
I am perhaps not making the best or appropriate usage of async and await but I would like to know how to call my async method from the overridden IsValid method of the inherited Validation class.
public class UniqueApplicationReferenceAttribute : ValidationAttribute
{
public UniqueApplicationReferenceAttribute() : base(() => "The {0} already exists") { }
public int? ApplicationCount { get; set; }
public override bool IsValid(object value)
{
var myTask = GetApplicationRefCountAsync();
myTask.Wait();
this.ApplicationCount = this.ApplicationCount ?? 0;
if (ApplicationCount > 0)
{
return true;
}
else
{
return false;
}
}
public async Task GetApplicationRefCountAsync()
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:11111/");
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
var apps = client.GetStringAsync("api/dataapplications");
await Task.WhenAll(apps);
var appList = apps.Result;
this.ApplicationCount = appList.Count();// apps.Count();
}
}
Many thanks,
Dan.
I recommend that you call your WebAPI methods synchronously. ValidationAttribute does not support asynchronous implementations natively, so any synchronous-over-asynchronous code you'll write is just going to be a hack and not actually provide any benefit as compared to the synchronous version.
I'm not able to test this in full, but you should be able to do something like this:
public bool IsValid(object value)
{
var appCount = GetApplicationRefCountAsync().Result;
return appCount > 0;
}
public async Task<int> GetApplicationRefCountAsync()
{
var client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:11111/");
client.DefaultRequestHeaders.Accept.Add(
new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
return await client.GetStringAsync("api/dataapplications")
.ContinueWith(r => Convert.ToInt32(r))
.ConfigureAwait(false);
}
Be careful about using async/await methods in an ASP.NET thread. It's easy to create deadlocks.

Resources