google email settings api send as alias - google-admin-sdk

I'm getting an error when trying to create a sendas alias using the Email Settings API for C#. Here's my code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Google.GData.Apps;
using Google.GData.Apps.GoogleMailSettings;
using Google.GData.Client;
using Google.GData.Extensions;
namespace EmailSettings
{
class Program
{
static void Main(string[] args)
{
GoogleMailSettingsService service = new GoogleMailSettingsService("domain.com", "apps");
service.setUserCredentials("administrator#domain.com", "pwd");
service.CreateSendAs("username", "FriendlyAlias", "testalias#domain.com", "", "true");
}
}
}
I'm getting the following error "{"Execution of request failed: https://apps-apis.google.com/a/feeds/emailsettings/2.0/domain.com/username/sendas"}"
the inner exception is {"The remote server returned an error: (400) Bad Request."}

Related

Google Cloud PubSub - Regional endpoint auth issue

I want to create a publisher for google cloud Pub/Sub that publish to a regional endpoint.
This is the code I am running(pretty much the code from the quickstart guide):
using Google.Cloud.PubSub.V1;
using Grpc.Core;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using static Google.Cloud.PubSub.V1.PublisherClient;
namespace PubSub
{
class PubSubProducer
{
public async Task<int> PublishMessagesAsync(string projectId, string topicId, IEnumerable<string> messageTexts)
{
var creationSettings = new ClientCreationSettings(credentials: await GoogleGrpcCredentials.GetApplicationDefaultAsync().ConfigureAwait(false),
serviceEndpoint: "us-central1-pubsub.googleapis.com");
var customSettings = new PublisherClient.Settings
{
EnableMessageOrdering = true
};
TopicName topicName = TopicName.FromProjectTopic(projectId, topicId);
PublisherClient publisher = await PublisherClient.CreateAsync(topicName, clientCreationSettings: creationSettings, settings: customSettings);
int publishedMessageCount = 0;
var publishTasks = messageTexts.Select(async text =>
{
try
{
string ordering_key;
if (int.Parse(text) > 5)
ordering_key = "a";
else
ordering_key = "b";
string message = await publisher.PublishAsync(ordering_key, text);
Console.WriteLine($"Published message {message}");
Interlocked.Increment(ref publishedMessageCount);
}
catch (Exception exception)
{
Console.WriteLine($"An error ocurred when publishing message {text}: {exception.Message}");
}
});
await Task.WhenAll(publishTasks);
return publishedMessageCount;
}
}
}
I would like to use the ordering feature so I need the messages to be in the same region.
This code returns:
An error ocurred when publishing message 9: Status(StatusCode="Unauthenticated", Detail="Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.", DebugException="Grpc.Core.Internal.CoreErrorDetailException: {"created":"#1608719160.348000000","description":"Error received from peer ipv4:<IP>","file":"T:\src\github\grpc\workspace_csharp_ext_windows_x64\src\core\lib\surface\call.cc","file_line":1062,"grpc_message":"Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.","grpc_status":16}")
When I am not suppling a regional endpoint it works fine:
var creationSettings = new ClientCreationSettings(credentials: await GoogleGrpcCredentials.GetApplicationDefaultAsync().ConfigureAwait(false));
It seems like my service account missing a permission to use this regional endpoint.
How can I fix this? What permissions am I missing?
The issue was with how I created the ClientCreationSettings.
The correct way for publisher:
var clientCreationSettings = new PublisherClient.ClientCreationSettings(serviceEndpoint: "us-central1-pubsub.googleapis.com:443");
For subscriber:
var clientCreationSettings = new SubscriberClient.ClientCreationSettings(serviceEndpoint: "us-central1-pubsub.googleapis.com:443");

InvalidOperationException: Scheme already exists: Bearer

I recently resumed work on a project that had lain dormant for a year. It was using Angular on AspNet Core 1.1 and using an early version of OpenIddict 1.0. It was developed using VS2017.
I updated VS2017 to the latest release (15.7.5) but the project would not compile and when I fixed the compilation errors it wouldn't run. So eventually I bit the bullet and decided to update the project to Asp Net Core 2.1 and to use the latest version of OpenIddict. I have the project so it compiles but when it starts it gives the error in the title, namely "InvalidOperationException: Scheme already exists: Bearer"
I can't see what is wrong. I understand that somewhere a second scheme named 'Bearer' is being added, but I can't figure out where. I am enclosing below my Startup.cs in its entirety.
using AspNet.Security.OpenIdConnect.Primitives;
using Microsoft.AspNetCore.Builder;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using SIAngular.DBContexts;
using SIAngular.Models;
using SIAngular.Services;
using OpenIddict.Abstractions;
using System.IdentityModel.Tokens.Jwt;
using Microsoft.IdentityModel.Tokens;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Authentication.JwtBearer;
namespace SIAngular
{
public class Startup
{
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddCors();
services.AddMvc();
services.AddDbContext<ApplicationDbContext>(options =>
{
// Configure the context to use Microsoft SQL Server.
options.UseSqlServer(Configuration.GetConnectionString("SqlConnection"));
// Register the entity sets needed by OpenIddict.
// Note: use the generic overload if you need
// to replace the default OpenIddict entities.
options.UseOpenIddict();
});
// Register the Identity services.
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>();
//.AddDefaultTokenProviders();
// Configure Identity to use the same JWT claims as OpenIddict instead
// of the legacy WS-Federation claims it uses by default (ClaimTypes),
// which saves you from doing the mapping in your authorization controller.
services.Configure<IdentityOptions>(options =>
{
options.ClaimsIdentity.UserNameClaimType = OpenIdConnectConstants.Claims.Name;
options.ClaimsIdentity.UserIdClaimType = OpenIdConnectConstants.Claims.Subject;
options.ClaimsIdentity.RoleClaimType = OpenIdConnectConstants.Claims.Role;
});
services.AddOpenIddict()
// Register the OpenIddict core services.
.AddCore(options =>
{
// Configure OpenIddict to use the Entity Framework Core stores and models.
options.UseEntityFrameworkCore()
.UseDbContext<ApplicationDbContext>();
})
// Register the OpenIddict server services.
.AddServer(options =>
{
// Register the ASP.NET Core MVC services used by OpenIddict.
// Note: if you don't call this method, you won't be able to
// bind OpenIdConnectRequest or OpenIdConnectResponse parameters.
options.UseMvc();
// Enable the token endpoint.
options .EnableTokenEndpoint("/connect/token");
options.AcceptAnonymousClients();
options.DisableScopeValidation();
// Note: the Mvc.Client sample only uses the code flow and the password flow, but you
// can enable the other flows if you need to support implicit or client credentials.
options.AllowPasswordFlow();
// Mark the "email", "profile" and "roles" scopes as supported scopes.
options.RegisterScopes(OpenIdConnectConstants.Scopes.Email,
OpenIdConnectConstants.Scopes.Profile,
OpenIddictConstants.Scopes.Roles);
// During development, you can disable the HTTPS requirement.
options.DisableHttpsRequirement();
// Note: to use JWT access tokens instead of the default
// encrypted format, the following lines are required:
//
options.UseJsonWebTokens();
options.AddEphemeralSigningKey();
})
// Register the OpenIddict validation services.
.AddValidation();
JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
JwtSecurityTokenHandler.DefaultOutboundClaimTypeMap.Clear();
services.AddAuthentication(o =>
{
o.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
options.Authority = "http://localhost:53244/";
options.Audience = "resource_server";
options.RequireHttpsMetadata = false;
//options.IncludeErrorDetails = true;
options.TokenValidationParameters = new TokenValidationParameters
{
NameClaimType = OpenIdConnectConstants.Claims.Subject,
RoleClaimType = OpenIdConnectConstants.Claims.Role
};
});
services.AddTransient<IEmailSender, AuthMessageSender>();
services.AddTransient<ISmsSender, AuthMessageSender>();
}
public void Configure(IApplicationBuilder app)
{
app.UseDeveloperExceptionPage();
app.UseAuthentication();
app.UseStaticFiles();
app.UseMvcWithDefaultRoute();
}
}
}
Can someone please exp-lain what I am doing wrong. My intent was to follow the OpenIddict examples but clearly I went wrong somewhere.
The full stacktrace follows:
System.InvalidOperationException: Scheme already exists: Bearer
at Microsoft.AspNetCore.Authentication.AuthenticationOptions.AddScheme(String name, Action`1 configureBuilder)
at Microsoft.AspNetCore.Authentication.AuthenticationBuilder.<>c__DisplayClass4_0`2.<AddSchemeHelper>b__0(AuthenticationOptions o)
at Microsoft.Extensions.Options.ConfigureNamedOptions`1.Configure(String name, TOptions options)
at Microsoft.Extensions.Options.OptionsFactory`1.Create(String name)
at Microsoft.Extensions.Options.OptionsManager`1.<>c__DisplayClass5_0.<Get>b__0()
at System.Lazy`1.ViaFactory(LazyThreadSafetyMode mode)
at System.Lazy`1.ExecutionAndPublication(LazyHelper executionAndPublication, Boolean useDefaultConstructor)
at System.Lazy`1.CreateValue()
at Microsoft.Extensions.Options.OptionsCache`1.GetOrAdd(String name, Func`1 createOptions)
at Microsoft.Extensions.Options.OptionsManager`1.Get(String name)
at Microsoft.Extensions.Options.OptionsManager`1.get_Value()
at Microsoft.AspNetCore.Authentication.AuthenticationSchemeProvider..ctor(IOptions`1 options, IDictionary`2 schemes)
at Microsoft.AspNetCore.Authentication.AuthenticationSchemeProvider..ctor(IOptions`1 options)
--- End of stack trace from previous location where exception was thrown ---
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, ServiceProviderEngineScope scope)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(IServiceCallSite callSite, TArgument argument)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScoped(ScopedCallSite scopedCallSite, ServiceProviderEngineScope scope)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitSingleton(SingletonCallSite singletonCallSite, ServiceProviderEngineScope scope)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(IServiceCallSite callSite, TArgument argument)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.DynamicServiceProviderEngine.<>c__DisplayClass1_0.<RealizeService>b__0(ServiceProviderEngineScope scope)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngine.GetService(Type serviceType, ServiceProviderEngineScope serviceProviderEngineScope)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngine.GetService(Type serviceType)
at Microsoft.Extensions.DependencyInjection.ServiceProvider.GetService(Type serviceType)
at Microsoft.Extensions.Internal.ActivatorUtilities.ConstructorMatcher.CreateInstance(IServiceProvider provider)
at Microsoft.Extensions.Internal.ActivatorUtilities.CreateInstance(IServiceProvider provider, Type instanceType, Object[] parameters)
at Microsoft.AspNetCore.Builder.UseMiddlewareExtensions.<>c__DisplayClass4_0.<UseMiddleware>b__0(RequestDelegate next)
at Microsoft.AspNetCore.Builder.Internal.ApplicationBuilder.Build()
at Microsoft.AspNetCore.Hosting.Internal.WebHost.BuildApplication()
at Microsoft.AspNetCore.Hosting.Internal.WebHost.StartAsync(CancellationToken cancellationToken)
at Microsoft.AspNetCore.Hosting.WebHostExtensions.RunAsync(IWebHost host, CancellationToken token, String shutdownMessage)
at Microsoft.AspNetCore.Hosting.WebHostExtensions.RunAsync(IWebHost host, CancellationToken token)
at Microsoft.AspNetCore.Hosting.WebHostExtensions.Run(IWebHost host)
at SIAngular.Program.Main(String[] args) in C:\Users\username\Documents\Visual Studio 2017\Projects\SIAngular\Program.cs:line 20
I finally found the answer which is probably obvious to OpenIddict experts, but not to casual users.
Since I am using JWT the.AddValidation() after the registration of the OpenIddict server options is not needed. This is obvious in hindsight but I hope this helps someone else with this problem. I am sure I am not thbe only person dumb enough to have been caught by this and when I look at OpenIddict samples now I understand, but I think the comment "For JWT tokens, use the Microsoft JWT bearer handler." could be amended to "For JWT tokens, use the Microsoft JWT bearer handler and remove the call to AddValidation below.
I have tried the below code and worked for me.
public void ConfigureServices(IServiceCollection services)
{
// Code omitted for brevity
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.Audience = "https://localhost:5000/";
options.Authority = "https://localhost:5000/identity/";
})
.AddJwtBearer("AzureAD", options =>
{
options.Audience = "https://localhost:5000/";
options.Authority = "https://login.microsoftonline.com/eb971100-6f99-4bdc-8611-
1bc8edd7f436/";
});
}
You can read this complete document on the below URL:
https://learn.microsoft.com/en-us/aspnet/core/security/authorization/limitingidentitybyscheme?view=aspnetcore-6.0
I have tried other solution as well.
Please check if you have multiple startup.cs files and you are using any authentication schemes in that files.
and also check to publish folder/deployment folder, need to delete App_Data Folder before deploying fresh/ latest changes.

Starting on web api ( can't locate namespace for HttpClient)

I'm starting to work with web api and i'm struggling to build my sample program. I get a compile error "The type or namespace name 'HttpClient' could not be found".
static void Main(string[] args)
{
var uri = "https://raw.github.com/AlexZeitler/HttpClient/master/README.md";
var httpClient = new System.Net.htt HttpClient();
httpClient.GetStringAsync(uri).ContinueWith(
t => Console.WriteLine(t.Result));
Console.ReadLine();
}
I have referenced the namespace Sytem.Net.Http but that does not seem to help.
I wonder if someone can tell me what i'm missing.
Thank is advance
B
You need to install this Nuget Package
http://www.nuget.org/packages/Microsoft.Net.Http/

Getting Error while consuming self created webservices which connect Oracle SQL Developer

I am creating a webservices and while consuming getting error like this:
Exception in thread "main" org.apache.axis2.AxisFault: org.apache.axis2.AxisFault: >Mapping qname not fond for the package: oracle.jdbc.driver
at org.apache.axis2.util.Utils.getInboundFaultFromMessageContext(Utils.java:531)
at org.apache.axis2.description.OutInAxisOperationClient.handleResponse>>>>(OutInAxisOperation.java:375)
at org.apache.axis2.description.OutInAxisOperationClient.send(OutInAxisOperation.java:421)
at org.apache.axis2.description.OutInAxisOperationClient.executeImpl(OutInAxisOperation.java:229)
at org.apache.axis2.client.OperationClient.execute(OperationClient.java:165)
at com.db.DatabaseClassStub.getDataBaseConnection(DatabaseClassStub.java:185)
at com.db.TestDatabaseClass.main(TestDatabaseClass.java:13)
For creating webservices that Connect Oracle SQL Developer using apache axis2 and eclipse. I have used the following s/w:
1). Eclipse Helios
2). Apache Tomcat 6
3). axis2-1.6.1-bin and axis2-1.6.1-war and also kept "ojdbc5" in tomcat lib folder.
My Webservices creation java code is,
package com.db;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DatabaseClass {
static Connection con = null;
public static Connection getDataBaseConnection()
{
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
}
try {
con = DriverManager.getConnection("jdbc:oracle:thin:#10.137.12.133:1521:ora11gr2","tran1","training123");
} catch (SQLException e) {
e.printStackTrace();
}
if (con != null) {
System.out.println("You made it, take control your database now!");
} else {
System.out.println("Failed to make connection!");
}
return con;
}
}
and Consuming webservices Java code is:
package com.db;
import java.rmi.RemoteException;
import com.db.DatabaseClassStub.GetDataBaseConnection;
import com.db.DatabaseClassStub.GetDataBaseConnectionResponse;
public class TestDatabaseClass {
public static void main(String[] args) throws RemoteException {
DatabaseClassStub stub = new DatabaseClassStub();
GetDataBaseConnection conn = new GetDataBaseConnection();
GetDataBaseConnectionResponse response = stub.getDataBaseConnection(conn);
System.out.println(response.get_return());
}
}
will you plz let me know where i am doing wrong?whenever i trying to execute TestDatabaseClass.java getting error which i have mentioned earlier. Same code (DatabaseClass.java) when i am executing in simple java project, its giving output but why not in webservices ?
You cannot 'export' a JDBC Connection in a SOAP web service operation: what goes across the wire has to be by definition serializable (as an XML).
You can expose methods/operations that provide the results of a query.

Send a mail through exchange server with C++ , EWS

using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Mail;
using Microsoft.Exchange.WebServices.Data;
namespace Email
{
class Program
{
static void Main(string[] args)
{
try
{
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP1);
service.UseDefaultCredentials = false;
service.Credentials = new NetworkCredential("id_in_server", "Password_in_server");
service.Url = new Uri("https://myexchangeserver/EWS/exchange.asmx");
Console.WriteLine(service.Url);
service.TraceEnabled = true;
EmailMessage message = new EmailMessage(service);
message.Subject = "Hello from the EWS Managed API";
message.Body = "Good Job!";
message.ToRecipients.Add("recipient_mail_address");
//message.Save();
message.SendAndSaveCopy();
}catch(Exception e)
{
Console.WriteLine(e.ToString());
}
}
}
}
I sent mail use EWS , C# without outlook and it worked ok.But in C++ , I can't, if use MAPI library 1 profile outlook required. I see a example use Webservice in C++ http://social.msdn.microsoft.com/Forums/en-US/wwsapi/thread/adf2a58c-32b7-477a-adcc-f2d053e2902b but I can't use this. Now, I want to send mail through exchange server use C++ without Outlook. Please help me. Thanks
I solved this problem.
Here is answer http://social.msdn.microsoft.com/Forums/en-US/wwsapi/thread/f0800af0-e62f-4b62-96e6-c504923ab77a
I used WWSAPI connect to exchange server with C++.