Google.APIs Change Group Owner - google-api

Looking for the proper code to change a Google email group's owner...
what I have currently (not working). The credential/service are all fine, as I'm using them to do a bunch of other GoogleAPIs stuff which is working correctly. I'm just not sure whether I should be messing with a user or the group.
String serviceAccountEmail = "asdfasdfasf#asdfasdfsdfsdf-323423.iam.gserviceaccount.com";
var certificate = new X509Certificate2(#"c:\asdf\PasswordReset2.p12", "notasecret", X509KeyStorageFlags.Exportable);
ServiceAccountCredential credential = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(serviceAccountEmail)
{
User = "andy#asdfasdfa.com",
Scopes = new[] { DirectoryService.Scope.AdminDirectoryUser, DirectoryService.Scope.AdminDirectoryGroup }
}.FromCertificate(certificate));
var service = new DirectoryService
(
new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "jimmyjohn",
ApiKey = "asdkfjasl;dkjfaskdjfasdfasdf"
}
);
Group g = new Group();
g = service.Groups.Get(groupemail).Execute();
// NEED HELP HERE
service.Groups.Update(g, groupemail).Execute();
//Member newMember = new Member();
//newMember.Email = useremail;
//newMember.Role = "OWNER"; //MANAGER , OWNER
//newMember.Kind = "admin#directory#member";
//service.Members.Update(newMember, groupemail, useremail).Execute();```

I already had the answer, but due to a facepalm bug I was always telling it to set the owner to myself (in a previous function feeding this one), hence never seeing anything change in Google Groups...
Member newMember = new Member
{
Email = useremail,
Role = "OWNER" //MANAGER , OWNER
};
service.Members.Update(newMember, groupemail, useremail).Execute();

Related

How can I retrieve Id of inserted entity using Entity framework Core?

I have a concern since as I am new to using EntityFramework Core, that if I add an object, that I still do not have the id generated by the database, sending the object to it in the transaction, I would add it automatically, this is my code ,
public async Task<ServiceResult<Common.Entities.Company>> SaveCompany(Domain.Models.Company companyModel, Domain.Models.Administrator administratoModel)
{
ServiceResult<Common.Entities.Company> serviceResult = new ServiceResult<Common.Entities.Company>();
try
{
if (user == null && companyExistsRnc == false)
{
Common.Entities.Company myCompany = new Common.Entities.Company
{
CompanyId = companyModel.CompanyId, // The id has not been generated yet,
CompanyName = companyModel.CompanyName,
Rnc = companyModel.Rnc,
CountryId = companyModel.Country.CountryId,
Telephone = companyModel.Telephone,
PersonContact = companyModel.PersonContact,
Address = companyModel.Address,
PhotoPath = companyModel.PhotoPath,
IsActive = false,
};
await _companyRepository.SaveCompany(myCompany); // this is the method that I add the company object to the database and do the savechanges
Common.Entities.User myUser = new Common.Entities.User
{
FirstName = administratoModel.FirstName,
SecondName = administratoModel.SecondName,
FirstLastName = administratoModel.FirstLastName,
SecondLastName = administratoModel.SecondLastName,
GenderId = administratoModel.Gender.GenderId,
PhoneNumber = administratoModel.Telephone,
Email = administratoModel.Email,
UserName = administratoModel.Email,
IsActive = administratoModel.IsActive,
UserTypeId = (short)Common.Core.UserType.Administrator,
Company = myCompany, // here I send the my company object for when I do the savechanges, I think it will add it to me
};
await _userHelper.AddUserAsync(myUser, administratoModel.Password);
await _userHelper.AddUserToRoleAsync(myUser, Common.Core.UserType.Administrator.ToString());
Common.Entities.Administrator myAdministrator = new Common.Entities.Administrator
{
AdministratorId = administratoModel.AdministratorId,
FirstName = administratoModel.FirstName,
SecondName = administratoModel.SecondName,
FirstLastName = administratoModel.FirstLastName,
SecondLastName = administratoModel.SecondLastName,
GenderId = administratoModel.Gender.GenderId,
Email = administratoModel.Email,
Telephone = administratoModel.Telephone,
IsActive = true,
PhotoPath = administratoModel.PhotoPath,
UserTypeId = (short)Common.Core.UserType.Administrator,
Company = myCompany, // company object without the id
User = myUser, // user object without the id
};
await _administratorRepository.SaveAdministrator(myAdministrator);
serviceResult.Data = myCompany;
serviceResult.Message = "CompaƱia agregada!";
}
}
I am new to using entity framework core, and if in case I am wrong in what I am doing please indicate in which part I am doing it wrong, to correct, I await your comments and would appreciate the help,

Using Google.Apis.Core for .NET Core, why can't i see a list of photos in my Google Photos when I specify spaces="photos"?

Sample code goes like this:
static string[] Scopes = { DriveService.Scope.Drive, DriveService.Scope.DrivePhotosReadonly };
static string ApplicationName = "Quickstart";
UserCredential credential;
using (var stream = new FileStream("credentials.json", FileMode.Open, FileAccess.Read))
{
string credPath = "token.json";
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
Scopes,
"user",
CancellationToken.None,
new FileDataStore(credPath, true)).Result;
}
// Create Drive API service.
var service = new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = ApplicationName,
});
// Define parameters of request.
FilesResource.ListRequest listRequest = service.Files.List();
listRequest.Spaces = "photos";
listRequest.PageSize = 100;
listRequest.Fields = "nextPageToken, files(id, name)";
// List files.
IList<Google.Apis.Drive.v3.Data.File> files = listRequest.Execute().Files;
Console.WriteLine("Files:");
if (files != null && files.Count > 0)
{
foreach (var file in files)
{
Console.WriteLine("{0} ({1})", file.Name, file.Id);
}
}
else
{
Console.WriteLine("No files found.");
}
Console.Read();
I enable the Google Drive API through the Google Console and get the credentials.json file. When I run this using listRequest.Spaces = "drive" then I can see all of my drive files, but I cannot see any photos when I make it "photos".
What other sort of undocumented magic needs to be in place here for this to work?
Thanks.
Google Drive and Google Photos have been disconnected, the space "photos" has been deprecated.
However, there is a Google Photos API that allows you to list your photos.

SignatureVerificationFailedException in JwtAuthForWebAPI

I have wired up the JwtAuthForWebAPI nuget project but I am not able to validate the generated tokens. I end up getting a 500 error. I am using the exact same key value for both token generation and also when configuring JwtAuthenticationMessageHandler.
This is the code to generate a token:
var tokenHandler = new JwtSecurityTokenHandler();
var symmetricKey = JsonWebTokenSecretKey.GetBytes();
var now = DateTime.UtcNow;
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(
new[]{
new Claim(JwtClaimKeys.Audience, SessionManager.Current.ApplicationId.ToString()),
new Claim(JwtClaimKeys.Subject, userLoginRequest.ApplicationInstanceId.ToString())
}),
TokenIssuerName = "My Company",
Lifetime = new Lifetime(now, now.AddMinutes(tokenLifetimeInMinutes)),
SigningCredentials = new SigningCredentials(
new InMemorySymmetricSecurityKey(symmetricKey),
"http://www.w3.org/2001/04/xmldsig-more#hmac-sha256",
"http://www.w3.org/2001/04/xmlenc#sha256")
};
tokenDescriptor.Subject.AddClaims(GetRoles(userLoginRequest));
var token = tokenHandler.CreateToken(tokenDescriptor);
return tokenHandler.WriteToken(token);
This is the code to register the authentication handler:
var keyBuilder = new SecurityTokenBuilder();
var jwtHandler = new JwtAuthenticationMessageHandler
{
Issuer = "My Company",
AllowedAudience = ApplicationId.ToString(),
SigningToken = keyBuilder.CreateFromKey(JsonWebTokenSecretKey),
PrincipalTransformer = new MyUserPrincipleTransformer()
};
config.MessageHandlers.Add(jwtHandler);
This is the error I get:
{"Message":"An error has occurred.","ExceptionMessage":"IDX10503: Signature validation failed. Keys tried: 'System.IdentityModel.Tokens.InMemorySymmetricSecurityKey\r\n'.\nExceptions caught:\n ''.\ntoken: '{\"typ\":\"JWT\",\"alg\":\"HS256\"}.{\"aud\":\"1\",\"sub\":\"3\",\"role\":[\"User\",\"Admin\"],\"iss\":\"My Company\",\"exp\":1429547369,\"nbf\":1429543769}'","ExceptionType":"System.IdentityModel.SignatureVerificationFailedException",
"StackTrace":"
at System.IdentityModel.Tokens.JwtSecurityTokenHandler.ValidateSignature(String token, TokenValidationParameters validationParameters)\r\n
at System.IdentityModel.Tokens.JwtSecurityTokenHandler.ValidateToken(String securityToken, TokenValidationParameters validationParameters, SecurityToken& validatedToken)\r\n
at JwtAuthForWebAPI.JwtSecurityTokenHandlerAdapter.ValidateToken(IJwtSecurityToken securityToken, TokenValidationParameters validationParameters)\r\n
at JwtAuthForWebAPI.JwtAuthenticationMessageHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)\r\n
at System.Web.Http.HttpServer.<SendAsync>d__0.MoveNext()"}
This is an example JSON token:
eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhdWQiOiIxIiwic3ViIjoiMyIsInJvbGUiOlsiVXNlciIsIkFkbWluIl0sImlzcyI6Ik15IENvbXBhbnkiLCJleHAiOjE0Mjk1NTE4MjgsIm5iZiI6MTQyOTU0ODIyOH0.9wA_RBir9u7Cn_-Fy2T-Q_IDUfz6B928IEbIgXD9Bug
Interestingly, I am able to validate the token with my key using http://jwt.io. I suspect it may have something to do with the JwtAuthForWebAPI library looking at something different than what the System.Identity JWT library is generating?
this is Jamie (author of the JwtAuthForWebAPI package). The server config code - specifically, SecurityTokenBuilder.CreateFromKey(string) - assumes the given string is base64 encoded. It was either that, or assumptions or parameters are needed that would indicate which encoding to use for converting to a byte array. I chose to assume the string was base64 encoded. I'm sure there's a clearer way to go about converting the string key into a SecurityToken, but that's the way the code is today.
In SmokeTests.cs within the JwtAuthForWebAPI.SampleClient project, you can see that I used the Convert.FromBase64String() method, as opposed to using the GetBytes() method from an Encoding class:
public const string SymmetricKey = "YQBiAGMAZABlAGYAZwBoAGkAagBrAGwAbQBuAG8AcABxAHIAcwB0AHUAdgB3AHgAeQB6ADAAMQAyADMANAA1AA==";
// ...
var key = Convert.FromBase64String(SymmetricKey);
var credentials = new SigningCredentials(
new InMemorySymmetricSecurityKey(key),
"http://www.w3.org/2001/04/xmldsig-more#hmac-sha256",
"http://www.w3.org/2001/04/xmlenc#sha256");
Feel free to keep using your current token generation code, but on the server...
Please try specifying a base64 encoded version of JsonWebTokenSecretKey in the server configuration code. You can use a site like https://www.base64encode.org/ to encode it, or try code like this:
var base64key = Convert.ToBase64String(Encoding.UTF8.GetBytes(JsonWebTokenSecretKey));
var keyBuilder = new SecurityTokenBuilder();
var jwtHandler = new JwtAuthenticationMessageHandler
{
Issuer = "My Company",
AllowedAudience = ApplicationId.ToString(),
SigningToken = keyBuilder.CreateFromKey(base64key),
PrincipalTransformer = new MyUserPrincipleTransformer()
};
Let me know whether or not that works.
Also, I'm going to update the library to catch the SignatureVerificationFailedException exception and return a 401, as opposed to letting an internal server error happen. You'll still need to specify your key as a base64 string, but at least such configuration issues won't cause a 500 error.
Again, please let me know if that does the trick.
it's just my code sample base on #Jamie answer
protected string GetUsername(string token)
{
string secret = "keyyyyy!#3";
var key = Convert.FromBase64String(secret);
var IssuerSigningKey = new SymmetricSecurityKey(key);
IdentityModelEventSource.ShowPII = true;
var SigningCredentials = new SigningCredentials(
IssuerSigningKey,
SecurityAlgorithms.HmacSha256Signature);
var handler = new JwtSecurityTokenHandler();
var tokenSecure = handler.ReadToken(token) as SecurityToken;
var validations = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = IssuerSigningKey,
ValidateIssuer = false,
ValidateAudience = false
};
var claims = handler.ValidateToken(token, validations, out tokenSecure);
return claims.Identity.Name;
}

LinqToTwitter generate exception when i try to send privatemessage

i try to send private message to followers of a user who is already authenticated with my_app, here is the code :
var authent = new MvcAuthorizer
{
Credentials = new SessionStateCredentials()
{
ConsumerKey = this.client.ConsumerKey,
ConsumerSecret = this.client.ConsumerSecret,
OAuthToken = identity.Token.Token
}
};
var twitterCtx = new TwitterContext(authent);
list_friend.ToList().ForEach(x => twitterCtx.NewDirectMessage(x.InvitedFriendID, messageWithPlaceHolders.Replace("[FRIEND_NAME]", x.Name)));
list_friend is the list of followers of the user who is authenticated.
Pleaaaase i need your help.
the solution is to use the InMemoryCrendentials rather than SessionStateCredentials and add the token secret to crendential, and after we should add DateTime.Now to the message because twitter don't allow duplicate message, here is the code off the solution it work well :
var authent = new MvcAuthorizer
{
Credentials = new InMemoryCredentials()
{
ConsumerKey = this.client.ConsumerKey,
ConsumerSecret = this.client.ConsumerSecret,
OAuthToken = identity.Token.Token,
AccessToken = identity.Token.Secret
}
};
var twitterCtx = new TwitterContext(authent);
list_friend.ToList().ForEach(x => twitterCtx.NewDirectMessage(x.SocialId, messageWithPlaceHolders.Replace("[FRIEND_NAME]", x.Name) +DateTime.Now.ToString()));
Thanks

How to read extended properties from Outlook contacts using EWS

I'm currently attempting to read certain properties from Outlook Contact objects through Microsoft's EWS managed API. I retrieve these Contact objects from the FindItems() function. Some of these fields are extended properties such as the Title or User1 field and I'm having difficulty reading them. At the moment, I have:
Guid propertySetId = new Guid("{00062004-0000-0000-C000-000000000046}");
ExtendedPropertyDefinition titleProp = new ExtendedPropertyDefinition(propertySetId, 0x3A45, MapiPropertyType.String);
ExtendedPropertyDefinition user1Prop = new ExtendedPropertyDefinition(propertySetId, 0x804F, MapiPropertyType.String);
string title, user1;
contact.TryGetProperty(titleProp, out title);
contact.TryGetProperty(user1Prop, out user1);
When running this, TryGetProperty always returns false. I have verified that these fields are populated in Outlook for the contacts that I am searching for.
Edit: This is how I retrieve the contact objects.
ExchangeService service = //...
Mailbox userMailbox = new Mailbox(emailAddress);
FolderId folderId = new FolderId(WellKnownFolderName.Contacts, userMailbox);
FindItemsResults<Item> results;
const string AQS = "Category:~>\"CategoryTag\"";
ItemView view = new ItemView(200);
results = service.FindItems(folderId, AQS, view);
foreach (var result in results)
{
Contact contact = result as Contact;
//...Try to read fields
}
You need to change the ItemView to include the properties (PropertySet) you wish to access.
var user1Val = string.Empty;
var user1Prop = new ExtendedPropertyDefinition(DefaultExtendedPropertySet.Address, 0x804F, MapiPropertyType.String);
ExtendedPropertyDefinition[] extendedFields = new ExtendedPropertyDefinition[] { user1Prop };
PropertySet extendedPropertySet = new PropertySet(BasePropertySet.FirstClassProperties, extendedFields);
ItemView view = new ItemView(200) { PropertySet = extendedPropertySet };
// ...
var title = contact.CompleteName.Title; // Title value
contact.TryGetProperty(user1Prop, out user1Val); // user field 1 value

Resources