So I was thinking about learning about app development for android. I know you use kotlin however, I also want to start working with .NET and C# is there a possibility for my first app that I create a basic login and register form in the app using Kotlin and connect it to a .NET REST API? Is that a thing I am sure you are just using the URL for the API call?
Sure! Using Retrofit, the Android app could be connected to the RESTful APIs that is available using the latest technology by Microsoft and the open source community; ASP.NET Core Web API 5.
A complete guide to do so:
http://codingsonata.com/a-complete-tutorial-to-connect-android-with-asp-net-core-web-api/
yes it is possible, there are plenty of libraries that are able to help you with that, like Retrofit or Volley
Yes. It's a very common way to consume API for data processing purposes in android-based applications.
If you have learnt on how to consume API with Android Application (built using JAVA), it's pretty much the same.
if you have never used JAVA to create android applications that consume API, don't worry because the process you need to do is very simple, moreover there are already many collections of libraries that you can use for this purpose. You can try to look on several library such as Retrofit and OkHttp.
Let me show you a a simple example of using OkHttp to pass data from android to API. This simple example is quoted from this article
private val client = OkHttpClient()
fun run() {
val formBody = FormBody.Builder()
.add("search", "Jurassic Park") /*The parameters*/
.build()
val request = Request.Builder()
.url("https://en.wikipedia.org/w/index.php") /*API URL*/
.post(formBody)
.build()
client.newCall(request).execute().use { response ->
if (!response.isSuccessful) throw IOException("Unexpected code $response")
println(response.body!!.string())
}
}
I hope this answer can be helpful for you. If you need more assistance, don't hesitate to contact.
If you are using API, you use URL and model of your data.
I recommend Retrofit as a library for connecting to any API. A good example is here, check out this and I think you will be well prepared to write Kotlin code.
Firstly, you need to define retrofit client, with your URL:
retrofit = new Retrofit.Builder()
.baseUrl("https://reqres.in")
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build();
then you need to map your API as an interface, for example if you have an endpoint https://reqres.in/api/users? you must define them like this:
#GET("/api/users?")
Call<UserList> doGetUserList(#Query("page") String page);
For creating .NET Core API, especially with user registration you must check some of tutorials, I recommend to be familiar with EF Identity (other).
Related
I am currently working on a school project with a classmate. We've decided on making the classic setup of an Administration-client (Blazor Server) and a Member-client (Angular).
We have 7 Projects in the solution so far:
Solution
├───Project.MemberClient (Angular)
├───Project.AdminClient (Blazor Server)
├───Project.Api (REST API)
├───Project.Application (CQRS & Mediatr)
├───Project.Core (Entities, Enums, Interfaces)
├───Project.Infrastructure (Database Context & Migrations)
└───Project.Test
We're using EntityFramework for the database, which both the API and Blazor Server have access to, through Mediatr.
Unfortunately, we can't come to terms with how we should handle the use of the API.
My classmate is convinced that both Blazor Server client and the Angular client should go through the REST API.
I'm convinced that we don't need to go through the API with the Blazor Server-client, since it can access Mediatr through Dependency injection. I feel it's silly to go through the API to deserialize a C# object to JSON just to serialize it again straight after.
This is a request on the API:
[HttpPost("organizr-user")]
[ProducesResponseType(StatusCodes.Status200OK)]
public async Task<ActionResult<OrganizrUserResponse>> CreateOrganizrUser([FromBody] CreateOrganizrUserCommand command)
{
var result = await _mediator.Send(command);
return Ok(result);
}
This is a request on Blazor Server:
private async Task OnButtonSave_Clicked()
{
_userCreated = false;
_showErrors = false;
var query = new RegisterUserRequest
{
FirstName = _firstName,
LastName = _lastName,
Gender = (Gender)_gender,
Address = _address,
PhoneNumber = _phoneNumber,
Email = _email,
Password = _password,
ConfigRefreshPrivilege = _refreshConfiguration
};
var result = await Mediator.Send(query);
if (!result.Succeeded)
{
_showErrors = true;
_errors = result.Errors.ToList();
}
else
{
_userCreated = true;
}
}
I feel (yeah, there are a lot of feelings involved) like we still uphold the principle of only one access point by the use of Mediatr. Blazor doesn't need the API, but Angular does.
What would be the right way to go about this?
I am glad you are taking this school project so seriously.
As is with all architectural decisions - "it depends". There is no such thing as a silver bullet approach, only the best for you situation.
I think you both have some points. You are correct in saying you are upholding a single point of access, and thus reducing the amount of code you need to write - but that is not the only thing to consider here. You need to ask yourself a few more questions.
You should treat this as an production application that has the potential to scale
Here are some questions you should ask yourself.
Are the API and the Blazor web server going to be hosted on the same server as the database ?
API's should be stateless, are you going to keep that consideration while writing your blazor web app, since they consume the same code ?
Is your application scalable ? How will you implement things like load balancing on both the API and the blazor web server ?
Can I easily replace/change some in the overall design if needed ?
If I had to choose for you, I would suggest filtering everything through a web API.
Here is why:
You have more options around hosting - you can host your blazor web application on one server and the database/webAPI on another.
It forces developers into "The pit of success". If you have 10 developer working on this product, it's easier for them to think of the application as "one API" rather than an "API and a server that uses the same code". This may not seem important now, but trust me, large scale application can get very hairy very quickly if you don't keep things as simple as possible.
Creating load balancers on Blazor web server can be tricky, since it uses SignalR to communicate with the client.
Testing becomes easier. What if your blazor application has functionality that your Angular client doesn't? That means it would never be built into the web api. Now you need to do things like load testing, stress testing, etc on two separate servers rather than just the web API. The testing required on the Blazor web server would be heavily scaled down if everything ran through the Web API.
And last but not least,the Blazor developers pride themselves on how easy it is to switch between Blazor client and Blazor web server. What if, in future, you decide that Blazor web server isn't the best solution, and you would prefer blazor client ? If everything was running through an Web API this would be a few lines of code. If not - you have a lot of refactoring to do.
I think its a better idea to write a few extra lines to "serialize and deserialize " through an API now, and save yourself potential hassle later.
This is my opinion based off my personal experiences - keep things simple, readable and scalable.
I hope this helped.
Let me know if you would like me to clarify anything.
Happy coding!!
Good morning.
I am a bit confused about these two repositories(graphql-dotnet/graphql-dotnet/ and graphql-dotnet/server/).
https://github.com/graphql-dotnet/graphql-dotnet/ and
https://github.com/graphql-dotnet/server
They are both under the same organization and there is some overlap of contributors, but I'm a bit lost about deciding which one to use.
I would like to build a dotnet 5 application that hosts a graphql endpoint. In a nutshell that is my goal.
I noticed that the graphql-dotnet/server/repository has inbuilt some helpers such as.
serviceCollection
.AddGraphQL((options, provider) =>
{
options.EnableMetrics = HostEnvironment.IsDevelopment();
var logger = provider.GetRequiredService<ILogger<Startup>>();
options.UnhandledExceptionDelegate = ctx => logger.LogError("{Error} occurred", ctx.OriginalException.Message);
})
.AddSystemTextJson()
.AddErrorInfoProvider(opt => opt.ExposeExceptionStackTrace = HostEnvironment.IsDevelopment())
.AddWebSockets()
.AddDataLoader()
.AddGraphTypes(typeof(ApplicationSchema))
Which allows my DI to be setup nice and easy. Its counterpart, the graphql-dotnet/graphql-dotnet/ does not.
So my question is "which one should I use exclusivly? Which one is recomended, by secondary goals are to add jwt authentication and finally federation support. But those two are far down the line.
One of my coworkers went ahead and used graphql-dotnet/graphql-dotnet/ and his server application has a lot more configuration than the documentation of graphql-dotnet/server/ so how do I know which one do I use?
Can any one recommend any documentation that highlights the difference between the two of them?
The main graphql-dotnet repo is the "core" library of GraphQL components. The server repo contains ASP.NET specific extensions. It uses the core library. If you use the server project, you are also using the core library.
GraphQL itself can be used with any protocol, it is not required to be used with HTTP or JSON. So the core library does not have any HTTP or ASP.NET dependencies.
If you are using ASP.NET, then the server project is the quickest way to get started. If you want to use Subscriptions, then the server project provides that functionality.
If you don't need subscriptions and if you want a bit more control over how the framework handles the HTTP request, then it would be easier to write your own controller or middleware.
Using JWT authentication is handled by ASP.NET and can be used in either scenario. Federation can also be used in either scenario.
I've searched some time, looking for easy way to connect with some other sites WebAPI. There are some solutions, but they are made in very complicated way.
What I want to do:
Connect with server using URL adress
Provide login and password to get some data
Get data as JSON/XML
Save this data in an "easy-to-read" way. I mean: save it to C# variable which could be easy to modify.
Currently, API that I want to work with is Bing Search, but I'm looking for some universal way. I found an example, but it doesn't work for me and in my app I can't use this class: "DataServiceQuery" because it doesn't exsist.
How do you usually do it? Do you have your favourite solutions? Are there some universal ways or it depends on type of API that you work with?
I'm currently working on .NET MVC app (in case it could make any difference)
From server side
You can use that like below.
// Create an HttpClient instance
HttpClient client = new HttpClient();
// Send a request asynchronously continue when complete
client.GetAsync(_address).ContinueWith(
(requestTask) =>
{
// Get HTTP response from completed task.
HttpResponseMessage response = requestTask.Result;
// Check that response was successful or throw exception
response.EnsureSuccessStatusCode();
// Read response asynchronously as JsonValue
response.Content.ReadAsAsync<JsonArray>().ContinueWith(
(readTask) =>
{
var result = readTask.Result
//Do something with the result
});
});
You can see example on following link.
https://code.msdn.microsoft.com/Introduction-to-HttpClient-4a2d9cee
For JavaScirpt:
You could use jQuery and WebAPI both together to do your stuff.
There are few steps to it.
Call web api with Ajax jquery call.
Get reponse in JSON
Write javascript code to manipulate that response and do your stuff.
This is the easiest way.
See following link for reference:
http://www.codeproject.com/Articles/424461/Implementing-Consuming-ASP-NET-WEB-API-from-JQuery
It entirely depends on the type of API you want to use. From a .Net point of view, there could be .Net 2 Web Services, WCF Services and Web API Services.
Web APIs today are following the REST standard and RMM. Some APIs need API Keys provided as url parameters, others require you to put in request's header. Even some more robust APIs, use authentication schemes such as OAuth 2. And some companies have devised their own standards and conventions.
So, the short answer is that there is no universal way. The long answer comes from documentation of each API and differs from one to another.
I am new to developing with the Goolge API’s. I am trying to get the Google.Apis.Freebase.V1 API working in C#. Does anyone have a small example on using this API in C#? I have spent the last several days looking and can only find a couple of examples for the old Freebase Api. Nothing for the Google API.
I am just looking for a simple example on setting up a connection to the API, doing a search, then how to handle a MQL query back into a Json object. The simpler the better.
Thanks
Scott
The correct code to do a MQL query in C# using the Google API Client Library should look something like this:
string API_KEY = "your-api-key-here";
FreebaseService service = new FreebaseService{ Key = API_KEY };
String query = "[{\"id\":null,\"name\":null,\"type\":\"/astronomy/planet\"}]";
FreebaseService.MqlreadRequest request = service.Mqlread(query);
string response = request.Fetch();
Console.WriteLine (response);
Unfortunately, there seems to be some sort of error with the client library right now as its not returning any results. I'll try to figure out what's going on there.
Update: The problem appears to be that the client library passes along an alt=json parameter which the Freebase API is unable to support. The Python client library has a way to disable this but there no way to do it in .Net. You can follow the open bug for this on the Google Code project.
I am creating a PHP website connected to a MySQL database. Next I will need to write a C# desktop app that will use the same DB. Unfortunately I cannot connect to the DB directly from a remote location and my hosting company won't allow SSH neither.
So what options do I have? If the hosting company supported .NET, it wouldn't be a problem, but I'm not that experienced with PHP. Will I have to write a PHP service (SOAP?) and then consume it in my desktop app? Also, how do I communicate with server from the desktop app?
Any help appreciated!
Depending on security requirement, could you write a generic SQL executing page in PHP, that took the SQL as a String parameter, and returned the results as an array of Strings (Might need some meta data too or something)?
Other than that the only thing I can think of is a web service of some kind.
Also SOAP can work both ways, you can read and write from the C# app, no need to write a WebService on both ends, unless you need to notify your c# app about something from the server (In which case you could always try frequent polling from the c# app)
Best option would be creating a set of RESTful services in your PHP site.
One of most important things to take in account is REST is more configuration by convention, and there's no need of things like SOAP which may be an absolute overkill for your solution.
You just send JSON from PHP and .NET Windows application will parse it as a CLR object.
A sample scenario would be:
Service operation: http://yourdomainhere.com/API/Message/34894
** This returns something like { "text": "hello world" }
.NET client receives this JSON and using a JSON parser like Newton JSON parser, you'd be doing this:
MessageDto dto = JsonConvert.DeserializeObject([JSON received from the service call]);
MessageBox.Show(dto.Text); // This will show "hello world"
It's just a very simple example, but it'd give you an idea of what's next.
You can query your REST API using WebRequest/WebResponse .NET BCL classes.
PHP only needs to send a web response including your JSON in the output stream, that's all. No SOAP, no XML, no complication. Keep it simple.
I think the following link will be of helpful to you!
Developing SOAP Web Services with PHP/C#
What you can do is providing some PHP-wrappers which you can access from your C# code. As an example you can use this discussion, regarding C# / PHP communication.
Basically you can send a HTTP request to PHP and retrieve it's return value with C#. PHP would then perform the DB requests. If you're using AJAX on the Website it should be easy using the same communication interfaces.
this is the first paragraph of Matt Fellows answer.
But in what form do you send the data back to the application in?
Maybe JSON?
PHP webpage
<?php
$host = "host.host.com";
$user = "XXXXX";
$password = "XXXX";//plaintext :)
$connection = mysql_connect($host, $user, $password);
$database = "XXXXX";
$syntax = $_GET['syntax']; //www.example.com/help.php?syntax=DROP%20TABLE%20XXX
$result = mysql_query($syntax);
//somehow output the $result in C# readable form
?>