Creating a Facebook.JsonArray object from a string, for testing purposes - c#

I'm using the Facebook C# SDK in my project and for testing purposes would like to be able to stub out the FacebookClient and insert my own fake client which will return pre-defined responses to Facebook API calls (I'm only calling the FacebookClient.Get method in my application). Achieving this is pretty easy using a factory pattern and a configurable StructureMap setup.
Apart from one thing...
My fake FacebookClient needs to return Facebook.JsonArray objects.
I've been sifting through the SDK source code, and can see that the SimpleJson class can be used to create JsonArray objects. However it is marked as internal, unless I start messing around and rebuilding the SDK.
Is there a simpler way?

You should use SimpleJson directly. You can get it via the "SimpleJson" NuGet package or on Github. Basically, we don't want people using the Facebook C# SDK as a JSON serializer - which is why we marked the methods you referenced as deprecated.
Github Source: https://github.com/facebook-csharp-sdk/simple-json

Found the answer myself; FacebookClient.DeserializeJson does the trick, although it is deprecated.
var content = /* Previously obtained JSON string */;
var client = new Facebook.FacebookClient();
var result = client.DeserializeJson(content, null);

You could also try using Facebook.Moq for testing purposes.
https://github.com/prabirshrestha/Facebook.Moq
Install-Package Facebook.Moq
var mockFb = FacebookMock.New();
mockFb
.FbSetup()
.ReturnsJson("{\"id\":\"4\",\"name\":\"Mark Zuckerberg\",\"first_name\":\"Mark\",\"last_name\":\"Zuckerberg\",\"link\":\"http:\\/\\/www.facebook.com\\/zuck\",\"username\":\"zuck\",\"gender\":\"male\",\"locale\":\"en_US\"}");
var fb = mockFb.Object;
dynamic result = fb.Get("/4");
Assert.Equal("Mark Zuckerberg", result.name);

Related

Using Force.com for arbitrary REST API methods

NB: This is a duplicate of my question on https://github.com/developerforce/Force.com-Toolkit-for-NET/issues/357. I'll sync both threads after this is resolved.
I'm using the Force.com toolkit for .NET. SOQL queries are working fine for me, but I'm trying to also make a simple REST call similar to one I can make with the REST Explorer tool at https://workbench.developerforce.com/restExplorer.php.
My code is:
using (var queryClient = new ForceClient(authClient.InstanceUrl, authClient.AccessToken, authClient.ApiVersion))
{
// Works fine
string soql = GetMyQuery();
QueryResult<dynamic> result = await queryClient.QueryAsync<dynamic>(soql);
// Throws exception. Changing version # doesn't seem to have any effect.
dynamic restResult = await queryClient.ExecuteRestApiAsync<dynamic>("/services/data/v46.0/sobjects/Task/describe");
When I get to ExecuteRestApiAsync, I get the exception:
Salesforce.Common.ForceException
HResult=0x80131500
Message=Could not find a match for URL
Source=Salesforce.Common
StackTrace:
at Salesforce.Common.JsonHttpClient.<HttpGetAsync>d__4`1.MoveNext()
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
[...]
I assume that my argument "/services/data/v46.0/sobjects/Task/describe", which works fine in the REST Explorer tool, needs to change. But I've guessed a bunch of different options (different versions, with or without leading URL string, etc.) and so far haven't gotten anything to work.
Can someone tell me how to use ForceClient to get the same results I get back from the Salesforce Workbench REST Explorer?
I ended up looking more closely at the ForceClient code. ExecuteRestApiAsync was not the correct call for this. For my specific example, there are 3 ways I found that work:
dynamic restResult = await queryClient.DescribeAsync<dynamic>("Task");
restResult = await queryClient.BasicInformationAsync<dynamic>("Task/describe/");
restResult = await queryClient.BasicInformationAsync<dynamic>("Task/describe");
(All 3 of the above lines return the same result)
This will work fine for sobjects. I don't think it's currently possible to use this library directly for things like reports which use "analytics" in their REST API definitions, but there are a couple workarounds that don't require recompiling the code. The cleanest and most performant of these that I've found is to pass your own HttpClient instances into the ForceClient ctor and use those directly instead of the methods on the ForceClient. An inspection of the ForceClient code will reveal that most of these methods are just thin string.Format() wrappers on HttpClient methods anyway.

Sendgrid not finding any templates when using urlPath: "templates"

I am using Sendgrid and am trying to access my templates.
Normally code underneath should provide the response var with my templates
var client = GetSendGridClient();
var response = await client.RequestAsync(SendGrid.SendGridClient.Method.GET, urlPath: "templates");
However it seems sendgrid is not returning any templates.
I thought "templates" was the default urlpath for my templates
And yes I have active templates on my SendGrid account, and yes My Sendgrid Client is being succesfully created.
In the SendGrid C# Library documentation, they show:
string apiKey = Environment.GetEnvironmentVariable("NAME_OF_THE_ENVIRONMENT_VARIABLE_FOR_YOUR_SENDGRID_KEY");
var client = new SendGridClient(apiKey);
You have: var client = GetSendGridClient();. Since you're not providing the apiKey, you're probably not authenticating, so it's not returning any data. Have you made sure that the client instance you generate is authenticated or otherwise "logged in"?
in the end it seems that my code only works with Legacy Templates and not the standard transactional. After creating a Legacy template SendGrid managed to find the templates.
To create a transaction template (none legacy type) add "generation": "dynamic" to the JSON when POSTing. For example.
{
"name": "my_template",
"generation": "dynamic"
}
NB: This appears to be an undocumented feature.!!

How to get information about all LexChatBots under a server with using AWSSDKCore.dll and AWSSDKLex.dll in C#

Recently when working with Lex in C#, I have referenced AWSCore.dll and AWSLex.dll and still trying to get a method that exposes all available Lexchatbots that I created in the Aamazon server.
var amazonPostRequest = new Amazon.Lex.Model.PostContentRequest();
var amazonPostResponse = new Amazon.Lex.Model.PostContentResponse();
used both methods to get all other information. Methods in request for bot name and alias is for setting and there is no method in response for getting available Lexchatbots in the server.
I don't believe that the Lex SDK supports this call directly.
Use the AWS Lex REST API to get a list of bots:
GET https://<your aws region endpoint>/bots/
https://docs.aws.amazon.com/lex/latest/dg/API_GetBots.html
After a long research I found the answer to my problem, It may help others.
First we need to add the AWSSDK.LexModelBuildingService through Nuget. This will add reference to the DLL.
From that all methods already exposed. We need to create both GetBotsRequest and GetBotsResponse methods.
var botRequest = new Amazon.LexModelBuildingService.Model.GetBotsRequest();
var botResponse = new Amazon.LexModelBuildingService.Model.GetBotsResponse();
Then we need to call lex model building service client
var amazonmodel = new AmazonLexModelBuildingServiceClient("YourAccesKeyId","YourSecretAccessKey",Amazon.RegionEndpoint.USEast1);
After that we can get the response of inbuilt method of GetBots()
botResponse = amazonmodel.GetBots(botRequest);
We will get the list of bots metadata
List<Amazon.LexModelBuildingService.Model.BotMetadata> bots = botResponse.Bots;
Every details about each bot created will be available in the array of list of bots
There is almost all methods in getting details from Lex configuration in LexModelBuildingService dll
Note:
In IAM (Identity Access Management) in AWS we need to give Access to have Lex components in Policy section. AWSLexFullAccess
or
atleast arn:aws:lex:region:account-id:bot:* access in policy

C# library for Amazon Product Advertising API

I'm trying to retrieve data from 'Amazon Product Advertising API', and I see that I need to sign my request, and then the response is an XML document which should be parsed.
I wonder if there is any library which I can send my requests throught, and recieve the response back as an object.
If not, what should I do to convert those XML reponses to an object ? I've read about schemas, but where do I get those schemas from and where do I get from the defention for the response objects so I could define them my self.
Thanks alot!
You can use the following nuget package
PM> Install-Package Nager.AmazonProductAdvertising
Example:
var authentication = new AmazonAuthentication();
authentication.AccessKey = "accesskey";
authentication.SecretKey = "secretkey";
var client = new AmazonProductAdvertisingClient(authentication, AmazonEndpoint.DE);
//Search
var result = await client.SearchItemsAsync("canon eos");
//Lookup
var result = await client.GetItemsAsync("B00BYPW00I");
There is a library that helps you sign requests AND process the responses by converting the XML into a relatively easy-to-use object. I've been using it for a few weeks now and wrote my own helper classes to really make querying the API fast and easy.
I wrote a demo console C# app where you can just plug in your Amazon credentials and start playing around here:
https://github.com/zoenberger/AmazonProductAdvertising
I also answered a similar question here:
https://stackoverflow.com/a/33617604/5543992

MongoDB C# Driver MongoCredential object

The documentation for the MongoDB Driver seems to differ from the actual driver pulled from NuGet.
More specifically, the documented "MongoCredentials" (plural) doesn’t exist, but only "MongoCredential" (singular). Further, MongoServer.GetDatabase doesn't seem to have a constructor that accepts MongoCredential, only MongoDatabaseSettings (alongside a string that names the databae), and I see no apparent way of giving a MongoDatabaseSettings object a MongoCredential object.
I haven't found any examples on Google with the objects I'm finding in the driver, only ones that align with the (outdated?) official documentation.
The driver that I'm using is called (in the NuGet Package Manager) "Official MongoDB C# driver."
To summarize: How does one actually provide credentials in the C# driver?
I'm also using the Official MongoDB C# driver from NuGet, version 1.8.3.
Indeed, the CSharp Driver Tutorial seems outdated.
However, the API documentation is correct; there's an entry there for the MongoCredential class (singular).
You can create a credential using either the constructor or one of the static factory methods (CreateGssapiCredential or CreateMongoCRCredential).
Next, in order to use the credentials you cannot specify them in the GetDatabase() call, but earlier, when you create the Server, like so:
var db1Credential = MongoCredential.CreateMongoCRCredential("db1", "uid", "pwd");
var db2Credential = MongoCredential.CreateMongoCRCredential("db2", "uid", "pwd");
var server = new MongoServer(
new MongoServerSettings
{
Server = new MongoServerAddress("localhost", 27017),
Credentials = new[]
{
db1Credential,
db2Credential
}
});

Categories

Resources