Unity WebGL: can I access to MySql using MySqlConnector? - c#

I'm developing a WebGL app with Unity 2018.
I need to access a MySQL database hosted on the same server.
My questions is: can I use C# and MySqlConnector (solution i prefer), or I have to use instead web services calls ?
EDIT: it seems it's not either possible to use/consume web service in WebGL build, because System.Web.Services it's not accessible.
Thanks

The general way for doing this (both for security reasons and it's just all round a more standard way from the unity side of things) is that you simply host the server side database interaction pages within php and then make use of either the WWW or UnitWebRequest classes to actually utilize this.
You can fairly easily get back Json formatted data to work with on the client side
A fairly old (though still kinda relevant) tutorial/guide for something along these lines can be found Here
Generally, the idea is though - Game makes a request to PHP using an encrypted key of some kind for validation, PHP does the database work and then fires back some data usually in Json format

You can make a websocket. The server who will host the WebGL app will have a websocket server, who will do the MySQL communication and return the results. And the WebGL app(the unity one) connects to this websocket using a Auth Token(To ensure that is the WebGL connecting, not someone else) and get the results from the queries there

You might already have your answer but i have done it few weeks ago and its pretty easy.
I am posting both php and c# code below, have a look:
C# Code
WWWForm form = new WWWForm();
WWW www = new WWW("url of file location on server goes here", form);
yield return www;
Debug.Log(www.text);// this should return "successful connection"
PHP Code
replace '123' with required fields
<?php
$servername = "123";
$server_username = "123";
$server_password = "123";
$dbName = "123";
//Connection
$conn = new PDO ("mysql:host=$servername;dbname=$dbName", $server_username, $server_password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//Check Connection
if(!$conn){
die("Connection failed.");
}else{
echo "Connection Successful";
}
?>
Hope its helps!

Related

How to connect my Xamarin app with local mySQL server?

I'm trying connect to mySQL server with code below: (just part of my whole code)
using MySql.Data.MySqlClient;
//...
public void ConnectToServer()
{
string ConnectionString =
"Server=DESKTOP-91JG566;Database=db_server;Uid=user;Pwd=123456A+;";
MySqlConnection cConn = new MySqlConnection(ConnectionString);
cConn.Open(); // this returns the exception
serverStatus = cConn.Ping() ? serverStatus = "connected" : serverStatus = "disconnected";
}
I'm using MySQL Workbench, there is my server with database https://i.stack.imgur.com/jxn84.jpg
The exception says: System.TypeInitializationException: 'The type initializer for 'MySql.Data.MySqlClient.MySqlConfiguration' threw an exception.'
I have searched about it, and even though I enabled "SQL Server Debugging" in project properties, things are the same.
The problem might be caused because I have bad connection string, I am not sure.
My goal is to communicate with the server, query him, reveive orders etc...
As Jason already mentioned this is a horrible idea to do. Instead, I suggest you build some mini REST API or even use some of the serverless services out there.
When you have that REST API or Azure Function ready then you can communicate with them using your C# code, more precisely using HttpClient from the .NET.
Your mobile app will be the client which will "talk" to REST API, and REST API will proceed with your request and make the request to the DB, grab some data and return you JSON or XML which you can, later on, deserialize into C# objects and show to the user.
The most simple example is located on the MS Docs page here, so you can take a look.
Wishing you lots of luck with coding!

Writing Variables via QuickOPC in C# (Visual Studio)

my project is about writing an OPC UA Client, to read and write variables on a Siemens PLC OPC UA Server. I'm using Visual Studio 2017 Enterprise and installed the Quick OPC Toolkit from OPClabs to get started and try to connect. To program the client, I'm using Windows Forms and C#.
Connecting with the server and reading variables is working just fine, but writing them gives me a headache:
1.) Before I started programming on my own, I downloaded the OPC UA Sample Client from the OPC Foundation (if someone needs the download-link just ask, the download is hard to find). I connected to the server and could browse through the variables, but the write function was greyed out/not available.
2.) I started programming a very simple client, but also failed to write variables. Reading via Live Binding (http://opclabs.doc-that.com/files/onlinedocs/QuickOpc/2018.2/User%27s%20Guide%20and%20Reference-QuickOPC/webframe.html#Making%20a%20first%20OPC%20UA%20application%20using%20Live%20Binding.html) is working, also reading them by using easyUAClient.Read() works. I tried to write a variable with this code:
namespace ErsteOPCUAVerbindung{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
var easyUAClient = new EasyUAClient();
easyUAClient.WriteValue("opc.tcp://OpcUaClient:password#192.168.216.1:4840/", "nsu=SinumerikVarProvider;ns=2;s=/NC/_N_NC_TEA_ACX/$MN_PLC_CYCLIC_TIMEOUT", 1);
}
}}
but I keep getting an exception:
OpcLabs.EasyOpc.UA.OperationModel.UAException: "An OPC-UA operation failure with error code -2144010240 (0x80350000) occurred, originating from 'OpcLabs.EasyOpcUA'. The inner OPC-UA service exception with service result 'BadAttributeIdInvalid' contains details about the problem."
{"OPC-UA service result - An error specific to OPC-UA service occurred.\r\n---- SERVICE RESULT ----\r\nStatusCode: {BadAttributeIdInvalid} = 0x80350000 (2150957056)\r\n"}
I have no idea what is causing this. I suspected, that maybe some kind of access restriction is the reason, but I can't find any hints about it in the documentations and besides I'm logged in as administrator anyway.
Has anyone an Idea? Thank you.
I have had one more look at your code, and the way you pass in the user name and password (in the URL itself) is definitely not correct. The way it is given now it is essentially ignored. It may or may not be the cause for the problem with the Write, but it definitely needs to be changed. The proper way of specifying the user name and password would be:
var client = new EasyUAClient();
var endpointDescriptor = new UAEndpointDescriptor("opc.tcp://192.168.216.1:4840/");
endpointDescriptor.UserIdentity = UserIdentity.CreateUserNameIdentity("OpcUaClient", "password");
client.WriteValue(endpointDescriptor, "nsu=SinumerikVarProvider;ns=2;s=/NC/_N_NC_TEA_ACX/$MN_PLC_CYCLIC_TIMEOUT", 1);
Update: I found a documentation, which explained, that the administrator does not have write rights by default and how you can change that. You need to call the methode GiveUserAccess and pass two Arguments, the Username and "SinuWriteAll" (the second one is kind of hidden). I'll try it now with C# and post my solution if it works.

Should I keep the SqlConnection open?

In my Unity3D game the Player plays himself through short levels, which at the beginning take about 4 seconds. The goal is to get the best possible clear time in each level. I am currently saving these clear times locally, but I would like to upload them to an SQL Server, to be able to create a leaderboard for each level.
Since performing the SqlConnection.Open() command takes about 1-2 seconds, sometimes also 3, I was wondering whether I should keep a static connection always open, ready to execute any queries that I want to run.
Are there any unwanted and dangerous side-effects when doing it?
Edit: This is the code that I use for opening the SqlConnection.
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder()
{
DataSource = dataServer,
UserID = userId,
Password = password
};
SqlConnection connection = new SqlConnection(builder.ToString());
connection.Open();
First I'll answer this question:
Are there any unwanted and dangerous side-effects when doing it?
Assuming you keep this code in your Game (client) and the SQL Server is not client-side but in a server of yours located somewhere, a simple Client Reverse Engineer will be able to grab your credentials from your connection string and use them to gain Unauthorized access to your database. (NEVER trust the client)
With that being said, I would suggest you use a simple server-side technology (php,Socket App, Java servlet, etc..) along with the SQL that the client will send the information there and then to the database.
Example:
1) Client-> Posts Data -> PHP
2) PHP -> Connects -> SQL Database
3) PHP -> Inserts data -> SQL Database
Like this you can also retrieve the results of your ladder from the database by asking php (or whatever technology you are using) to send your data to the client.
Best wishes in your progress, and feel free to contact me for any additional information!

Detect Internet Connectivity on client machine

I have this web application (MVC using C#) that serves like an advertisement in my client's office. My client will open this "advertisement page" and display it on a big screen to their customers.
What happen is, every 30 minutes or so, the page will automatically refresh to fetch latest data from the database, however, they are using WIFI to connect to our server and sometimes the connection is very slow (or lost connection completely). My client requested me to write a code to prevent the page from refreshing if the connectivity is bad or no internet connection. (They do not want to show "No Internet Connection" on their advertisement TV)
I know I cannot do anything from the server side code because it is the client's machine that want to detect the internet connection, so leaving client side code as the only option. I am not good at this, can anyone help me out?
I'd suggest a "ping" sent via ajax:
var timeStart= new Date().getTime();
$.ajax({
url:"url-to-ping-response-file",
success:function(){
var timeNow = new Date().getTime();
var ping = timeNow - timeStart;
//less than one second
if(ping < 1000){
window.location.reload();
}
}
});
You can use the Circuit Breaker Pattern to gracefully handle intermittently connected environments.
Here are 2 open source JavaScript implementations. I have never used either of them, so I cannot attest to their quality.
https://github.com/yammer/circuit-breaker-js
https://github.com/mweagle/circuit-breaker
You can also make use of
if (navigator.onLine) {
location.reload();
}
This will not detect slow internet. Now, I don't understand your web layout but for sites that I work on I tend to get HTML content and DATA as separate calls. I do this with a MVVM/MVC pattern which is worth learning. I use angularjs it is very awesome.
Now.. you can also use good old jQuery to replace the content have a read of this Replace HTML page with contents retrieved via AJAX you could couple this with the .onLine check.
http://www.w3schools.com/jsref/prop_nav_online.asp

A not stateless Socket solution for NodeJS

I have to built a Client/Server application where the server side is just an application that passes data from one client to the other.
The client will be written in C# and I want to write the server in NodeJS, if that's possible. I'll try to explain the idea behind this.
It's best to explain this if you see this application as a 1vs1 game. So multiple clients can connect to an Async server. One client will be matched with another client as in a Player1 / Player2 context.
Player1 can make a "move". A POCO will be converted to a JSON format for example. That will then be send to the server and the server should know to what opponent (Player2) it should sent the data. Then in return Player2 can make a move and then new data will be send back through the server back to Player1.
So the server needs to have a list of all the connected players/clients. So it can keep track of what player play vs who and what scores they have etc. Basically, a stateless environment.
I've been thinking about writting the server in C# with the SocketAsyncEventArgs class. But since NodeJS/Socket.IO is already an optimized lib, that would save time if I could do it in that.
I just need to know if it's possible to do this in NodeJS. Or should I stick to a C# server?
Okey,
I argue that it is possible if you use something like SocketIO4Net.Client at your C# side to open connection to your node.js server.
From the docs:
SocketIO4Net.Client can interact with Socket.IO instances in a very
similar manner as Socket.IO JavaScript clients. This project aims to
fill the JavaScript client and C# client gap for Socket.IO, and retain
a very similar application experience.
And for the purpose of storing player lists etc. at server, it is easy. You define javascript object just as players where you add your connected clients and use for example socket.id as identifier.
// Players currently at server
var players = {};
you do this usually by listening socket connection event, for example:
... somewhere in your code ...
var io = require('socket.io').listen(httpServer);
... somewhere in your code ...
// run on new client connection..
io.sockets.on("connection", function (socket) {
// adding to list of players you have in your server
// Player can be your own declared class as you like it to be
players[socket.id] = new Player({
nickname: "playerNameExample"
});
});
However, if your game is more like match-making 1vs1 it would be worth to consider that you add always your separate playing partners to different rooms in server. So exchanging messages travels only between relevant participants. See socket.io rooms
As for the resources where to go next: best choice is to just google "multiplayer game with socket.io" which will give wide variety of results. Just as this: Building-multiplayer-games-with-nodejs if you are completely new to node.js googling hello world with node.js might be better to do first.
Due note: If you don't know the basics and haven't tried programming anything with node.js you are not ready to make working multiplayer game, advance step by step.! ( and yes I am looking this now from game perspective as you instructed but behavior of games can be applied to many apps as well ). Cheers.

Categories