I'm using Google Contacts API v3, I'm unable to update gender information for a contact
public static Contact UpdateContactName(ContactsRequest cr, Uri contactURL)
{
// First, retrieve the contact to update.
Contact contact = cr.Retrieve<Contact>(contactURL);
contact.Name.FullName = "New Name";
contact.Name.GivenName = "New";
contact.Name.FamilyName = "Name";
contact.ContactEntry.AddExtension(new Gender("male"));
try
{
Contact updatedContact = cr.Update(contact);
Console.WriteLine("Updated: " + updatedEntry.Updated.ToString())
return updatedContact;
}
catch (GDataVersionConflictException e)
{
// Etags mismatch: handle the exception.
}
return null;
}
Related
I'm trying to access a SharePoint instance using SharePoint Online Client Components SDK (sharepointclientcomponents_16-6518-1200_x64-en-us.msi) through .Net 6 console application.
My Code:
internal class SpMain
{
public static void GetApprovedAppsByView(
string siteUrl, NetworkCredential credentials, string listName, string viewName, string camlQuery)
{
try
{
using var context = new ClientContext(siteUrl);
context.Credentials = credentials;
var list = context.Web.Lists.GetByTitle(listName);
var view = list.Views.GetByTitle(viewName);
var query = new CamlQuery();
context.Load(view);
if (context.HasPendingRequest)
{
context.ExecuteQuery();
}
query.ViewXml = $"<View><Query>{view.ViewQuery}{camlQuery}</Query></View>";
var items = list.GetItems(query);
context.Load(items);
if (context.HasPendingRequest)
{
context.ExecuteQuery();
}
foreach (var listItem in items)
{
Console.WriteLine(listItem["Title"]);
}
}
catch (Exception ex)
{
Console.WriteLine("Error Message: " + ex.Message);
}
}
}
I'm calling this function like:
// Target Page: https://dummy.company.com/commy/cotrev/Lists/DevCMRL/DaMemos.aspx
const string siteUrl = "https://dummy.company.com/commy/cotrev/";
const string listName = "DevCMRL";
const string viewName = "DaMemos";
const string query = "*";
var credentials = new NetworkCredential("sp_testUser", "AwesomePassword", "myDomain");
SpMain.GetApprovedAppsByView(siteUrl, credentials, listName, viewName, query);
Console.ReadKey();
But I keep getting Bad Request at the first context.ExecuteQuery();. The credentials are correct. I think I have the Url, List, & View names set up incorrectly. And also, CamlQuery is completely wrong for sure. But this is something new for me and the docs at Microsoft are talking about SharePoint Online only.
Given the Target URL of the page with the actual List, how should I set the correct parameters?
I try Mictosoft example to create and and contact to exchange server using EWS and strangly mark as invalid while try using fax number for sending using Windows Fax and Scan (wfs.exe).
So , Does anybody know how should I set fax number in EWS that can be usable for sending fax in fax and scan?
After a lot of exprementing and invaestigating using OutlookSpy I found out I should add a # before number to be recognizable by Windows Fax and Scan. This is my final code.
public static ExchangeService GetService(string emailUser = defaultUser, string pass = defaultPass)
{
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP2);
//service.AutodiscoverUrl(emailUser, RedirectionUrlValidationCallback);
service.Url = new Uri("https://xs3.domain.net/EWS/Exchange.asmx");
service.Credentials = new WebCredentials(emailUser, pass);
service.TraceEnabled = true;
service.TraceFlags = TraceFlags.All;
return service;
}
public static bool IsValidEmail(string email)
{
try
{
var addr = new System.Net.Mail.MailAddress(email);
return addr.Address == email;
}
catch
{
return false;
}
}
public static void AddOrUpdateContact(ExchangeService service, string id, Dictionary<string, string> dataRecord, string targetFolder = defaultCotactsFolder, bool faxOnly = false)
{
Folder parentFolder;
FindFoldersResults folderItems = service.FindFolders(
WellKnownFolderName.Contacts,//parent folder
new SearchFilter.IsEqualTo(FolderSchema.DisplayName, targetFolder),
new FolderView(1)// return first 1 records
);
if (folderItems != null && folderItems.Count() > 0)
{//folder found!
parentFolder = folderItems.First() as Folder;
}
else
{//folder NOT found!
return;
}
ExtendedPropertyDefinition CustomProperty = new ExtendedPropertyDefinition(DefaultExtendedPropertySet.PublicStrings, "BusinessFax", MapiPropertyType.String);
FindItemsResults<Item> contactItems = service.FindItems(
parentFolder.Id,
new SearchFilter.IsEqualTo(ContactSchema.NickName, id),
new ItemView(1)
);
bool doesExist = contactItems != null && contactItems.Count() > 0;
Contact contact;
if (doesExist)
{//contact found!
contact = contactItems.First() as Contact;
}
else
{
// Create the contact.
contact = new Contact(service);
}
// Specify the name and how the contact should be filled.
contact.CompanyName = name;
contact.NickName = id;
contact.PhoneNumbers[PhoneNumberKey.BusinessFax] = "#"+dataRecord["COD_FAX_SUPID"];
contact.FileAsMapping = FileAsMapping.Company;
if (!faxOnly)
{
// Specify the business, home, and car phone numbers.
contact.PhoneNumbers[PhoneNumberKey.BusinessPhone] = dataRecord["COD_TEL_SUPID"];
if (IsValidEmail(dataRecord["EMAIL_SUPID"]))
{
// Specify two email addresses.
contact.EmailAddresses[EmailAddressKey.EmailAddress1] = new EmailAddress(dataRecord["EMAIL_SUPID"]);
}
contact.PhysicalAddresses[PhysicalAddressKey.Home] = new PhysicalAddressEntry()
{
Street = dataRecord["DES_STREET_SUPID"],
City = dataRecord["DES_TOWN_SUPID"],
CountryOrRegion = dataRecord["DES_COUNTRY_SUPID"],
PostalCode = dataRecord["COD_POST_SUPID"] + (String.IsNullOrWhiteSpace(dataRecord["NUM_BOX_SUPID"]) ? "" : $", PostBox: {dataRecord["NUM_BOX_SUPID"]}"),
}
}
if (doesExist)
{ //contact found!
contact.Update(ConflictResolutionMode.AlwaysOverwrite);
}
else
{
//save new!
contact.Save(parentFolder.Id);
}
}
Usage Example:
ExchangeService service = ContatctUpdaterLib.ContatcUpdater.GetService("USER#DONAMAIN.COM","123456");
//GetUserData return user data record as a Dictionary<string,string>
var data = GetUserData();
AddOrUpdateContact(service, dataRecord["COD_SUP_SUPID"], dataRecord, "Contacts(Fax Only)" ,true);
I am developing a Xamarin Forms application which integrates Facebook and logs in using the Xamarin.Auth package. But each time a browser window will open to login with Facebook or Twitter.
Does Xamarin support native login with Facebook and Twitter? That is, can I log in using the Facebook or Twitter app on the user's device?
I need to get the Facebook and Twitter id of the user.
you can use ACAccountStore and if user doesn't have the social framework you can alternatively use xamarin auth
ACAccountStore accountStore = new ACAccountStore();
ACAccountType accountType = accountStore.FindAccountType(ACAccountType.Facebook);
AccountStoreOptions fbAccountStoreOptions = new AccountStoreOptions();
fbAccountStoreOptions.FacebookAppId = "333333";
fbAccountStoreOptions.SetPermissions(ACFacebookAudience.Everyone, new[] { "email", "user_birthday", "user_about_me","public_profile" });
Tuple<bool, NSError> requestResult = await accountStore.RequestAccessAsync(accountType, fbAccountStoreOptions);
if (requestResult.Item1)
{
ACAccount[] availableAccounts = accountStore.Accounts.Where(acco => acco.AccountType.Description == "Facebook").ToArray();
int fbAccountsCount = availableAccounts.Count();
if (fbAccountsCount < 1)
{
HandleFacebookAuthorizationUsingOAuthDialog();
}
else if (fbAccountsCount == 1)
{
HandleFacebookAuthorizationUsingACAccount(availableAccounts.First());
}}
private void HandleFacebookAuthorizationUsingOAuthDialog()
{
try
{
OAuth2Authenticator fbAuthenticator = new OAuth2Authenticator(SharedConstants.FacebookLiveClientId, "email,user_birthday,user_about_me", new Uri("https://m.facebook.com/dialog/oauth/"), new Uri("http://www.facebook.com/connect/login_success.html"));
fbAuthenticator.AllowCancel = true;
fbAuthenticator.Completed += FbAuthenticator_Completed;
fbAuthenticator.Error += FbAuthenticator_Error; ;
RootView.PresentViewController(fbAuthenticator.GetUI(), true, null);
}
catch (Exception ex)
{
}
}
private async void HandleFacebookAuthorizationUsingACAccount(ACAccount account)
{
try
{
NSMutableDictionary<NSString, NSString> params_ = new NSMutableDictionary<NSString, NSString>();
params_.SetValueForKey(new NSString("id,name,birthday,gender"), new NSString("fields"));
SLRequest request = SLRequest.Create(SLServiceKind.Facebook, SLRequestMethod.Get, new NSUrl($"https://graph.facebook.com/me"), params_);
request.Account = account ?? throw new ArgumentNullException(nameof(account));
SLRequestResult response = await request.PerformRequestAsync();
NSHttpUrlResponse responseData = response.Arg2;
if (responseData.StatusCode == 200)
{
string jsonResponse = response.Arg1.ToString();
FacebookAuthorizationResult authResult = ParseFacebookAuthorizationResultFromJsonResponse(jsonResponse);
_facebookAuthTCS?.TrySetResult(new SocailAutheticationResult<FacebookAuthorizationResult>(authResult));
}
else
{
_facebookAuthTCS?.TrySetResult(new SocailAutheticationResult<FacebookAuthorizationResult>(SocialAuthorizationState.CouldntConnectToService));
}
}
catch (Exception ex)
{
_
}
}
I am using this code and getting the events from the calendar and it is working fine but, I want to get the events from google accounts calendar .For example, I want to get the (deepakcando90#gmail.com )google calendar accounts events also? I know it is possible but do not know how to implement it?
public static void readCalendarEvent(Context context) throws ParseException {
ContentResolver contentResolver = context.getContentResolver();
Calendar calendar = Calendar.getInstance();
String dtstart = "dtstart";
String dtend = "dtend";
SimpleDateFormat displayFormatter = new SimpleDateFormat("EEEE, MMMM dd, yyyy");
stime=displayFormatter.format(calendar.getTime());
SimpleDateFormat startFormatter = new SimpleDateFormat("MM/dd/yy");
String dateString = startFormatter.format(calendar.getTime());
long after = calendar.getTimeInMillis();
SimpleDateFormat formatterr = new SimpleDateFormat("hh:mm:ss MM/dd/yy");
Calendar endOfDay = Calendar.getInstance();
Date dateCCC = formatterr.parse("47:59:59 " + dateString);
endOfDay.setTime(dateCCC);
cursor = contentResolver.query(Uri.parse("content://com.android.calendar/events"), (new String[] { "calendar_id", "title", "description", "dtstart", "dtend", "eventLocation" }), "(" + dtstart + ">" + after + " and " + dtend + "<" + endOfDay.getTimeInMillis() + ")", null, "dtstart ASC");
gCalendar = new ArrayList<GoogleCalendar>();
try {
System.out.println("Count=" + cursor.getCount());
if (cursor.getCount() > 0) {
System.out.println("the control is just inside of the cursor.count loop");
while (cursor.moveToNext()) {
GoogleCalendar googleCalendar = new GoogleCalendar();
gCalendar.add(googleCalendar);
int calendar_id = cursor.getInt(0);
googleCalendar.setCalendar_id(calendar_id);
String title = cursor.getString(1);
googleCalendar.setTitle(title);
String description = cursor.getString(2);
googleCalendar.setDescription(description);
String dtstart1 = cursor.getString(3);
googleCalendar.setDtstart(dtstart1);
String dtend1 = cursor.getString(4);
googleCalendar.setDtend(dtend1);
String eventlocation = cursor.getString(5);
googleCalendar.setEventlocation(eventlocation);
}
}
} catch (AssertionError ex) {
ex.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
You can try OAuth 2.0 service accounts to properly access the user accounts. Using a service account lets you impersonate users and perform operation on their behalf.
Accessing domain calendars as an app
An app can access domain-owned calendars without requiring user credentials if it authenticates using a service account. The service account must have the necessary access using domain-wide authority delegation. In order to impersonate a user account, specify the email address of the user account with the setServiceAccountUser method of the GoogleCredential factory.
I hope it helps. Goodluck :)
I’m trying to read out the Internet formatted address from an Exchange connected Outlook. I read all contacts from the Outlook Contacts, i.e. not from the Global Address Book (GAB), and the problem is that for all users that are stored in Contacts from the Exchange GAB I’ve only managed to read out the X.500 formatted address which is not useful in this case. For all manually added contacts that are not in the domain of the Exchange server, the Internet address is exported as expected.
Basically I’ve used the following code snippet to enumerate the Contacts:
static void Main(string[] args)
{
var outlookApplication = new Application();
NameSpace mapiNamespace = outlookApplication.GetNamespace("MAPI");
MAPIFolder contacts = mapiNamespace.GetDefaultFolder(OlDefaultFolders.olFolderContacts);
for (int i = 1; i < contacts.Items.Count + 1; i++)
{
try
{
ContactItem contact = (ContactItem)contacts.Items[i];
Console.WriteLine(contact.FullName);
Console.WriteLine(contact.Email1Address);
Console.WriteLine(contact.Email2Address);
Console.WriteLine(contact.Email3Address);
Console.WriteLine();
}
catch (System.Exception e) { }
}
Console.Read();
}
Is there any way to extract the Internet address instead of the X.500?
You need to convert from ContactItem to AddressEntry - one email address at a time.
To do this, you need to access the AddressEntry via the Recipient object model. The only way to retrieve the actual Recipient EntryID is by leveraging the PropertyAccessor of the ContactItem.
const string Email1EntryIdPropertyAccessor = "http://schemas.microsoft.com/mapi/id/{00062004-0000-0000-C000-000000000046}/80850102";
string address = string.Empty;
Outlook.Folder folder = this.Application.Session.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderContacts) as Outlook.Folder;
foreach (var contact in folder.Items.Cast<Outlook.ContactItem>().Where(c=>!string.IsNullOrEmpty(c.Email1EntryID)))
{
Outlook.PropertyAccessor propertyAccessor = contact.PropertyAccessor;
object rawPropertyValue = propertyAccessor.GetProperty(Email1EntryIdPropertyAccessor);
string recipientEntryID = propertyAccessor.BinaryToString(rawPropertyValue);
Outlook.Recipient recipient = this.Application.Session.GetRecipientFromID(recipientEntryID);
if (recipient != null && recipient.Resolve() && recipient.AddressEntry != null)
address = recipient.AddressEntry.GetExchangeUser().PrimarySmtpAddress;
}