Using TweetSharp and Rx - system.reactive

I have been trying to create an observable tweeter feed using tweetsharp with the following
public IObservable<IEnumerable<TwitterStatus>> MakeTweetRequest(string screenName)
{
var service = new TwitterService();
var r = Observable.FromAsyncPattern<string, IEnumerable<TwitterStatus>>(
(x,y,g) => service.BeginListTweetsOnSpecifiedUserTimeline(x),
d => service.EndListTweetsOnSpecifiedUserTimeline(d) );
return r(screenName);
}
but i'm just unable to get it to work can anyone help?

There are a few examples using TweetSharp in my Rx-Demo
Each of these do the same thing, via different Rx methods, which is too ListTweetsOnHomeTimelineSince and all future tweets:
TwitterFeedAsync
TwitterFeedCreateSync
TwitterFeedGenerateSync

Related

Getting JSON Data from InAppBrowser IONIC 5

I'm using the cordova in-app-browser plugin. One Page I get back is just a bunch of JSON-Data which i want to store inside my IONIC 5 Project. I could'nt figure out yet how to receive the Data and transfer it to the App yet with the Plugin. Is there such a possibility?
Thank you
To transfer data using InAppBrowser you can pass It by parameters, and also to receive the date you get it from parameters. Follows a small example:
Short way sending data on Page1.ts:
const dataToSend = `/${this.dataOne}/${this.dataTwo}`;
let finalUrl = `https://app-example.io` + dataToSend;
this.inAppB.create(finalUrl, '_system');
Receiving data on Page2.ts:
import { ActivatedRoute } from '#angular/router';
constructor(
private actRoute: ActivatedRoute
){}
ngOnInit() {
this.actRoute.paramMap.subscribe( params => {
console.log('Params => ', params);
if (params) {
let dataReceived = [params['params']['dataOne'], params['params']['dataTwo']];
console.log('dataReceived => ', dataReceived);
}
}
}
Please, adapt it to your code and variables as it is just a short example.

Solidity Contract Calls issue

I created a dummy solidity contract (https://learn.aion.network/docs/deploy-a-smart-contract-using-web3) and deployed it.The issue occurs when I try to make a call using aion-web3.
const contract = require('aion-web3-eth-contract');
contract.setProvider("https://aion.api.nodesmith.io/v1/mastery/jsonrpc?apiKey=*");
const Web3 = require('aion-web3');
const web3 = new Web3(new Web3.providers.HttpProvider("https://aion.api.nodesmith.io/v1/mastery/jsonrpc?apiKey=*"));
const account = web3.eth.accounts.privateKeyToAccount("****");
let myContract = new contract([...], "0xa0e1166A455a0d75CFC2bfa32D7f76f0e1852c106b981Acf59EDE327CFD36811");
// console.log("C a",myContract.options.address);
myContract.methods.getCount().call({from: account.address}, function (error, result) {
if (error){
console.log("err=>", error)
} else {
console.log("res=>", result)
}
});
I expect 0 because it the first call but its throwing the below error:
TypeError: myContract.methods.getCount is not a function
It looks like the way you're trying to call the function isn't quite correct. Instead of creating a myContract object, try just putting the contract address into a transaction object, and then calling that:
let transactionCall = {
from: account.address,
to: "0xa0bf00624C2E81de745A826052D635f5c35515F0B55df6E4b1BAaCe785C124B9",
gas: 54321,
data: contractInst.methods.getCount().encodeABI()
};
web3.eth.call(transactionCall).then((res) => console.log(web3.utils.hexToNumber(res)));
Also, make sure that your account has coins in it. There's a faucet you can use here: https://faucets.blockxlabs.com/aion
Also, welcome to StackOverflow!
Try use the following to create a contract instance:
let myContract = new web3.eth.Contract(["compile contract abi info"])
And
web3.eth.call({to:YourContractAddress, data:myContract.methods.getCount().encodeABI()}).then((res) => console.log(web3.utils.hexToNumber(res)));

Programatically Invoking LUIS Outside the Message Controler

I'm writting a bot application that uses a Prompt Dialog to interact with users.
The idea here is when a user selects a certain option a message should be sent to LUIS that will be processing the request via ML.
Thought about two ways to get it done.
1 - Invoke LUIS directly
2 - Simulate a user entry to make sure the message would pass by the Message Controller and finally the Root Dialog which will be making a LUIS call
Makes sense?
I've tried something like this but it didn't work.
public virtual async Task ChoiceReceivedAsync_MainMenuOption(IDialogContext context, IAwaitable<MainMenuOption> activity)
{
...
IMessageActivity message = Activity.CreateMessageActivity();
message.Text = "Como e a seguranca da escola?";
message.TextFormat = "plain";
message.Locale = "en-Us";
var luisAttributes = new LuisModelAttribute(BellaMain.GlobalVariable.LuisModelID, BellaMain.GlobalVariable.LuisSubscriptionKey);
var luisService = new LuisService(luisAttributes);
await Conversation.SendAsync(message, () => new Dialogs.RootDialog(luisService));
}
Any ideas?
Thanks
Trying to call LUIS by mocking up a new Activity to send to the bot is not recommended.
Instead you should call LUIS through a simple request using an HttpClient.
Here is a sample from the LUIS Endpoint API:
Copy-pasted example:
using System;
using System.Net.Http.Headers;
using System.Text;
using System.Net.Http;
using System.Web;
namespace CSHttpClientSample
{
static class Program
{
static void Main()
{
MakeRequest();
Console.WriteLine("Hit ENTER to exit...");
Console.ReadLine();
}
static async void MakeRequest()
{
var client = new HttpClient();
var queryString = HttpUtility.ParseQueryString(string.Empty);
// Request headers
client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", "{subscription key}");
// Request parameters
queryString["timezoneOffset"] = "{number}";
queryString["verbose"] = "{boolean}";
queryString["spellCheck"] = "{boolean}";
queryString["staging"] = "{boolean}";
queryString["bing-spell-check-subscription-key"] = "{string}";
queryString["log"] = "{boolean}";
var uri = "https://westus.api.cognitive.microsoft.com/luis/v2.0/apps/{appId}?q={q}&" + queryString;
var response = await client.GetAsync(uri);
}
}
}

Is there a way to filter based on dates in Bing Webmaster API calls?

I am trying to fetch some page stats using GetPageStats method in IWebmasterApi for a url. It returns stats for all the dates. Is there a way to set filter on dates we want the date for? I am sending a GET request through Postman and not using c# program.
After some digging around, I found it is not possible to do a date filter in Bing API calls. Everytime, the entire data (3 months approx) of page stats is sent. The date filter has to be handled in client side.
Hi Not sure this is answering your question, I just start "digging" to develop some app for my use, normally first I read where people complain and fail.
there is some date filter...
You need to see what is the request in C# easy... then reverse engineering and build it in Postman
var oneMonthAgo = DateTime.Now.AddMonths(-1);
var stats = api.GetRankAndTrafficStats("http://yoursite.com/")
.Where(s => s.Date > oneMonthAgo)
.OrderBy(s => s.Date);
https://learn.microsoft.com/en-us/bingwebmaster/getting-started
namespace WebmasterApiExamples
{
using System;
using System.Linq;
using System.ServiceModel;
internal class Program
{
private static void Main(string[] args)
{
var api = new WebmasterApi.WebmasterApiClient();
try
{
var oneMonthAgo = DateTime.Now.AddMonths(-1);
var stats = api.GetRankAndTrafficStats("http://yoursite.com/")
.Where(s => s.Date > oneMonthAgo)
.OrderBy(s => s.Date);
Console.WriteLine("Date\tImpressions\tClicks");
foreach (var value in stats)
{
Console.WriteLine("{0}\t{1}\t{2}", value.Date.ToShortDateString(), value.Impressions, value.Clicks);
}
}
catch (FaultException<WebmasterApi.ApiFault> fault)
{
Console.WriteLine("Failed to add site: {0}", fault.Message);
}
}
}
}

Possible to force the C# Facebook SDK to use HTTP instead of HTTPS?

I need to do some connectivity simulations to see that my code handles various connectivity errors to Facebook. I want to be able to simulate 500s, timeouts etc.
The easiest way to do that is to use Fiddler, but it seems to not be working with HTTPS (I get 403s when I try).
Is ther a way to force the SDK to work with HTTP instead of HTTPS for debugging purposes?
Facebook C# SDK supports your scenario for mocking the entire HttpWebRequest and HttpWebResponse. In fact we actually use that internally in our unit tests so that every single line of the code in Facebook C# SDK actually gets executed and the result is always the same. https://github.com/facebook-csharp-sdk/facebook-csharp-sdk/blob/v5/Source/Facebook.Tests/TestExtensions.cs For now you will need to check these tests in v5 branch as we haven't yet migrated those tests to v6.
For v5, you will need to override the protected CreateHttpWebRequest method in FacebookClient.
Here is an example for v5 when there is no internet connection. There are three hidden classes HttpWebRequestWrapper, HttpWebResponseWrapper and WebExceptionWrapper that you will need to make use of.
public static void NoInternetConnection(this Mock<Facebook.FacebookClient> facebookClient, out Mock<HttpWebRequestWrapper> mockRequest, out Mock<WebExceptionWrapper> mockWebException)
{
mockRequest = new Mock<HttpWebRequestWrapper>();
mockWebException = new Mock<WebExceptionWrapper>();
var mockAsyncResult = new Mock<IAsyncResult>();
var request = mockRequest.Object;
var webException = mockWebException.Object;
var asyncResult = mockAsyncResult.Object;
mockRequest.SetupProperty(r => r.Method);
mockRequest.SetupProperty(r => r.ContentType);
mockRequest.SetupProperty(r => r.ContentLength);
mockAsyncResult
.Setup(ar => ar.AsyncWaitHandle)
.Returns((ManualResetEvent)null);
mockWebException
.Setup(e => e.GetResponse())
.Returns<HttpWebResponseWrapper>(null);
mockRequest
.Setup(r => r.GetResponse())
.Throws(webException);
mockRequest
.Setup(r => r.EndGetResponse(It.IsAny<IAsyncResult>()))
.Throws(webException);
AsyncCallback callback = null;
mockRequest
.Setup(r => r.BeginGetResponse(It.IsAny<AsyncCallback>(), It.IsAny<object>()))
.Callback<AsyncCallback, object>((c, s) =>
{
callback = c;
})
.Returns(() =>
{
callback(asyncResult);
return asyncResult;
});
var mockRequestCopy = mockRequest;
var mockWebExceptionCopy = mockWebException;
facebookClient.Protected()
.Setup<HttpWebRequestWrapper>("CreateHttpWebRequest", ItExpr.IsAny<Uri>())
.Callback<Uri>(uri =>
{
mockRequestCopy.Setup(r => r.RequestUri).Returns(uri);
mockWebExceptionCopy.Setup(e => e.Message).Returns(string.Format("The remote name could not be resolved: '{0}'", uri.Host));
})
.Returns(request);
}
You can then write your tests as below.
[Fact]
public void SyncWhenThereIsNotInternetConnectionAndFiddlerIsNotOpen_ThrowsWebExceptionWrapper()
{
var mockFb = new Mock<FacebookClient> { CallBase = true };
Mock<HttpWebRequestWrapper> mockRequest;
Mock<WebExceptionWrapper> mockWebException;
mockFb.NoInternetConnection(out mockRequest, out mockWebException);
Exception exception = null;
try
{
var fb = mockFb.Object;
fb.Get(_parameters);
}
catch (Exception ex)
{
exception = ex;
}
mockFb.VerifyCreateHttpWebRequest(Times.Once());
mockRequest.VerifyGetResponse();
mockWebException.VerifyGetReponse();
Assert.IsAssignableFrom<WebExceptionWrapper>(exception);
}
In v6 we have made mocking the HttpWebRequest and HttpWebResponse much easier.
Create your custom HttpWebRequest and HttpWebResponse by inheriting HttpWebRequestWrapper and HttpWebReponseWrapper.
Then change the default http web request factory for Facebook C# SDK. Here is the sample of the default factory.
FacebookClient.SetDefaultHttpWebRequestFactory(uri => new HttpWebRequestWrapper((HttpWebRequest)WebRequest.Create(uri)));
If you want to change the HttpWebRequestFactor per FacebookClient instance then use the following code.
var fb = new FacebookClient();
fb.HttpWebRequestFactory = uri=> new MyHttpWebRequestWrapper(uri);
Note: HttpWebRequestWrapper, HttpWebResponseWrapper, WebExceptionWrapper, FacebookClient.SetDefaultHttpWebRequestFactory and FacebookClient.HttpWebRequestFactory has the attribute [EditorBrowsable(EditorBrowsableState.Never)] so you might not see it in the intellisense.
Things like no internet connection that you mention should actually be a part of facebook c# sdk tests and not your app unit tests. The sdk should guarantee that when there is not internet conenction it always throws WebExceptionWrapper and your app unit tests should actually be handling the WebExceptionWrapper exception and not mocking the entire httpwebrequest and httpwebresponse.
I'd suggest you introduce another level of abstraction to your code and code to that abstraction rather than the implementation. Eg.
public interface IFacebookClient {
IEnumerable<Friend> GetFriends();
}
public class HttpsClient : IFacebookClient {
public IEnumerable<Friend> GetFriends() {
// Make a call out to the Facebook API, as per usual
};
}
In your consuming code you'd do something like;
public class ConsumingCode {
private IFacebookClient _client;
public ConsumingCode(IFacebookClient client) {
_client = client;
foreach (Friend friend in _client.GetFriends()) {
// Do something with each Friend
}
}
}
If you're using an IoC container this can all get wired up for you automatically. MVVM frameworks like Caliburn.Micro tend to support this as well.
Then when it comes to unit testing (or manual testing) you can change the implementation of your interface;
public class Http403Client : IFacebookClient {
public IEnumerable<Friend> GetFriends() {
throw new HttpException(403, "Forbidden");
}
}
Obviously this is just a mock up example but I think it demonstrates the concept that you want to implement.