How to get Trending Tweets using twitterizer? - c#

I am looking to display the current trending tweets using Twitterizer. I am using the following code to try to generate the current trends .
public TwitterResponse<TwitterTrendCollection>
GetTrendingTweets(string
accesstoken, string accesstokensecreat, double lati, double longi)
{
OAuthTokens tokens = SetTokens(accesstoken, accesstokensecreat);
LocalTrendsOptions options = new LocalTrendsOptions();
options.UseSSL = true;
options.APIBaseAddress = "http://api.twitter.com/1.1/";
PlaceInfo p = GetWoeid(lati, longi);
AvailableTrendsOptions option = new AvailableTrendsOptions() { Lat =
lati, Long = longi };
TwitterResponse<TwitterTrendCollection> trends =
TwitterTrend.Trends(tokens, (int)p.Woeid, options);
return trends;
}

Related

How to get the status of a Comprehend Medical Job Request in C#

I am starting a Comprehend Medical Job Request using the StartEntitiesDetectionV2JobRequest function.
In the documentation it says "To get the status of a job, use this(JobId) identifier with the DescribeEntitiesDetectionV2Job operation", however there is no operation called DescribeEntitiesDetectionV2Job, only DescribeEntitiesDetectionV2JobRequest and DescribeEntitiesDetectionV2JobResponse.
How can I call DescribeEntitiesDetectionV2JobResponse (or any other function) to get the status of the job?
I was thinking something like this would work:
ComprehendMedicalAsyncJobProperties jobProperties = new ComprehendMedicalAsyncJobProperties()
{
DataAccessRoleArn = "arn:aws:iam::1129587198257:role/role_name",
InputDataConfig = input,
OutputDataConfig = output
};
DescribeEntitiesDetectionV2JobResponse requestResponse = new DescribeEntitiesDetectionV2JobResponse()
{
ComprehendMedicalAsyncJobProperties = jobProperties
};
while(requestResponse.HttpStatusCode!=(*something that would indicate that the job is completed here*))
{
Thread.Sleep(500);
}
InputDataConfig input = new InputDataConfig()
{
S3Bucket = "your_bucket_here",
S3Key = "subdirectory_name"
};
OutputDataConfig output = new OutputDataConfig()
{
S3Bucket = "your_bucket_here",
S3Key = "subdirectory_name"
};
StartEntitiesDetectionV2JobRequest request = new StartEntitiesDetectionV2JobRequest()
{
InputDataConfig = input,
JobName = "job_name_example",
LanguageCode = "en",
OutputDataConfig = output,
DataAccessRoleArn = "arn:aws:iam::12312512512:role/acces_role_name_here"
};
StartEntitiesDetectionV2JobResponse comprehendResult = comprehendClient.StartEntitiesDetectionV2JobAsync(request).GetAwaiter().GetResult();
DescribeEntitiesDetectionV2JobRequest entitiesDetectionV2JobRequest = new DescribeEntitiesDetectionV2JobRequest()
{
JobId = comprehendResult.JobId
};
DescribeEntitiesDetectionV2JobResponse comprehendResult2 = comprehendClient.DescribeEntitiesDetectionV2JobAsync(entitiesDetectionV2JobRequest).GetAwaiter().GetResult();

How to get Bitcoin Private Key from an ExtPrivKey using NBitcoin

So, I am trying to send some money over using NBitcoin, there is a step where i am failing and that is creating de bitcoin secret to sign the transaction, I have the address, and the ExtPrivKey but i haven't gotten any luck signing it, any recommendation, this is my code below.
var priv = mbwallet.SelectedWallet.PrivateKeys[0].ToWif();
//var ool = new BitcoinSecret(base58, App.Network);
var privkey = mbwallet.SelectedWallet.PrivateKeys[0].PrivateKey.GetBitcoinSecret(App.Network).ToWif();
var key = Key.Parse(privkey, App.Network);
var keysT = key.GetWif(App.Network);
//var myaddress = mbwallet.SelectedWallet.PrivateKeys[0].PrivateKey.PubKey.GetAddress(App.Network);
var myaddress = mbwallet.SelectedWallet.CurrentAddress;
string address = Address.Text;
var destination = BitcoinAddress.Create(address, App.Network);
decimal value = Convert.ToDecimal(Value.Text);
var coins2 = GetCoins(value);
TransactionBuilder txBuilder = new TransactionBuilder();
var tx = txBuilder.AddCoins(coins2)
.AddKeys(keysT)
.SetChange(myaddress)
.Send(destination, new Money(value, MoneyUnit.BTC))
.SendFees("0.0002");
//.BuildTransaction(true);
var tx2 = txBuilder.BuildTransaction(true);
//Console.WriteLine(txBuilder.Verify(tx));
var hello = tx2.ToHex();
var txRepo = new NoSqlTransactionRepository();
//txRepo.Put(tx.GetHash(), tx);
//Assert(txBuilder.Verify(tx)); //check fully signed
List<ICoin> GetCoins(decimal sendAmount)
{
//var mbwallet = (root.DataContext as MainWindowViewModel);
var amountMoney = new Money(sendAmount, MoneyUnit.BTC);
var client = new QBitNinjaClient(App.Network);
var txInAmount = Money.Zero;
var coins1 = new List<ICoin>();
foreach (var balance in client.GetBalance(mbwallet.SelectedWallet.CurrentAddress,//MBWallet.Wallet.Address,
true).Result.Operations)
{
var transactionId = balance.TransactionId;
var transactionResponse =
client.GetTransaction(transactionId).Result;
var receivedCoins = transactionResponse.ReceivedCoins;
foreach (Coin coin in receivedCoins)
{
if (coin.TxOut.ScriptPubKey ==
mbwallet.SelectedWallet.CurrentAddress.ScriptPubKey)//MBWallet.Wallet.BitcoinPrivateKey.ScriptPubKey) // this may not be necessary
{
coins1.Add(coin);
txInAmount += (coin.Amount as Money);
}
}
}
return coins1;
}
For what I see in the code you already add the private key to the builder so basically you only need to sign , something like this
Transaction signed = txBuilder.SignTransaction(tx2);

How can I retrieve all the tweets from a keyword using Tweetinvi?

I am a new C# developer and I am trying to develop an ASP.NET Webforms application to search Twitter using Tweetinvi library. I was able to search Twitter by user and phrase. However, I am struggling now with searching the tweets by phrase as it only returns a small number of tweets that is below 150 tweets and I don't know why.
I was able to retrieve more than 1700 tweets by user, but i could only get 150 tweets when I applied the same concept of code on search by phrase and I don't know why.
Kindly note that the phrase in Searching Tweets by Phrase could be any keyword, hashtag or twitter account name
Here's the C# code for searching the tweets by phrase:
private List<ITweet> GetFilteredTweets(string keyword)
{
try
{
RateLimit.RateLimitTrackerMode = RateLimitTrackerMode.TrackAndAwait;
RateLimit.QueryAwaitingForRateLimit += (se, ar) =>
{
Console.WriteLine($"Query : {ar.Query} is awaiting for rate limits!");
};
// Create a parameter for queries with specific parameters
var searchParameters = new SearchTweetsParameters(keyword)
{
Lang = LanguageFilter.English,
SearchType = SearchResultType.Mixed,
//MaximumNumberOfResults = 100,
MaximumNumberOfResults = 200,
TweetSearchType = TweetSearchType.OriginalTweetsOnly
};
var lastTweets = Tweetinvi.Search.SearchTweets(searchParameters).ToArray();
var allTweets = new List<ITweet>(lastTweets);
var beforeLast = allTweets;
while (lastTweets.Length > 0 && allTweets.Count <= 3200)
{
var idOfOldestTweet = lastTweets.Select(x => x.Id).Min();
Console.WriteLine($"Oldest Tweet Id = {idOfOldestTweet}");
var numberOfTweetsToRetrieve = allTweets.Count > 3000 ? 3200 - allTweets.Count : 200;
var searchRequestParameters = new SearchTweetsParameters(keyword)
{
Lang = LanguageFilter.English,
SearchType = SearchResultType.Mixed,
// MaxId ensures that we only get tweets that have been posted
// BEFORE the oldest tweet we received
MaxId = idOfOldestTweet - 1,
MaximumNumberOfResults = numberOfTweetsToRetrieve,
TweetSearchType = TweetSearchType.OriginalTweetsOnly
};
lastTweets = Tweetinvi.Search.SearchTweets(searchRequestParameters).ToArray();
allTweets.AddRange(lastTweets);
}
// `allTweets` now contains all the tweets that Twitter can return
tweetList = allTweets;
return allTweets;
}
catch (Exception ex)
{
throw ex;
}
}
Gets all the tweets in the last 7 days.
static public List<ITweet> GetTweets(string keyword)
{
RateLimit.RateLimitTrackerMode = RateLimitTrackerMode.TrackAndAwait;
var searchParam = new Tweetinvi.Parameters.SearchTweetsParameters(keyword)
{
MaximumNumberOfResults = 1000
};
var tweets = Tweetinvi.Search.SearchTweets(searchParam).ToList();
var tweetList = new List<ITweet>(tweets);
while (tweets.Count > 0)
{
searchParam.MaxId = tweets.Select(x => x.Id).Min() - 1;
searchParam.MaximumNumberOfResults = 5000;
tweets = Tweetinvi.Search.SearchTweets(searchParam).ToList();
tweetList.AddRange(tweets);
Console.WriteLine($"Find : {tweets.Count}");
Console.WriteLine($"All : {tweetList.Count}");
}
return tweetList;
}

Rally Api - How do I page GetByReference results

I've got some code that looks something like this.
var userStory = restApi.GetByReference (userStoryRef, "Name", "FormattedID");
for (int i = 0; i < (int) userStory["TotalResultCount"]; i++)
{
var name = userStory["Results"][i]["Name"];
...
Of course this fails if the GetByReference has more than 20 results (i.e. TotalResultCount > 20) since the default page size is 20.
So I need to page this but I can't work out how you set the page size, or request a second page from GetByReference.
I tried adding ?pagesize=100 to the reference but it doesn't appear to affect the result set.
e.g.
var userStory = restApi.GetByReference (userStoryRef + "?pagesize=100", "Name", "FormattedID");
I also tried giving up on this altogether and re-phrasing it as a query (which I do know how to page.)
e.g.
var request = new Request("HierarchicalRequirement")
{
Fetch = new List<string>()
{
"Name", "FormattedID"
}, Query = new Query("Parent.FormattedID", Query.Operator.Equals, featureId)
};
var result = myRestApi.Query(request);
But this query doesn't work for me either (featureId is a valid formatted id with associated User Stories). But that query returns no results.
(I appreciate that's a different question altogether - happy to get either working but understanding both would be fantastic!)
Grateful as ever for any help.
See code below. Notice storiesRequest.Limit = 1000 When this number is above default 20, it defaults to max 200, so there is no need to set storiesRequest.PageSize to 200
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Rally.RestApi;
using Rally.RestApi.Response;
using Rally.RestApi.Json;
namespace GetByRefExample
{
class Program
{
static void Main(string[] args)
{
RallyRestApi restApi = new RallyRestApi(webServiceVersion: "v2.0");
String apiKey = "_abc123";
restApi.Authenticate(apiKey, "https://rally1.rallydev.com", allowSSO: false);
String workspaceRef = "/workspace/123";
String projectRef = "/project/456";
Request request = new Request("PortfolioItem/Feature");
request.Fetch = new List<string>() { "Name", "FormattedID" };
request.Query = new Query("FormattedID", Query.Operator.Equals, "F2356");
QueryResult result = restApi.Query(request);
String featureRef = result.Results.First()._ref;
Console.WriteLine("found" + featureRef);
//create stories
try
{
for (int i = 1; i <= 25; i++)
{
DynamicJsonObject story = new DynamicJsonObject();
story["Name"] = "story " + i;
story["PlanEstimate"] = new Random().Next(2,10);
story["PortfolioItem"] = featureRef;
story["Project"] = projectRef;
CreateResult createResult = restApi.Create(workspaceRef, "HierarchicalRequirement", story);
story = restApi.GetByReference(createResult.Reference, "FormattedID");
Console.WriteLine("creating..." + story["FormattedID"]);
}
//read stories
DynamicJsonObject feature = restApi.GetByReference(featureRef, "UserStories");
Request storiesRequest = new Request(feature["UserStories"]);
storiesRequest.Fetch = new List<string>()
{
"FormattedID",
"PlanEstimate"
};
storiesRequest.Limit = 1000;
QueryResult storiesResult = restApi.Query(storiesRequest);
int storyCount = 0;
foreach (var userStory in storiesResult.Results)
{
Console.WriteLine(userStory["FormattedID"] + " " + userStory["PlanEstimate"]);
storyCount++;
}
Console.WriteLine(storyCount);
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
}
}

Query for All Invoices With Open Balances using QuickBooks Online (QBO) Intuit Partner Platform (IPP) DevKit

I am trying to Query for all invoices with open balances using IPP but I keep on getting 0 results back. Am I doing something wrong in code?
Here is my C# code snippet that I am trying to do with the applied Filtering
InvoiceQuery qboInvoiceQuery = new InvoiceQuery();
int iMaxPageNumber = QUERY_MAX_PAGE_NUMBER; // A Constant with the Maximum Page Number allowed in a query
int iResultsPerPage = QUERY_MAX_NUM_PER_PAGE_INVOICE; // A Constant with the Maximum Results per page
// Paging Information
qboInvoiceQuery.PageNumber = QUERY_START_PAGE_NUMBER;
qboInvoiceQuery.ResultsPerPage = iResultsPerPage;
#region Query Filtering
//////////////////////////////////////////////
// initial filtering via Query Criteria //
//////////////////////////////////////////////
// Get only Open (Unpaid) Invoices
qboInvoiceQuery.OpenBalance = (decimal)0.00;
qboInvoiceQuery.SpecifyOperatorOption(FilterProperty.OpenBalance, FilterOperatorType.AFTER);
//////////////////////////////////////////////
// END initial filtering via Query Criteria //
//////////////////////////////////////////////
#endregion
// Complete the Query calls to build the list
IEnumerable<Invoice> results = qboInvoiceQuery.ExecuteQuery<Invoice>(_ServiceContext);
IEnumerable<Invoice> qboInvoices = results;
int iCount = results.Count();
while (iCount > 0 && iCount == iResultsPerPage && qboInvoiceQuery.PageNumber <= iMaxPageNumber)
{
qboInvoiceQuery.PageNumber++;
results = qboInvoiceQuery.ExecuteQuery<Invoice>(_ServiceContext);
iCount = results.Count();
qboInvoices = qboInvoices.Concat(results);
}
*** UPDATE ***
I have implemented peterl's answer and now have the following code. However I am now running into a new problem that my code is always returning the default of 10 invoices and is not taking into consideration my body. Even if i set it to a different page number or ResultsPerPage value I was get back the first page and 10 results. Any ideas?
private Dictionary<string, Invoice> GetUnpaidInvoicesDictionary(IdType CustomerId, bool bById = true)
{
Dictionary<string, Invoice> dictionary = new Dictionary<string, Invoice>();
int iMaxPageNumber = 100;
int iResultsPerPage = 100;
try
{
OAuthConsumerContext consumerContext = new OAuthConsumerContext
{
ConsumerKey = _sConsumerKey,
SignatureMethod = SignatureMethod.HmacSha1,
ConsumerSecret = _sConsumerSecret
};
string sBaseURL = "https://oauth.intuit.com/oauth/v1";
string sUrlRequestToken = "/get_request_token";
string sUrlAccessToken = "/get_access_token";
OAuthSession oSession = new OAuthSession(consumerContext,
sBaseURL + sUrlRequestToken,
sBaseURL,
sBaseURL + sUrlAccessToken);
oSession.AccessToken = new TokenBase
{
Token = _sAccessToken,
ConsumerKey = _sConsumerKey,
TokenSecret = _sAccessTokenSecret
};
int iPageNumber = QUERY_START_PAGE_NUMBER;
string sCustomerId = CustomerId.Value;
string sBodyBase = "PageNum={0}&ResultsPerPage={1}&Filter=OpenBalance :GreaterThan: 0.00 :AND: CustomerId :EQUALS: {2}";
string sBody = String.Format(sBodyBase, iPageNumber, iResultsPerPage, sCustomerId);
IConsumerRequest conReq = oSession.Request();
conReq = conReq.Post().WithRawContentType("application/x-www-form-urlencoded").WithRawContent(System.Text.Encoding.ASCII.GetBytes(sBody)); ;
conReq = conReq.ForUrl(_DataService.ServiceContext.BaseUrl + "invoices/v2/" + _DataService.ServiceContext.RealmId);
conReq = conReq.SignWithToken();
// Complete the Query calls to build the list
SearchResults searchResults = (SearchResults)_DataService.ServiceContext.Serializer.Deserialize<SearchResults>(conReq.ReadBody());
IEnumerable<Invoice> results = ((Invoices)searchResults.CdmCollections).Invoice;
IEnumerable<Invoice> qboInvoices = results;
int iCount = searchResults.Count;
while (iCount > 0 && iCount == iResultsPerPage && iPageNumber <= iMaxPageNumber)
{
iPageNumber++;
sBody = String.Format(sBodyBase, iPageNumber, iResultsPerPage, sCustomerId);
conReq = oSession.Request();
conReq = conReq.Post().WithRawContentType("application/x-www-form-urlencoded").WithRawContent(System.Text.Encoding.ASCII.GetBytes(sBody)); ;
conReq = conReq.ForUrl(_DataService.ServiceContext.BaseUrl + "invoices/v2/" + _DataService.ServiceContext.RealmId);
conReq = conReq.SignWithToken();
searchResults = (SearchResults)_DataService.ServiceContext.Serializer.Deserialize<SearchResults>(conReq.ReadBody());
results = ((Invoices)searchResults.CdmCollections).Invoice;
qboInvoices = qboInvoices.Concat(results);
iCount = searchResults.Count;
}
if (bById)
foreach (Invoice Inv in qboInvoices)
dictionary.Add(Inv.Id.Value, Inv);
else
foreach (Invoice Inv in qboInvoices)
dictionary.Add(Inv.Header.DocNumber, Inv);
return dictionary;
}
catch (Exception)
{
return null;
}
}
* UPDATE *
There is a similar issue out there that involves the new api tester. This could be related to this issue and they are currently looking into it.
Stack Overflow: QuickBooks Online querying with filter returns 401 everytime
This is a bug in the DevKit. The OpenBalance filter defaults to :EQUALS: and does not support :GreaterThan:.
https://ipp.developer.intuit.com/0010_Intuit_Partner_Platform/0050_Data_Services/0400_QuickBooks_Online/Invoice#Attributes_Supporting_Filtering_and_Sorting
Here is a workaround using DevDefined to construct the OAuth header:
public List<Intuit.Ipp.Data.Qbo.Invoice> GetQboUnpaidInvoices(DataServices dataServices, int startPage, int resultsPerPage, IdType CustomerId)
{
StringBuilder requestXML = new StringBuilder();
StringBuilder responseXML = new StringBuilder();
var requestBody = String.Format("PageNum={0}&ResultsPerPage={1}&Filter=OpenBalance :GreaterThan: 0.00 :AND: CustomerId :EQUALS: {2}", startPage, resultsPerPage, CustomerId.Value);
HttpWebRequest httpWebRequest = WebRequest.Create(dataServices.ServiceContext.BaseUrl + "invoices/v2/" + dataServices.ServiceContext.RealmId) as HttpWebRequest;
httpWebRequest.Method = "POST";
httpWebRequest.ContentType = "application/x-www-form-urlencoded";
httpWebRequest.Headers.Add("Authorization", GetDevDefinedOAuthHeader(httpWebRequest, requestBody));
requestXML.Append(requestBody);
UTF8Encoding encoding = new UTF8Encoding();
byte[] content = encoding.GetBytes(requestXML.ToString());
using (var stream = httpWebRequest.GetRequestStream())
{
stream.Write(content, 0, content.Length);
}
HttpWebResponse httpWebResponse = httpWebRequest.GetResponse() as HttpWebResponse;
using (Stream data = httpWebResponse.GetResponseStream())
{
Intuit.Ipp.Data.Qbo.SearchResults searchResults = (Intuit.Ipp.Data.Qbo.SearchResults)dataServices.ServiceContext.Serializer.Deserialize<Intuit.Ipp.Data.Qbo.SearchResults>(new StreamReader(data).ReadToEnd());
return ((Intuit.Ipp.Data.Qbo.Invoices)searchResults.CdmCollections).Invoice.ToList();
}
}
protected string GetDevDefinedOAuthHeader(HttpWebRequest webRequest, string requestBody)
{
OAuthConsumerContext consumerContext = new OAuthConsumerContext
{
ConsumerKey = consumerKey,
ConsumerSecret = consumerSecret,
SignatureMethod = SignatureMethod.HmacSha1,
UseHeaderForOAuthParameters = true
};
consumerContext.UseHeaderForOAuthParameters = true;
//URIs not used - we already have Oauth tokens
OAuthSession oSession = new OAuthSession(consumerContext, "https://www.example.com",
"https://www.example.com",
"https://www.example.com");
oSession.AccessToken = new TokenBase
{
Token = accessToken,
ConsumerKey = consumerKey,
TokenSecret = accessTokenSecret
};
IConsumerRequest consumerRequest = oSession.Request();
consumerRequest = ConsumerRequestExtensions.ForMethod(consumerRequest, webRequest.Method);
consumerRequest = ConsumerRequestExtensions.ForUri(consumerRequest, webRequest.RequestUri);
if (webRequest.Headers.Count > 0)
{
ConsumerRequestExtensions.AlterContext(consumerRequest, context => context.Headers = webRequest.Headers);
if (webRequest.Headers[HttpRequestHeader.ContentType] == "application/x-www-form-urlencoded")
{
Dictionary<string, string> formParameters = new Dictionary<string, string>();
foreach (string formParameter in requestBody.Split('&'))
{
formParameters.Add(formParameter.Split('=')[0], formParameter.Split('=')[1]);
}
consumerRequest = consumerRequest.WithFormParameters(formParameters);
}
}
consumerRequest = consumerRequest.SignWithToken();
return consumerRequest.Context.GenerateOAuthParametersForHeader();
}
http://nuget.org/packages/DevDefined.OAuth

Categories