Add a reminder to Android calendar in xamarin - xamarin.android

I am adding a reminder to a calendar entry. i am using this piece of code,
ContentValues eventValues = new ContentValues();
eventValues.Put(CalendarContract.Events.InterfaceConsts.CalendarId, _calId);
eventValues.Put(CalendarContract.Events.InterfaceConsts.Title, "Test Event");
eventValues.Put(CalendarContract.Events.InterfaceConsts.Description, "This is an event created for demo app");
eventValues.Put(CalendarContract.Events.InterfaceConsts.Dtstart, GetDateTimeMS(DateTime.Today, DateTime.Now));
eventValues.Put(CalendarContract.Events.InterfaceConsts.Dtend, GetDateTimeMS(DateTime.Today.AddDays(1), DateTime.Now));
eventValues.Put(CalendarContract.Events.InterfaceConsts.HasAlarm, true);
eventValues.Put(CalendarContract.Events.InterfaceConsts.EventTimezone, "Local");
eventValues.Put(CalendarContract.Events.InterfaceConsts.EventEndTimezone, "Local");
var eventUri = ContentResolver.Insert(CalendarContract.Events.ContentUri,
eventValues);
long eventID = long.Parse(eventUri.LastPathSegment);
string reminderUriString = "content://com.android.calendar/reminders";
ContentValues reminderValues = new ContentValues();
// reminderValues.Put(CalendarContract.Reminders.InterfaceConsts.CalendarId, _calId);
reminderValues.Put(CalendarContract.Reminders.InterfaceConsts.EventId, eventID);
reminderValues.Put(CalendarContract.Reminders.InterfaceConsts.Method, RemindersMethod.Alert.ToString());
reminderValues.Put(CalendarContract.Reminders.InterfaceConsts.Minutes, 5);
Android.Net.Uri url = Android.Net.Uri.Parse(reminderUriString);
var reminderUri = ContentResolver.Insert(url, reminderValues);
this doesnt give any exception but does not add the reminder either. what is wrong? How do i add reminder?i do have write permission. I am able to add calendar events but not able to add reminders

RemindersMethod is an enum, so you need to cast it to an int.
So change your code for adding Reminder method to:
remindersValues.Put(
CalendarContract.Reminders.InterfaceConsts.Method,
(int) RemindersMethod.Alert
);

Related

Graph API bug changing recurrence from "noEnd" to "numbered"

I have an event in Outlook with an attendee that uses Google calendar. When I change the event recurrence range type using the graph API from "noEnd" to "numbered", the google attendee's event does not get updated.
Here is the code I am using to set the recurrence as "noEnd":
public async System.Threading.Tasks.Task SetDailyRecurrenceForever(string ExternalID, string CalendarRefreshToken)
{
var tmpEvent = new Microsoft.Graph.Event
{
Recurrence = new PatternedRecurrence
{
Pattern = new RecurrencePattern
{
Type = RecurrencePatternType.Daily,
Interval = 1,
FirstDayOfWeek = Microsoft.Graph.DayOfWeek.Sunday,
Index = WeekIndex.First
},
Range = new RecurrenceRange
{
Type = RecurrenceRangeType.NoEnd,
StartDate = new Microsoft.Graph.Date(2020,10,6),
RecurrenceTimeZone = "Central Standard Time",
NumberOfOccurrences = 0
}
}
};
var graphClient = await MicrosoftAuthenticationProvider.GetGraphClient(CALENDAR_CLIENT_ID, CALENDAR_CLIENT_SECRET, CALENDAR_REDIRECT_URI, CALENDAR_ACCESS_SCOPES, CalendarRefreshToken)
.ConfigureAwait(false);
await graphClient.Me.Events[ExternalID]
.Request()
.UpdateAsync(tmpEvent)
.ConfigureAwait(false);
}
Here is the code I am using to set the recurrence as "numbered":
public async System.Threading.Tasks.Task SetDailyRecurrenceForFiveDays(string ExternalID, string CalendarRefreshToken)
{
var tmpEvent = new Microsoft.Graph.Event
{
Recurrence = new PatternedRecurrence
{
Pattern = new RecurrencePattern
{
Type = RecurrencePatternType.Daily,
Interval = 1,
FirstDayOfWeek = Microsoft.Graph.DayOfWeek.Sunday,
Index = WeekIndex.First
},
Range = new RecurrenceRange
{
Type = RecurrenceRangeType.Numbered,
StartDate = new Microsoft.Graph.Date(2020, 10, 6),
RecurrenceTimeZone = "Central Standard Time",
NumberOfOccurrences = 5
}
}
};
var graphClient = await MicrosoftAuthenticationProvider.GetGraphClient(CALENDAR_CLIENT_ID, CALENDAR_CLIENT_SECRET, CALENDAR_REDIRECT_URI, CALENDAR_ACCESS_SCOPES, CalendarRefreshToken)
.ConfigureAwait(false);
await graphClient.Me.Events[ExternalID]
.Request()
.UpdateAsync(tmpEvent)
.ConfigureAwait(false);
}
The bug is also repeatable by sending a PATCH using the graph explorer:
https://graph.microsoft.com/v1.0/me/events/{ID}
Update the event as "noEnd":
{"recurrence":{"pattern":{"type":"daily","interval":1,"month":0,"dayOfMonth":0,"firstDayOfWeek":"sunday","index":"first"},"range":{"type":"noEnd","startDate":"2020-10-06","endDate":"0001-01-01","recurrenceTimeZone":"Central Standard Time","numberOfOccurrences":0}}}
Update the event as "numbered":
{"recurrence":{"pattern":{"type":"daily","interval":1,"month":0,"dayOfMonth":0,"firstDayOfWeek":"sunday","index":"first"},"range":{"type":"numbered","startDate":"2020-10-06","endDate":"0001-01-01","recurrenceTimeZone":"Central Standard Time","numberOfOccurrences":5}}}
The following video displays the behavior the google attendee is experiencing:
https://www.screencast.com/t/uhwovvZf
Note: At the end of the video I show that switching the interval to 2 will cause the google event to be updated properly, so this is specifically a problem when the interval is 1.
Is this a known bug? Does anyone have a work-around for it?

Display contact address in ios using xamarin

absolute beginner with xamarin.
Followed the following tutorial to try and simply click a button to display the contact list, select a contact, and then to display firstname, surname, and address on the screen.
https://github.com/xamarin/recipes/tree/master/Recipes/ios/shared_resources/contacts/choose_a_contact
Managed to get the firstname and surname to be displayed, but cannot get the address. Constantly getting the error
Foundation.MonoTouchException: Objective-C exception thrown. Name: CNPropertyNotFetchedException Reason: A property was not requested when contact was fetched.
On the
contanct.PostalAddresses
This is the snippet of code:-
partial void UIButton197_TouchUpInside(UIButton sender)
{
// Create a new picker
var picker = new CNContactPickerViewController();
// Select property to pick
picker.DisplayedPropertyKeys = new NSString[] { CNContactKey.GivenName, CNContactKey.FamilyName, CNContactKey.PostalAddresses };
// Respond to selection
var pickerDelegate = new ContactPickerDelegate();
picker.Delegate = pickerDelegate;
pickerDelegate.SelectionCanceled += () => {
SelectedContact1.Text = "";
};
pickerDelegate.ContactSelected += (contact) => {
SelectedContact1.Text = contact.GivenName;
SelectedContact2.Text = contact.FamilyName;
SelectedContact3.Text = contact.PostalAddresses
};
pickerDelegate.ContactPropertySelected += (property) => {
SelectedContact1.Text = property.Value.ToString();
};
// Display picker
PresentViewController(picker, true, null);
}
Am i missing something?
Seem to have resolved this if anyone else is having a similar issue.
The solution was to completely close down visual studio on the mac and re-open it.
Originally, i was stopping the project, and re-building. Possibly a bug, but non of my changes where being picked up.
A simple re-start kicked it back in

Retrieve TextAd using Adwords Api

I'm trying to retrieve TextAd (Headline,Desc1,Desc2,Display URL and Destination URL) and i failed.
This is my Code on retrieving Text ad it returns Null result
TextAd text = new TextAd();
System.out.println("Headline:"+text.getHeadline());
Syso... etc.
I want to retrieve All details of TextAd , I'm using java.
This is my the code for adding TextAd
public static void runExample(
AdWordsServices adWordsServices, AdWordsSession session, long adGroupId) throws Exception {
// Get the AdGroupAdService.
AdGroupAdServiceInterface adGroupAdService =
adWordsServices.get(session, AdGroupAdServiceInterface.class);
// Create text ads.
TextAd textAd1 = new TextAd();
textAd1.setHeadline("Luxury Cruise to Mars");
textAd1.setDescription1("Visit the Red Planet in style.");
textAd1.setDescription2("Low-gravity fun for everyone!");
textAd1.setDisplayUrl("www.example.com");
textAd1.setFinalUrls(new String[] {"http://www.example.com/1"});
TextAd textAd2 = new TextAd();
textAd2.setHeadline("Luxury Cruise to Mars");
textAd2.setDescription1("Enjoy your stay at Red Planet.");
textAd2.setDescription2("Buy your tickets now!");
textAd2.setDisplayUrl("www.example.com");
textAd2.setFinalUrls(new String[] {"http://www.example.com/2"});
// Create ad group ad.
AdGroupAd textAdGroupAd1 = new AdGroupAd();
textAdGroupAd1.setAdGroupId(adGroupId);
textAdGroupAd1.setAd(textAd1);
// You can optionally provide these field(s).
textAdGroupAd1.setStatus(AdGroupAdStatus.PAUSED);
AdGroupAd textAdGroupAd2 = new AdGroupAd();
textAdGroupAd2.setAdGroupId(adGroupId);
textAdGroupAd2.setAd(textAd2);
// Create operations.
AdGroupAdOperation textAdGroupAdOperation1 = new AdGroupAdOperation();
textAdGroupAdOperation1.setOperand(textAdGroupAd1);
textAdGroupAdOperation1.setOperator(Operator.ADD);
AdGroupAdOperation textAdGroupAdOperation2 = new AdGroupAdOperation();
textAdGroupAdOperation2.setOperand(textAdGroupAd2);
textAdGroupAdOperation2.setOperator(Operator.ADD);
AdGroupAdOperation[] operations =
new AdGroupAdOperation[] {textAdGroupAdOperation1, textAdGroupAdOperation2};
// Add ads.
AdGroupAdReturnValue result = adGroupAdService.mutate(operations);
// Display ads.
for (AdGroupAd adGroupAdResult : result.getValue()) {
System.out.println("Ad with id \"" + adGroupAdResult.getAd().getId() + "\"" + " and type \""
+ adGroupAdResult.getAd().getAdType() + "\" was added.");
}
}
How can i retrieve Those values from adwords.
this is my selector for retrieving the data from adword
SelectorBuilder builder = new SelectorBuilder();
Selector selector = builder
.fields(AdGroupAdField.Id, AdGroupAdField.AdGroupId, AdGroupAdField.Status,
AdGroupAdField.Description1,AdGroupAdField.Description2,AdGroupAdField.Headline)
.orderAscBy(AdGroupAdField.Id)
.offset(offset)
.limit(PAGE_SIZE)
.equals(AdGroupAdField.AdGroupId, adGroupId.toString())
.in(AdGroupAdField.Status, "ENABLED", "PAUSED", "DISABLED")
.equals("AdType", "TEXT_AD")
.build();
Typecast adGroupAd.getAd() to TextAd then you can get headline and other methods.
TextAd textAd = (TextAd)adGroupAd.getAd();
textAd.getHeadline();

Google Ad-Words API - ad extention link for mobile

During adding site links to campaign feed, I would like to set device preference for mobile to be checked.
How can I do it with ad words API ?
platformOperand.stringValue = "Mobile";//it also can be set for "Desktop"
I tried to do it like this:
ConstantOperand platformOperand = new ConstantOperand();
platformOperand.stringValue = "Mobile";//it also can be set for "Desktop"
platformOperand.type = ConstantOperandConstantType.STRING;
Function platformFunction = new Function();
platformFunction.lhsOperand = new FunctionArgumentOperand[] {
platformRequestContextOperand };
platformFunction.#operator = FunctionOperator.EQUALS;
platformFunction.rhsOperand = new FunctionArgumentOperand[] {
platformOperand };
and then it combined in function with links ids from google service and mutated for campaign feed service.
No exception and link added but when I enter to link edit, "Mobile" option remain unmarked.
Please advise.
I found the answer:
you shuld set devicePreference when you set propertes for FeedItem:
// Create the feed item and operation.
var item = new FeedItem();
item.feedId = siteLinksData.SiteLinksFeedId;
item.attributeValues = new FeedItemAttributeValue[]
{linkTextAttributeValue, linkUrlAttributeValue };
if (value.DeviceType == Device.Mobile)
{
item.devicePreference = new FeedItemDevicePreference();
item.devicePreference.devicePreference = 30001L;
item.devicePreference.devicePreferenceSpecified = true;
}
and this is most important part:
item.devicePreference = new FeedItemDevicePreference();
item.devicePreference.devicePreference = 30001L;
item.devicePreference.devicePreferenceSpecified = true;
if you wondering what the meaning of 30001L, it's device criteria IDs according to adwords API
See https://developers.google.com/adwords/api/docs/appendix/platforms

Get all clientID from MCC adwords account by adwordsAPI

I want to retrieve all clientID from my MCC account. I'm using this code
AdWordsUser user = new AdWordsUser(adwordsPropertyService.getEmail(), adwordsPropertyService.getPassword(),
null, adwordsPropertyService.getUseragent(), adwordsPropertyService.getDeveloperToken(),
adwordsPropertyService.getUseSandbox());
InfoServiceInterface infoService = user.getService(AdWordsService.V201109.INFO_SERVICE);
InfoSelector selector = new InfoSelector();
selector.setApiUsageType(ApiUsageType.UNIT_COUNT_FOR_CLIENTS);
String today = new SimpleDateFormat("yyyyMMdd").format(new Date());
selector.setDateRange(new DateRange(today, today));
selector.setIncludeSubAccounts(true);
ApiUsageInfo apiUsageInfo = infoService.get(selector);
for (ApiUsageRecord record : apiUsageInfo.getApiUsageRecords()) {
......
But apiUsageInfo.getApiUsageRecords return my only some clientId.
Have you any suggests?
My Answer will be helpful for PHP Developers
I am using v201502(php), You will get all account details from ManagedCustomerService api. Please refer the following URL https://developers.google.com/adwords/api/docs/reference/v201502/ManagedCustomerService
This is the sample code i used,
function DisplayAccountTree($account, $link, $accounts, $links, $depth) {
print str_repeat('-', $depth * 2);
printf("%s, %s\n", $account->customerId, $account->name);
if (array_key_exists($account->customerId, $links)) {
foreach ($links[$account->customerId] as $childLink) {
$childAccount = $accounts[$childLink->clientCustomerId];
DisplayAccountTree($childAccount, $childLink, $accounts, $links,
$depth +1);
}
}
}
function GetAccountHierarchyExample(AdWordsUser $user) {
// Get the service, which loads the required classes.
$user->SetClientCustomerId('xxx-xxx-xxxx');
$managedCustomerService =
$user->GetService('ManagedCustomerService');
// Create selector.
$selector = new Selector();
// Specify the fields to retrieve.
$selector->fields = array('CustomerId', 'Name');
// Make the get request.
$graph = $managedCustomerService->get($selector);
// Display serviced account graph.
if (isset($graph->entries)) {
// Create map from customerId to parent and child links.
$childLinks = array();
$parentLinks = array();
if (isset($graph->links)) {
foreach ($graph->links as $link) {
$childLinks[$link->managerCustomerId][] = $link;
$parentLinks[$link->clientCustomerId][] = $link;
}
}
// Create map from customerID to account, and find root account.
$accounts = array();
$rootAccount = NULL;
foreach ($graph->entries as $account) {
$accounts[$account->customerId] = $account;
if (!array_key_exists($account->customerId, $parentLinks)) {
$rootAccount = $account;
}
}
// The root account may not be returned in the sandbox.
if (!isset($rootAccount)) {
$rootAccount = new Account();
$rootAccount->customerId = 0;
}
// Display account tree.
print "(Customer Id, Account Name)\n";
DisplayAccountTree($rootAccount, NULL, $accounts, $childLinks, 0);
} else {
print "No serviced accounts were found.\n";
}
}
GetAccountHierarchyExample($user);
SetClientCustomerId will be the parent ID of your all accounts, It will be appeared near the Sign Out button of you google AdWords account, Please see the attached image
I hope this answer will be helpful, Please add your comments below if you want any further help
If you need just the list of clientCustomerIds, try ServicedAccountService.
Here is a code example that shows how this may be done.
Next time, you might also want to consider asking the question on the official forum for AdWords API: https://groups.google.com/forum/?fromgroups#!forum/adwords-api

Resources