I can able to upload single offline conversion to my adwords account through API.But I want to upload bulk conversions through API. Is there any way to upload bulk conversions in single API call. I am using v201402 adwords client library.
You could use the "MutateJobService" for this. This exactly serves your purpose
Here's the link:
https://developers.google.com/adwords/api/docs/reference/v201402/MutateJobService
https://developers.google.com/adwords/api/docs/guides/importing-conversions
Here is my c# code
public OfflineConversionFeedReturnValue UploadOfflineConversionsToExistingConversionType(List<OfflineConversionFeed> offlineConversions)
{
try
{
// Get the OfflineConversionFeedService.
OfflineConversionFeedService offlineConversionFeedService =
(OfflineConversionFeedService)User.GetService(
AdWordsService.v201509.OfflineConversionFeedService);
List<OfflineConversionFeedOperation> offlineConversionOperations = new List<OfflineConversionFeedOperation>();
foreach (OfflineConversionFeed conversion in offlineConversions)
{
OfflineConversionFeedOperation offlineConversionOperation =
new OfflineConversionFeedOperation();
offlineConversionOperation.#operator = Operator.ADD;
offlineConversionOperation.operand = conversion;
offlineConversionOperations.Add(offlineConversionOperation);
}
OfflineConversionFeedReturnValue offlineConversionRetval =
offlineConversionFeedService.mutate(offlineConversionOperations.ToArray());
return offlineConversionRetval;
}
catch (Exception e)
{
throw new System.ApplicationException("Failed upload offline conversions.", e);
}
}
Related
Calling a .net core based webapi from Twilio flow fails due to the fact that, because the underlying call of the webapi to Microsoft cognitive service lasts more than 5 seconds. any idea on how to make the call perform faster?
I have created a .net core based WebAPI controller that generates mp3 file that is generated by Microsoft Cognitive speech-to-text service. working great.
However, when calling it from a Twilio flow, the flow fails due to the fact that the tts service takes about more than 5 seconds to complete. The first phase - getting an access token from MS takes about 2.5 seconds, and than the tts itself takes about 3 seconds. 5 seconds is the maximum that Twilio allows for a call to return, so it fails.
any idea on how to manage the Cognitive service access token (valid for 10 minutes, by Microsoft) so it will be regenerated in parallel, so I won't have to spend 2.5 seconds every call?
I can't use Twilio's text-to-speech service since Twilio do not support Hebrew (they support Hebrew only for speech-to-text).
public class AzureSSAuthentication
{
public string subscriptionKey;
private string tokenFetchUri;
public AzureSSAuthentication(string tokenFetchUri, string subscriptionKey)
{
if (string.IsNullOrWhiteSpace(tokenFetchUri))
{
throw new ArgumentNullException(nameof(tokenFetchUri));
}
if (string.IsNullOrWhiteSpace(subscriptionKey))
{
throw new ArgumentNullException(nameof(subscriptionKey));
}
this.tokenFetchUri = tokenFetchUri;
this.subscriptionKey = subscriptionKey;
}
public async Task<string> FetchTokenAsync()
{
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", this.subscriptionKey);
UriBuilder uriBuilder = new UriBuilder(this.tokenFetchUri);
var result = await client.PostAsync(uriBuilder.Uri.AbsoluteUri, null).ConfigureAwait(false);
return await result.Content.ReadAsStringAsync().ConfigureAwait(false);
}
}
}
/////////////// Controller
[Route("api/[controller]")]
public class TTSController : Controller
{
// GET api/values/SomethingToSay
[HttpGet("{text}")]
[Route("Say")]
public async Task<FileContentResult> Get(string text)
{
string accessToken;
AzureSSAuthentication auth = new AzureSSAuthentication("https://westeurope.api.cognitive.microsoft.com/sts/v1.0/issuetoken", "<MyToken>");
//try
//{
accessToken = await auth.FetchTokenAsync().ConfigureAwait(false);
string host = "https://westeurope.tts.speech.microsoft.com/cognitiveservices/v1";
string body = #"<speak version='1.0' xmlns='https://www.w3.org/2001/10/synthesis' xml:lang='he-IL'>" +
"<voice name='Microsoft Server Speech Text to Speech Voice (he-IL, Asaf)'>" +
text + "</voice></speak>";
using (var client = new HttpClient())
{
using (var request = new HttpRequestMessage())
{
// Set the HTTP method
request.Method = HttpMethod.Post;
request.RequestUri = new Uri(host);
request.Content = new StringContent(body, Encoding.UTF8, "application/ssml+xml");
request.Headers.Add("Authorization", "Bearer " + accessToken);
request.Headers.Add("Connection", "Keep-Alive");
request.Headers.Add("User-Agent", "sayWhat");
request.Headers.Add("X-Microsoft-OutputFormat", "riff-24khz-16bit-mono-pcm");
using (var response = await client.SendAsync(request).ConfigureAwait(false))
{
response.EnsureSuccessStatusCode();
// Asynchronously read the response
using (var dataStream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false))
{
byte[] dataByteArray = new byte[dataStream.Length];
dataStream.Read(dataByteArray, 0, (int)dataStream.Length);
return File(dataByteArray, "audio/mpeg", "audio.mp3");
}
}
}
}
//}
//catch (Exception ex)
//{
// return BadRequest(ex.Message);
//}
}
}
It just takes too long.
I am looking at doing something very similar and I am concerned about the time for the MS services also. I am also dealing with text-to-speech. The flow I was considering was to call the MS Cognitive services prior to call and temporarily store the MP3. Once the call is complete, delete the MP3 file. This way you already have the MP3 file prior to the even making the call.
I am trying for a while now to implement this flow: When user adds some files on server app, notification should trigger and send from server to FCM and that from there to pass message saying something like: 'New file has been added'.
Basically I want to inform mobile device user that something on server has been changed.
I have tried many things, but nothing seems to work as I would expect, at least.
On the mobile side I have set up Firebase inside my Xamarin.Android project, and when I am sending notifications directly from Firebase console, I get notifications, and everything is good.
But I don't want to send notifications via Firebase console, I would rather send notification from server (which is ASP.NET MVC project) to Firebase console and then pass it from there to android device.
My first question would be: Has anybody got an idea how can I inform web app about device_id? Is there some way that android device send this information on server? And maybe from there I can store that data and update it occasionally, since it is basically a refresh token.
My second problem is this: Even when I hard code current device_id of an active android device and try to send a message from server whit this code:
public class FirebaseService : IFirebaseService
{
public void SendMessageToClientApplication(string message, string serverApiKey, string senderId, string deviceId)
{
AndroidFCMPushNotificationStatus result = new AndroidFCMPushNotificationStatus();
try
{
result.Successful = false;
result.Error = null;
deviceId = "eMk6mD8P8Dc:APA91bG5Lmqn4Hwb4RZJ1Mkdl8Rf_uYQsQCEfDJK334tzSvIGzdao7o2X6VmtcTEp_Li0mG8iUoUT7-_RnZxQKocHosZwx6ITWdpmQyCwUv60IIIy0vxNlEaccT6RqK6c-cE1C6I3FTT";
var value = message;
WebRequest tRequest = WebRequest.Create("https://fcm.googleapis.com/fcm/send");
tRequest.Method = "post";
tRequest.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";
tRequest.Headers.Add(string.Format("Authorization: key={0}", serverApiKey));
tRequest.Headers.Add(string.Format("Sender: id={0}", senderId));
string postData = "collapse_key=score_update&time_to_live=108&delay_while_idle=1&data.message="
+ value + "&data.time=" + DateTime.Now.ToString() + "®istration_id=" + deviceId + "";
Byte[] byteArray = Encoding.UTF8.GetBytes(postData);
tRequest.ContentLength = byteArray.Length;
using (Stream dataStream = tRequest.GetRequestStream())
{
dataStream.Write(byteArray, 0, byteArray.Length);
using (WebResponse tResponse = tRequest.GetResponse())
{
using (Stream dataStreamResponse = tResponse.GetResponseStream())
{
using (StreamReader tReader = new StreamReader(dataStreamResponse))
{
String sResponseFromServer = tReader.ReadToEnd();
result.Response = sResponseFromServer;
}
}
}
}
}
catch (Exception ex)
{
result.Successful = false;
result.Response = null;
result.Error = ex;
}
}
}
I get nothing both in Firebase console and of course nothing on device as well.
I have tried to implement Firebase web as javascript on my server app like this:
<script>
var config = {
apiKey: "mykey",
authDomain: "myauthdomain",
databaseURL: "mydatabaseurl",
projectId: "myprojectid",
storageBucket: "mystoragebucket",
messagingSenderId: "mysenderid"
};
window.onload = function () {
firebase.initializeApp(config);
const messaging = firebase.messaging();
messaging.requestPermission()
.then(function () {
console.log('Notification permission granted.');
return messaging.getToken()
})
.then(function (token) {
console.log(token);
})
.catch(function (err) {
console.log('Unable to get permission to notify.', err);
});
messaging.onMessage(function (payload) {
console.log('onMessage: ', payload);
});
}
</script>
But this code gets some kind of a different device_id(aka token), probably one generated for that server machine.
Does anybody has experience with sending device_id to server app and from there sending notification message to Firebase console? I would appreciate some code examples, tutorials or anything that can help, since I was unable to find something useful during my google search.
My first question would be: Has anybody got an idea how can I inform web app about device_id?
The most common approach is to store the list of device tokens (each device that uses FCM has such a token) in a database, such as the Firebase Database. There is an example of this in the Cloud Functions for Firebase documentation. In this example the devices receiving the messages are web pages, but the approach is the same for iOS and Android.
I also recommend reading Sending notifications between Android devices with Firebase Database and Cloud Messaging. In this article, instead of sending to a device token, each user subscribes to a topic. That prevents having to manage the device tokens in your code.
When uploading videos to YouTube using the YouTube api v3, I get the following error:
Google.Apis.Requests.RequestError
Access forbidden. The request may not be properly authorized. [403]
Errors [
Message[Access forbidden. The request may not be properly authorized.] Location[ - ] Reason[forbidden] Domain[youtube.common]
]
The app will successfully upload a couple videos, then randomly throws this 403 error.
The quota limit is 1 millon queries per day, I have only used about 1%.
There are approximately 1200 videos already on the channel that were uploaded using the same app, now all of a sudden in the last few days I am getting this error. I've tried uploading videos to another channel and had no problems, so it looks as though the issue is specific to this one channel. Seems as though it's being throttled, but I don't know why?
I have not contravened any terms of service, the videos are original, the account is in good standing and I'm within the quota limit.
If there are any other limits, why does Google not document it in the api refrence? That way we can design our apps according to policy.
It makes it impossible to build an app if you follow spec and then Google have a different set of rules on the backend and you are left guessing what you are and aren't allowed to do.
Using this code:
using System;
using System.IO;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Services;
using Google.Apis.Upload;
using Google.Apis.Util.Store;
using Google.Apis.YouTube.v3;
using Google.Apis.YouTube.v3.Data;
namespace Google.Apis.YouTube.Samples
{
/// <summary>
/// YouTube Data API v3 sample: upload a video.
/// Relies on the Google APIs Client Library for .NET, v1.7.0 or higher.
/// See https://developers.google.com/api-client-library/dotnet/get_started
/// </summary>
internal class UploadVideo
{
[STAThread]
static void Main(string[] args)
{
Console.WriteLine("YouTube Data API: Upload Video");
Console.WriteLine("==============================");
try
{
new UploadVideo().Run().Wait();
}
catch (AggregateException ex)
{
foreach (var e in ex.InnerExceptions)
{
Console.WriteLine("Error: " + e.Message);
}
}
Console.WriteLine("Press any key to continue...");
Console.ReadKey();
}
private async Task Run()
{
UserCredential credential;
using (var stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read))
{
credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
// This OAuth 2.0 access scope allows an application to upload files to the
// authenticated user's YouTube channel, but doesn't allow other types of access.
new[] { YouTubeService.Scope.YoutubeUpload },
"user",
CancellationToken.None
);
}
var youtubeService = new YouTubeService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = Assembly.GetExecutingAssembly().GetName().Name
});
var video = new Video();
video.Snippet = new VideoSnippet();
video.Snippet.Title = "Default Video Title";
video.Snippet.Description = "Default Video Description";
video.Snippet.Tags = new string[] { "tag1", "tag2" };
video.Snippet.CategoryId = "22"; // See https://developers.google.com/youtube/v3/docs/videoCategories/list
video.Status = new VideoStatus();
video.Status.PrivacyStatus = "unlisted"; // or "private" or "public"
var filePath = #"REPLACE_ME.mp4"; // Replace with path to actual movie file.
using (var fileStream = new FileStream(filePath, FileMode.Open))
{
var videosInsertRequest = youtubeService.Videos.Insert(video, "snippet,status", fileStream, "video/*");
videosInsertRequest.ProgressChanged += videosInsertRequest_ProgressChanged;
videosInsertRequest.ResponseReceived += videosInsertRequest_ResponseReceived;
await videosInsertRequest.UploadAsync();
}
}
void videosInsertRequest_ProgressChanged(Google.Apis.Upload.IUploadProgress progress)
{
switch (progress.Status)
{
case UploadStatus.Uploading:
Console.WriteLine("{0} bytes sent.", progress.BytesSent);
break;
case UploadStatus.Failed:
Console.WriteLine("An error prevented the upload from completing.\n{0}", progress.Exception);
break;
}
}
void videosInsertRequest_ResponseReceived(Video video)
{
Console.WriteLine("Video id '{0}' was successfully uploaded.", video.Id);
}
}
}
I have a list of tweets with information about the user who tweeted them that I am using for an undergrad research project. To build a social network graph of these tweets I need to grab their friend and follower lists. I have tried using the GET Follower IDs call through the twitter4j platform. My authentication is Oauth with Read, write, and direct messages. I get a 400 response code with no further error code. I also get the following exception code
exceptionCode=[92c30ec6-19bed99c 70a5018f-1e1c55ac 70a5018f-1e1c55aa], statusCode=-1, message=null, code=-1, retryAfter=-1, rateLimitStatus=null, version=3.0.3}
This tells me that I'm not authenticated to make this request which from what I have read is because the people are not followers of mine. Is there a way I can request this information without having this relationship with the user?
here is my code
public static void main (String[] args){
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true)
.setOAuthConsumerKey("something")
.setOAuthConsumerSecret("something else")
.setOAuthAccessToken("another thing")
.setOAuthAccessTokenSecret("a secret thing")
.setUseSSL(true)
.setUserStreamRepliesAllEnabled(true);
Twitter twitter = new TwitterFactory(cb.build()).getInstance();
long cursor = -1;
IDs ids = null;
String[] users = new String[16717];
BufferedReader br = null;
try {//getting user screen names
String sCurrentLine;
br = new BufferedReader(new FileReader("users.txt"));
int i = 0;
while ((sCurrentLine = br.readLine()) != null) {
users[i]=sCurrentLine;
i++;
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
for(int i=0;i<users.length;i++){
System.out.println("==================="+users[i]+"===================");
do {
try {
ids = twitter.getFollowersIDs(users[i], cursor);
for (long id : ids.getIDs()) {
System.out.println(id);
User user = twitter.showUser(id);
System.out.println(user.getName());
}
} catch (TwitterException e) {
e.printStackTrace();
}
} while ((cursor = ids.getNextCursor()) != 0);
}
}
One can obtain the list of followers IDs for any public twitter user using this API from twitter. I don't use twitter4j but it should work fine.
Main thing to be conscious of, outside of authentication, is that twitter allows fetching maximum 5000 IDs in one call and rate limits aggressively (15 calls per app/user token) so your application has to be designed and built to honor those considerations/limitations with appropriate tokens/sleeps etc.
For e.g. if you use the application token and a given user has 100K followers, twitter will start returning rate_limit_exceeded errors after fetching 75K (5K * 15) followers IDs.
In an extremely embarrassing turn of events it turns out that the reason the request could not be made is that the usernames I was searching with had an extra space. So I trimmed each name and it works now.
I am developing one application in that i have contact details ,when i click the contact number it will ask some option like call or sms or add to phone contact. I implemented call and sms, But when am trying to implement add number ,name ,email in to the phone contact am getting struggle. the below code am used for add contact
try
{
ContactList contacts = null;
try {
contacts = (ContactList) PIM.getInstance().openPIMList(PIM.CONTACT_LIST, PIM.READ_WRITE);
} catch (PIMException e) {
// An error occurred
return;
}
Contact contact = contacts.createContact();
String[] name = new String[ contacts.stringArraySize( Contact.NAME) ];
name[Contact.NAME_GIVEN] = "Kate";
name[Contact.NAME_FAMILY] = "Turner";
contact.addStringArray(Contact.NAME, Contact.ATTR_NONE,name);
contact.addString(Contact.EMAIL, Contact.ATTR_NONE, emailAddressTo);
contact.addString(Contact.TEL,Contact.ATTR_NONE,"6776787"//this for voice call number.
AddressBookArguments entry = new AddressBookArguments(AddressBookArguments.ARG_NEW, contact);
Invoke.invokeApplication(Invoke.APP_TYPE_ADDRESSBOOK, entry);
}
catch (Throwable t)
{
}
}
This above code work fine but when am trying to add mobile number like this
contact.addString(Contact.ATTR_MOBILE,Contact.ATTR_NONE,"mobile Number");
am getting exception Illegal argument Exception, I don't know how to add the mobile number here,Can anyone help me to solve this?
You can do like this,
if (contacts.isSupportedField(Contact.TEL)) {
contact.addString(Contact.TEL, Contact.ATTR_MOBILE, "1234567890");
}
See this IBM developerWorks article for more info:
Develop mobile apps with Personal Information Management