Generate Google Cloud Endpoints - Android studio - google-app-engine

I've been trying to add a Google Cloud Backend to my android application using Android Studio. I've been following along with this I/O talk: http://youtu.be/lmv1dTnhLH4?t=37m2s and I realise that things have changed a bit from back then. In the video, he generates an endpoint be right clicking on a java file like the one below then selecting 'Generate Cloud Endpoint' which produces an endpoint java class he can then use in his app. I'm using Android Studio v0.5.6 and that option doesn't seem to be there any more. It seems all of the Android studio documentation relating to App Engine integration I've found on the internet hasn't been updated. Could anyone point me in the right direction to get this set up using the latest versions of Android Studio.
To add the backend I selected Tools > Google Cloud Tools > Add App Engine Backend:
Class I am trying to create an endpoint for:
User class:
package com.test.lol;
import com.googlecode.objectify.annotation.Entity;
import com.googlecode.objectify.annotation.Id;
import java.util.Date;
#Entity
public class User {
#Id
private String mID;
private String mFirstName;
private String mLastName;
private String mEmail;
private String mBirthday;
private Date mLastSeen;
public String getID() {
return mID;
}
public void setID(String ID) {
this.mID = ID;
}
public String getFirstName() {
return mFirstName;
}
public void setFirstName(String firstName) {
mFirstName = firstName;
}
public String getLastName() {
return mLastName;
}
public void setLastName(String lastName) {
mLastName = lastName;
}
public String getEmail() {
return mEmail;
}
public void setEmail(String email) {
mEmail = email;
}
public String getBirthday() {
return mBirthday;
}
public void setBirthday(String birthday) {
mBirthday = birthday;
}
public Date getLastSeen() {
return mLastSeen;
}
public void setLastSeen(Date lastSeen) {
mLastSeen = lastSeen;
}
}

Google have acknowledged this feature is missing and are working to implement it.
Source: https://code.google.com/p/android/issues/detail?id=68223
Edit: This feature has been implemented in the beta version of Android Studio
In the mean time, I:
Was able to use the Google Endpoint documentation to figure out
which annotations to use for the Endpoint API.
Checked out the Objectify Documentation to figure out which
annotations to use for Entities and Datastore persistance.
Uploaded my code to app engine using the terminal command: gradlew appengineUpdateAll
Installed the android client libraries to my local Maven repository using the terminal command: gradlew appengineEndpointsInstallClientLibs
Followed this tutorial on how to add the google API client to my Gradle project.
Added the local Maven repo to my projects build.gradle file and the client library as a dependency in my app's build.gradle
Used the Endpoint in my app.
Double fist pumped the air with great elation and proclaimed "I am the master commander!"

Finally Google Cloud Backend has been added again in Android Studio 0.6.1:
http://android-developers.blogspot.it/2014/06/new-ways-to-connect-your-app-to-the-cloud-android-studio.html

Related

How to troubleshoot local SQL connections in a Blazor App from Visual Studio 2019

Learning Visual Studio 2019, C#, and SQL on my local PC. Having trouble connecting to the local SQL databases and making sure that my app opens up in my local browser.
Now an app that has previously worked fine gives me a 404 error. I cannot figure out why this is happening. In general I would like to have a tool or some other checklists to see why the server is throwing the error.
Would love to have some advice on best ways to do this.
=================
I should have added code and better explanation initially.
I am rebuilding an app. Started with a fresh Blazor server app project, and started moving things over from the old app. I was eventually able to compile the new app and then launched it and originally got an SQL error.
Now I can get the app to launch a browser window (tried both Chrome and Edge) but nothing displays at all, it just looks like it is loading. There is nothing I can see in the console or in output. No errors. When I debug everything seems fine, the code never hangs on any line. Nothing ever errors out.
I can rebuild again but I want to figure out how to troubleshoot issues like this.
Startup.cs
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Wire_Desk.Data;
using Syncfusion.Blazor;
namespace Wire_Desk
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
services.AddRazorPages();
services.AddServerSideBlazor();
services.AddSingleton<WeatherForecastService>();
services.AddSyncfusionBlazor();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapBlazorHub();
endpoints.MapFallbackToPage("/_Host");
});
}
}
}
Program.cs
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
namespace Wire_Desk
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
}
I don't know what more code I should include. When I debug once I get through the program file and step into, there are no more code to step through, although this was also true with a small sample app.
I am stumped.

xUnit test project connection string

I would like to know the recommended approach to getting a connection string from a config file for my xUnit .net core test project.
I have set up a test project using the new Visual Studio 2017 xUnit Test project template for .net core. This project will run my integration tests that reference 2 different .net core class library projects - one of which will talk to the database using EF Core.
I understand that normally the connection string should not be set or accessed in a class library project - it should be the application that consumes the class library that should set the connection string.
However, in this case it appears that the xUnit test project is treated somewhat like a class library project. I have not seen any examples of how to set up some sort of config file and access that from the test project. How do I access the connection string from a config file so that my test project can consume my Datalayer class library project and pass in the appropriate connection string?
I was able to access the connection string from my xUnit test project by creating a DbOptionsFactory class that returns a DbContextOptions object initialized with a connection string that it reads from an appsettings.json configuration file.
This requires a dependency on Microsoft.Extensions.Configuration
public static class DbOptionsFactory
{
static DbOptionsFactory()
{
var config = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.Build();
var connectionString = config["Data:DefaultConnection:ConnectionString"];
DbContextOptions = new DbContextOptionsBuilder<MyDbContext>()
.UseSqlServer(connectionString)
.Options;
}
public static DbContextOptions<MyDbContext> DbContextOptions { get; }
}
appsettings.json
{
"Data": {
"DefaultConnection": {
"Name": "MyDbContext",
"ConnectionString": "connection string goes here"
}
}
}
When instantiating my DbContext I pass in the optionsBuilder object that has the connection string from the configuration file like so:
using (var context = new MyDbContext(DbOptionsFactory.DbContextOptions))
{
// access db here
}
Hope this helps anyone else that runs into the same issue.

Spring-boot: add application to tomcat server

I have a back-end which is build on spring-boot and then some custom code from my school built upon that.
The front-end is pure angular application which I serve from a different server trough a gulp serve.
They're only connected by REST calls.
There's already an authentication module running on the backend and to now I need to serve this angular application from the same tomcat server the back-end is running on so it can also use this authentication module.
I've found this about multiple connectors so I copied it as following class to set up multiple connectors:
#ConfigurationProperties
public class TomcatConfiguration {
#Bean
public EmbeddedServletContainerFactory servletContainer() {
TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory();
//tomcat.addAdditionalTomcatConnectors(createSslConnector());
return tomcat;
}
private Connector createSslConnector() {
Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
Http11NioProtocol protocol = (Http11NioProtocol) connector.getProtocolHandler();
try {
File keystore = new ClassPathResource("keystore").getFile();
File truststore = new ClassPathResource("keystore").getFile();
connector.setScheme("https");
connector.setSecure(true);
connector.setPort(8443);
protocol.setSSLEnabled(true);
protocol.setKeystoreFile(keystore.getAbsolutePath());
protocol.setKeystorePass("changeit");
protocol.setTruststoreFile(truststore.getAbsolutePath());
protocol.setTruststorePass("changeit");
protocol.setKeyAlias("apitester");
return connector;
} catch (IOException ex) {
throw new IllegalStateException("can't access keystore: [" + "keystore"
+ "] or truststore: [" + "keystore" + "]", ex);
}
}
}
Problem is that I don't see or find how I should setup these connectors so they serve from my angularJS build folder.
Upon searching I came upon Spring-Boot : How can I add tomcat connectors to bind to controller but I'm not sure if in that solution I should change my current application or make a parent application for both applications.
My current application main looks like this:
#Configuration
#ComponentScan({"be.ugent.lca","be.ugent.sherpa.configuration"})
#EnableAutoConfiguration
#EnableSpringDataWebSupport
public class Application extends SpringBootServletInitializer{
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
If possible I'd like some more info about what connectors are in the spring-boot context.
If this is not the way to go I'd like someone to be able to conform this second solution or suggest a change in my code.
I'm really not sure enough about these solution that I want to go breaking my application over it. (though it's backed up with github)
Just place your AngularJS + other front-end assets into src/main/resources/static folder, Spring Boot will serve them automatically.

Two projects in one solution

I have two projects in my Visual Studio solution. One is an empty WEB API application with AngularJS and html front-end. Other is WEB API project with embedded database, controllers and stuff. The problem is when I call web api controllers from my first solution, I'm getting 404 not found. I suspect there is a problem in a hosting, but I don't know what kind exactly. I tried to host back-end project in IIS, but no results. Maybe there is something I missed.
After a lot time spent on investigating this, I realised that it was problem with different ports in localhost, the solution can be found there:http://jaliyaudagedara.blogspot.com/2014/08/angularjs-consuming-aspnet-web-api.html.
Basically I should change the project URL in properties to match the front-end project's localhost port and add an 'api' suffix to avoid using the same virtual directory by both projects.
#satish,
Global.asax:
namespace WebAPI_Training
{
public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
GlobalConfiguration.Configure(WebApiConfig.Register);
}
}
}
WebApiConfig.cs:
namespace WebAPI_Training
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().First();
jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
}
}
}

Cloud Endpoints API does not authorise Google APIs Explorer after upgrading to App Engine 1.9.0

I use the Google APIs Explorer to test my Cloud Endpoint API running on the local dev server. I have authentication turned on:
#Api(
name = "testapi",
version = "1.0",
description = "Test API",
clientIds = { ApiConstants.WEB_CLIENT_ID, ApiConstants.ANDROID_CLIENT_ID,
ApiConstants.IOS_CLIENT_ID, ApiConstants.EXPLORER_ID },
audiences = { ApiConstants.ANDROID_AUDIENCE })
public class TestAPI
{
#ApiMethod(name = "TextObject.get", path = "testobject/{id}")
public TestObject get(#Named("id") Long id, User user) throws OAuthRequestException
{
if (user == null)
{
throw new OAuthRequestException(
"No User specified when calling protected API method.");
}
...
where ApiConstants.EXPLORER_ID is set to:
public static final String EXPLORER_ID = com.google.api.server.spi.Constant.API_EXPLORER_CLIENT_ID;
Everything worked fine in 1.8.9, and it works fine again when downgrading to 1.8.9. In 1.9.0, I get a null user in the code, and the "This method requires you to be authenticated." message in the explorer, even after logging in on the slider.
For now, I'll just hold off upgrading to 1.9.0, but I do want to upgrade at some stage to try out the Modules API.
Any ideas? Many thanks in advance.

Resources