I am trying to get data from my MySQL server to my Unity project. I tried to get the data like so:
public string awsurl = "ec2-174-129-82-141.compute-1.amazonaws.com/connect_to_server.php";
IEnumerator GetScores()
{
print("get scores start");
WWW aws_get = new WWW(awsurl);
yield return aws_get;
print("getscore here");
if (aws_get.error != null)
{
print("There was an error getting aws: " + aws_get.error);
}
else
{
print(aws_get.text); // this is a GUIText that will display the scores in game.
}
}
I have a php script on my server to handle the interaction because I am having trouble using the MySqlConnection library for my unity project.
Here is my php script:
$address = "localhost"
$dbusername = "root";
$dbpassword = "root";
$db_name = "watshoes";
$db_conn = new mysqli($address, $dbusername, $dbpassword, $db_name);
if(isset($_POST['username'])) $username = $_POST['username'];
if(isset($_POST['user_id'])) $user_id = $_POST['user_id'];
if(isset($password)) $password =$_POST['password'];
$stmt = $db_conn->prepare("SELECT image FROM ImageText");
// "s" means the database expects a string
$stmt->bind_param("s", $user_id);
if($stmt->execute())
{
/* bind result variables */
$stmt->bind_result($image);
/* fetch value */
$stmt->fetch();
echo $image;
}
else
{
echo "query failed";
}
$stmt->close();
$db_conn->close();
But every time I run the code I get this error:There was an error getting aws: Failed to connect to ec2-174-129-82-141.compute-1.amazonaws.com port 80: Timed out
Thanks for looking at the code and please let me know if there is anything else I can do to help.
You have to add a rule to open the port 80 using security groups (Inbound tab)
How your rule should look:
By default the port 80 is close in EC2 AWS instances.
And the URL is malformed in Unity
Add http:// to your server URL
In editor will work ok without http:// but it will fail in android.
Related
What i would like to achieve is have two different SQL Server Databases, on two different servers running the same SQL Server Version( SQL Server 2008 R2 RTM - 10.50.1600.1 ) to be synched daily. Synched meaning just transferring the new data ( or even all the data ) from one of the two ("parent" database ) to the other ( "child" database ). We want the parent to force its shema as well all its data to its child.
What i have already tried
Knowing that the two machines run on windows server 2012 R2 i have already tried to implement a solution ( although i am no expert when it comes to SQL Server ) using the following tools.
PHP v7.2
ExeOutputforPHP ( https://www.exeoutput.com/ )
WinSCP ( For its build in ftp methods https://winscp.net )
Schemazen ( https://github.com/sethreno/schemazen )
So what i would do would be this :
Read a configuration file using PHP ( server, user, pass, database, etc.. )
When PHP would not produce any errors i would trigger the schemazen script method.
When everything would go smooth i would trigger the winscp's ftp method to the remote Server
That would be the export Side
Now for the import Side
I would Locate the ftp directory and using the Schemazen create method i would import the data again by reading a configuration file.
Export Side Code
$iniConfig = parse_ini_file('..\conf.ini', true);
if ($iniConfig) {
echo PHP_EOL.'Configuration file found in '.realpath('..\conf.ini').PHP_EOL;
define('EXPORT_HOST', $iniConfig['export']['host']);
define('EXPORT_DB', $iniConfig['export']['db']);
define('EXPORT_DIR', $iniConfig['export']['dir']);
define('FTP_HOST', $iniConfig['ftp']['host']);
define('FTP_PATH_TO_SAVE', $iniConfig['ftp']['path']);
define('FTP_USERNAME', $iniConfig['ftp']['user']);
define('FTP_PASS', $iniConfig['ftp']['pass']);
define('PATH_TO_SAVE', $iniConfig['ftp']['path']);
$output = [];
$return_var = 0;
$credsFlag = '';
if ($iniConfig['export']['user'] && $iniConfig['export']['pass']) {
define('EXPORT_USER', $iniConfig['export']['user']);
define('EXPORT_PASS', $iniConfig['export']['pass']);
$credsFlag = ' -u '.EXPORT_USER.' -p '.EXPORT_PASS;
} else {
echo PHP_EOL.'Please Define the Username and Password for connection to the Database!'.PHP_EOL;
die();
}
$connArray = [
'Database' => EXPORT_DB,
'UID' => EXPORT_USER,
'PWD' => EXPORT_PASS,
];
$connection = sqlsrv_connect(EXPORT_HOST, $connArray);
if (!$connection) {
echo PHP_EOL.'Could not Connect to the Database!' . PHP_EOL . 'We received the following tried to connect:' . PHP_EOL;
print_r(sqlsrv_errors());
die();
}
$query = "select table_name from information_schema.tables where table_catalog = '" . EXPORT_DB . "'";
$tables = [];
$rs = sqlsrv_query($connection, $query);
while (($rd = sqlsrv_fetch_array($rs, SQLSRV_FETCH_ASSOC)) !== false) {
if ($rd) {
array_push($tables, $rd);
}
}
sqlsrv_close($connection);
$dataTablesString = '--dataTables=';
foreach ($tables as $table) {
$dataTablesString .= $table['table_name'].',';
}
exec('scriptor\SchemaZen.exe script -s '.EXPORT_HOST.' -b '.EXPORT_DB.$credsFlag.' -d '.EXPORT_DIR.' -o '.$dataTablesString, $output, $return_var);
if (-1 === $return_var) {
$file = fopen('ftp_script.txt', 'w+');
if ($file) {
$ftpStringToWrite = 'open ftp://'.FTP_USERNAME.':'.FTP_PASS.'#'.FTP_HOST.'/'.PHP_EOL.'cd '.FTP_PATH_TO_SAVE.PHP_EOL.'put '.EXPORT_DIR.'\*'.PHP_EOL.'exit';
$writer = fwrite($file, $ftpStringToWrite);
if ($writer) {
fclose($file);
unset($output);
exec('ftp\WinSCP.com /script=ftp_script.txt', $output, $return_var);
if (0 === $return_var) {
echo PHP_EOL.'Backup Exported and Transfered via FTP.'.PHP_EOL;
}
}
}
}
}
Import Side Code
<?php
if ($iniConfig = parse_ini_file('../conf.ini', true)) {
define('IMPORT_HOST', $iniConfig['import']['host']);
define('IMPORT_DB', $iniConfig['import']['db']);
define('IMPORT_DB_AFTER', $iniConfig['settings']['databaseAfterFix']);
$credsFlags = '';
if ($iniConfig['import']['user'] && $iniConfig['import']['pass']) {
define('IMPORT_USER', $iniConfig['import']['user']);
define('IMPORT_PASS', $iniConfig['import']['pass']);
$credsFlags = ' -u '.IMPORT_USER.' -p '.IMPORT_PASS;
} else {
echo PHP_EOL.'Please Define the Username and Password for connection to the Database!'.PHP_EOL;
die();
}
$output = [];
$return_var = 0;
exec('scriptor\SchemaZen.exe create -s '.IMPORT_HOST.$credsFlags.' -o -b '.IMPORT_DB. ' -d ../../DBMigrate/'.$iniConfig['ftp']['path'].'', $output, $return_var);
foreach ($output as $message) {
echo $message.PHP_EOL;
}
if (0 !== $return_var) {
$error_log = fopen($iniConfig['settings']['errorlog'], 'a+');
if ($error_log) {
foreach ($output as $error) {
$writer = fwrite($error_log, '['.date('Y-m-d h:i:s').']'.$error.PHP_EOL);
}
$notify = mail($iniConfig['settings']['mail'], 'Import Error Encoutered!', 'Errors in Import of the Server.Please Check an error log should have been Created inside the folder /Data of the importer!');
if ($notify) {
echo PHP_EOL.'Mail sent about errors!'.PHP_EOL;
}
if ($writer) {
echo PHP_EOL.'Created Error LOg Please Check!'.PHP_EOL;
}
}
}
}
The Issue
The big issue is that i developed this testing in my local environment where i am running a different SQL Server Version, and when i tried to test in a staging environment inside the live servers i encountered the following problem https://github.com/sethreno/schemazen/issues/141
I would really appreciate any good alternative ( especially built in tools in SQL Server Managing Studio, but i would need some guidance ) , or any correction that could be applied to the Schemazen since its an open source project to correct the Issue.
There are plenty of options, which I enumerated from easiest to the most complex
Backup with further Restore
Log shipping
Snapshot or Transaction Replications
Database Mirroring
Automation of the first option can be done using command shell:
https://blog.sqlauthority.com/2013/02/08/sql-server-backup-and-restore-database-using-command-prompt-sqlcmd/
Some other striking thing:
you run RTM version of SQL Server 2008 R2 on servers:
It unpatched, Microsoft released 4 service packs. RTM version has severe bugs
This version is out support
Depending upon your requirements you could simply try backup and restore which seems to satisfy your requirement. Alternatively try Replication but that adds considerably to the complexity.
There are also various tools that can do this. If you can pay for them Redgate work pretty well. I'm sure there are also free ones but I don't have experience with them.
I wouldn't recommend rolling your own.
Building a Unity front-end app that communicates with a PHP/MySQL back-end. Right now I am working on the register and login portions of it. In the Unity editor, all works perfectly, on the browser front end registration is working fine as well. But as soon as I take the working build in Unity and build it to test on my Google Pixel phone, registration and login both fail on my phone. The error message I am getting on Login is "Error parsing response from server, please try again!" which is in my UILogin.cs. Yet there is nothing else attached. I tried following the Unity documentation for debugging, adb, and DDMS to get access to find out what is happening but I have failed on all those ventures. Is there something particularly different about Android and WWW objects or web communications? Here is a portion of my UILogin.cs and also will include the Login.php.
UILogin.cs
IEnumerator AttemptLogin(bool quickLogin)
{
CreateLoadingScreen();
DeactivateForm();
WWWForm form = new WWWForm();
form.AddField("email", Email.text);
form.AddField("password", Password.text);
WWW www = new WWW(URL.GetLoginURL, form);
yield return www;
DestroyLoadingScreen();
ActivateForm();
ParseResult(www.text, quickLogin);
}
void ParseResult(string result, bool quickLogin)
{
byte resultCode;
if (!byte.TryParse(result, out resultCode))
Result.text = "Error parsing response from server, please try again!";
else if (resultCode == 0)
{
if (RememberToggle.isOn && !quickLogin) // Remember me
{
PlayerPrefs.SetInt("remember", 1);
PlayerPrefs.SetString("email", Email.text);
PlayerPrefs.SetString("password", Password.text);
}
else if (!quickLogin)
{
TemporaryAccount.Email = Email.text;
TemporaryAccount.Password = Password.text;
}
SceneManager.LoadScene(3);
}
else // Failure
{
if (quickLogin)
ShowForm();
Result.text = WebError.GetLoginError(resultCode);
}
}
Login.php
<?php
require "conn.php";
$stmt = $pdo->prepare("SELECT * FROM account WHERE email=:email");
$stmt->bindParam(":email", $_POST['email']);
$stmt->execute();
$count = $stmt->rowCount(); // gets count of records found
if($count > 0) {
$result = $stmt->fetch(); // gets resultset
if(!password_verify($_POST['password'], $result[4]))
echo "2";
else
echo "0";
}
else {
echo "1";
}
?>
Any ideas?
Update #1
I printed www.text and www.error after the yield return www; Text is null and error says: Unknown Error.
Update #2
Interestingly enough, I get Unknown Error from this as well:
Clickme.cs
using System.Collections;
using UnityEngine;
using UnityEngine.UI;
public class Clickme : MonoBehaviour
{
public Text Result;
public void OnClick()
{
StartCoroutine(RunScript());
}
IEnumerator RunScript()
{
WWW www = new WWW("http://www.familypolaris.com/helloWorld.php");
yield return www;
if (www.text == "")
Result.text = "Result was empty, error: " + www.error;
}
}
HelloWorld.php
<?php
echo "Hello World!";
?>
I figured it out, so I will post the answer here. After somebody commented that they tried my code and it worked just fine, I decided to try another device here. That device also failed to register and login. This told me something was wrong with my build settings. My first idea was to switch build type from Gradle to Internal, and that solved the problem for both my devices immediately.
I am trying to connect to a MS SQL database through Unity. However, when I try to open a connection, I get an IOException: Connection lost.
I have imported System.Data.dll from Unity\Editor\Data\Mono\lib\mono\2.0. I am using the following code:
using UnityEngine;
using System.Collections;
using System.Data.Sql;
using System.Data.SqlClient;
public class SQL_Controller : MonoBehaviour {
string conString = "Server=myaddress.com,port;" +
"Database=databasename;" +
"User ID=username;" +
"Password=password;";
public string GetStringFromSQL()
{
LoadConfig();
string result = "";
SqlConnection connection = new SqlConnection(conString);
connection.Open();
Debug.Log(connection.State);
SqlCommand Command = connection.CreateCommand();
Command.CommandText = "select * from Artykuly2";
SqlDataReader ThisReader = Command.ExecuteReader();
while (ThisReader.Read())
{
result = ThisReader.GetString(0);
}
ThisReader.Close();
connection.Close();
return result;
}
}
This is the error I get:
IOException: Connection lost
Mono.Data.Tds.Protocol.TdsComm.GetPhysicalPacketHeader ()
Mono.Data.Tds.Protocol.TdsComm.GetPhysicalPacket ()
Mono.Data.Tds.Protocol.TdsComm.GetByte ()
Mono.Data.Tds.Protocol.Tds.ProcessSubPacket ()
Mono.Data.Tds.Protocol.Tds.NextResult ()
Mono.Data.Tds.Protocol.Tds.SkipToEnd ()
Rethrow as TdsInternalException: Server closed the connection.
Mono.Data.Tds.Protocol.Tds.SkipToEnd ()
Mono.Data.Tds.Protocol.Tds70.Connect (Mono.Data.Tds.Protocol.TdsConnectionParameters connectionParameters)
Mono.Data.Tds.Protocol.Tds80.Connect (Mono.Data.Tds.Protocol.TdsConnectionParameters connectionParameters)
Please disregard any security risks with this approach, I NEED to do this for testing, security will come later.
Thank you for your time.
Please disregard any security risks with this approach
Do not do it like this. It doesn't matter if security will come before or after. You will end of re-writing the whole code because the password is hard-coded in your application which can be decompiled and retrieved easily. Do the connection the correct way now so that you won't have to re-write the whole application.
Run your database command on your server with php, perl or whatever language you are comfortable with but this should be done on the server.
From Unity, use the WWW or UnityWebRequest class to communicate with that script and then, you will be able to send and receive information from Unity to the server. There are many examples out there. Even with this, you still need to implement your own security but this is much more better than what you have now.
You can also receive data multiple with json.
Below is a complete example from this Unity wiki. It shows how to interact with a database in Unity using php on the server side and Unity + C# on the client side.
Server Side:
Add score with PDO:
<?php
// Configuration
$hostname = 'localhot';
$username = 'yourusername';
$password = 'yourpassword';
$database = 'yourdatabase';
$secretKey = "mySecretKey"; // Change this value to match the value stored in the client javascript below
try {
$dbh = new PDO('mysql:host='. $hostname .';dbname='. $database, $username, $password);
} catch(PDOException $e) {
echo '<h1>An error has ocurred.</h1><pre>', $e->getMessage() ,'</pre>';
}
$realHash = md5($_GET['name'] . $_GET['score'] . $secretKey);
if($realHash == $hash) {
$sth = $dbh->prepare('INSERT INTO scores VALUES (null, :name, :score)');
try {
$sth->execute($_GET);
} catch(Exception $e) {
echo '<h1>An error has ocurred.</h1><pre>', $e->getMessage() ,'</pre>';
}
}
?>
Retrieve score with PDO:
<?php
// Configuration
$hostname = 'localhost';
$username = 'yourusername';
$password = 'yourpassword';
$database = 'yourdatabase';
try {
$dbh = new PDO('mysql:host='. $hostname .';dbname='. $database, $username, $password);
} catch(PDOException $e) {
echo '<h1>An error has occurred.</h1><pre>', $e->getMessage() ,'</pre>';
}
$sth = $dbh->query('SELECT * FROM scores ORDER BY score DESC LIMIT 5');
$sth->setFetchMode(PDO::FETCH_ASSOC);
$result = $sth->fetchAll();
if(count($result) > 0) {
foreach($result as $r) {
echo $r['name'], "\t", $r['score'], "\n";
}
}
?>
Enable cross domain policy on the server:
This file should be named "crossdomain.xml" and placed in the root of your web server. Unity requires that websites you want to access via a WWW Request have a cross domain policy.
<?xml version="1.0"?>
<cross-domain-policy>
<allow-access-from domain="*"/>
</cross-domain-policy>
Client/Unity Side:
The client code from Unity connects to the server, interacts with PDO and adds or retrieves score depending on which function is called. This client code is slightly modified to compile with the latest Unity version.
private string secretKey = "mySecretKey"; // Edit this value and make sure it's the same as the one stored on the server
public string addScoreURL = "http://localhost/unity_test/addscore.php?"; //be sure to add a ? to your url
public string highscoreURL = "http://localhost/unity_test/display.php";
//Text to display the result on
public Text statusText;
void Start()
{
StartCoroutine(GetScores());
}
// remember to use StartCoroutine when calling this function!
IEnumerator PostScores(string name, int score)
{
//This connects to a server side php script that will add the name and score to a MySQL DB.
// Supply it with a string representing the players name and the players score.
string hash = Md5Sum(name + score + secretKey);
string post_url = addScoreURL + "name=" + WWW.EscapeURL(name) + "&score=" + score + "&hash=" + hash;
// Post the URL to the site and create a download object to get the result.
WWW hs_post = new WWW(post_url);
yield return hs_post; // Wait until the download is done
if (hs_post.error != null)
{
print("There was an error posting the high score: " + hs_post.error);
}
}
// Get the scores from the MySQL DB to display in a GUIText.
// remember to use StartCoroutine when calling this function!
IEnumerator GetScores()
{
statusText.text = "Loading Scores";
WWW hs_get = new WWW(highscoreURL);
yield return hs_get;
if (hs_get.error != null)
{
print("There was an error getting the high score: " + hs_get.error);
}
else
{
statusText.text = hs_get.text; // this is a GUIText that will display the scores in game.
}
}
public string Md5Sum(string strToEncrypt)
{
System.Text.UTF8Encoding ue = new System.Text.UTF8Encoding();
byte[] bytes = ue.GetBytes(strToEncrypt);
// encrypt bytes
System.Security.Cryptography.MD5CryptoServiceProvider md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
byte[] hashBytes = md5.ComputeHash(bytes);
// Convert the encrypted bytes back to a string (base 16)
string hashString = "";
for (int i = 0; i < hashBytes.Length; i++)
{
hashString += System.Convert.ToString(hashBytes[i], 16).PadLeft(2, '0');
}
return hashString.PadLeft(32, '0');
}
This is just an example on how to properly do this. If you need to implement session feature and care about security, look into the OAuth 2.0 protocol. There should be existing libraries that will help get started with the OAuth protocol.
An alternative would be to create your own dedicated server in a command prompt to do your communication and connecting it to unity to Handel multiplayer and SQL communication. This way you can stick with it all being created in one language. But a pretty steep learning curve.
Unity is game engine.
so That's right what the answer says.
but, Some domains need to connect database directly.
You shouldn't do that access database directly in game domain.
Anyway, The problem is caused by NON-ENGLISH computer name.
I faced sort of following errors at before project.
IOException: Connection lost
Mono.Data.Tds.Protocol.TdsComm.GetPhysicalPacketHeader ()
Mono.Data.Tds.Protocol.TdsComm.GetPhysicalPacket ()
Mono.Data.Tds.Protocol.TdsComm.GetByte ()
Mono.Data.Tds.Protocol.Tds.ProcessSubPacket ()
Mono.Data.Tds.Protocol.Tds.NextResult ()
Mono.Data.Tds.Protocol.Tds.SkipToEnd ()
Rethrow as TdsInternalException: Server closed the connection.
Mono.Data.Tds.Protocol.Tds.SkipToEnd ()
Mono.Data.Tds.Protocol.Tds70.Connect (Mono.Data.Tds.Protocol.TdsConnectionParameters connectionParameters)
Mono.Data.Tds.Protocol.Tds80.Connect (Mono.Data.Tds.Protocol.TdsConnectionParameters connectionParameters)
And after changing computer name as ENGLISH, It works.
I don't know how it's going. But It works.
Mono's System.Data.dll has some issues in P.C has NON-ENGLISH Computer name.
So, at least Unity project.
You should tell your customer Do not set their computer name as NON-ENGLISH.
I don't know people in mono knows these issue or not.
---------- It's OK in after 2018 version ----------
Api Compatibility Level > .Net 4.x
You can connect database in Non-english computer name machine.
My company has purchased the CoolUtils TotalPDFPrinterX from https://www.coolutils.com/TotalPDFPrinterX
I make an HTTP PUT from Postman to the API and I get “Could not get any response”.
When running on my Windows machine the PDF prints fine however on the server the site crashes and in the event log I get the error "A process serving application pool '[MY_APP_POOL]' failed to respond to a ping. The process id was '[MY_PROCESS_ID]'."
Here is my C# code:
PDFPrinterX ppx = new PDFPrinterX();
ppx.Print(fileName, printerName, "-ap Default");
if (ppx.ErrorMessage != null)
{
WriteToSQL(id, false, ppx.ErrorMessage, 2);
Console.WriteLine(ppx.ErrorMessage);
}
By writing to the event log I know the site crashes on this line: PDFPrinterX ppx = new PDFPrinterX(); I have also surrounded the above code with a try catch and no exception is thrown. The site still crashes.
Things I have tried:
Uninstalling and Reinstalling the CoolUtils software
Giving EVERYONE Full control to the site folder and the CoolUtils program folder
Creating a C# desktop application using the same code. THIS WORKS FINE ON THE SERVER. It's just the ASP site that crashes.
Does anyone know what might be causing this?
The more I research this thing online the more I'm inclined to say that ActiveX which is the X in PDFPrinterX doesn't seem to work well when hosted in IIS.
I've seen a few forums where they say it works fine when they debug on localhost but when deployed to server is crashes.
...works fine when used inside localhost(Visual studio)
One of their feature pages shows that it requires Win 2000/NT/XP/2003/Vista/7
You should look into whether your server supports ActiveX components that can work in conjunction with IIS.
Looking at one of their other products support page: TotalPDFConverterX:
the following note in my opinion may also apply to TotalPDFPrinterX, given its dependency on ActiveX as well.
Note: Pay attention to some details during installation Total PDF Converter X:
Do not forget to register ActiveX in your web-server account.
Total PDF Converter X supports only Internet Explorer, Mozilla and Firefox browsers.
ActiveX works only with 32-bit internet information server. 64-bit server is not supported. Use command line version instead.
Thanks to #Nkosi I was able to find a workaround.
ActiveX works only with 32-bit internet information server. 64-bit server is not supported. Use command line version instead.
Our IIS server is 64 bit so that is what probably caused the site to hang up.
Buttt... the command line still worked in printing the PDFs on the server.
Client side code (makes the HTTP POST):
private void SendToPrinter(string fileName, string printerName, int id, decimal documentSequence)
{
// use http client to make a POST to the print api
using (var client = new HttpClient())
{
// compile the values string to transfer in POST
// should finish to look something like this:
// C:\print.pdf&PRTFTW_OFIT&ValShip-155320-1
var values = new Dictionary<string, string>
{
{ "", fileName + "&" + printerName + "&ValShip-" + id + "-" + documentSequence},
};
// URL encode the values string
var content = new FormUrlEncodedContent(values);
// make the POST
// DEBUG
var response = client.PostAsync("http://localhost:54339/api/print", content);
// retrieve the response
var responseString = response.Result.ToString();
}
}
Server side code (receives the HTTP POST):
using System;
using System.Net.Http;
using System.Web;
using System.Web.Http;
namespace api.valbruna.print.Controllers
{
public class PrintController : ApiController
{
// POST api/print
public HttpResponseMessage Post(HttpRequestMessage request)
{
try
{
// parse the content recieved from the client
var content = request.Content.ReadAsStringAsync().Result;
// decode the content, certain characters such as
// '&' get encoded to URL lingo such as '%26'
content = HttpUtility.UrlDecode(content);
// split the string into 3 seperate parts
String[] str = content.Split('&');
// remove the equal sign from the first string
str[0] = str[0].Trim('=');
// compile the arguments command line string
// should finish to look something like this:
// "C:\Program Files (x86)\CoolUtils\Total PDF PrinterX\PDFPrinterX.exe" "C:\print.pdf" -p"\\PRINTERS\PRTFTW_OFIT" -ap Default -log "C:\inetpub\logs\CoolUtils\log-ValShip-155320-4.txt" -verbosity detail"
String arguments = "\"" + str[0] + "\" -p\"\\\\PRINTERS\\" + str[1] +
"\" -ap Default -log \"C:\\inetpub\\logs\\CoolUtils\\log-" + str[2] +
".txt\" -verbosity detail";
// file location for PDFPrinterX.exe
String file = #"C:\Program Files (x86)\CoolUtils\Total PDF PrinterX\PDFPrinterX.exe";
// start the process
System.Diagnostics.Process process = new System.Diagnostics.Process();
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal;
startInfo.FileName = file;
startInfo.Arguments = arguments;
process.StartInfo = startInfo;
process.Start();
return new HttpResponseMessage() { Content = new StringContent(content) };
}
catch (Exception e)
{
return new HttpResponseMessage() { Content = new StringContent(e.Message) };
}
}
}
}
I am writing a game in Unity3D and I was wondering if there are any tools available to check a server for an update, if so, download and install the update.
I have been trying to write my own, however I am stuck on the "Download and Install" part.
This is what I have:
//Unity3D Patching Tool v0.1
using UnityEngine;
using System.Collections;
public class Patcher : MonoBehaviour {
public const string VERSION = "1.0"; // The version of the program that is running
private string patchUrl = "http://yoursite.com/patchversion.html"; //a website with the current build number
//a template to find the current build for windows
private const string UPDATE_WINDOWS_URL_TEMPLATE = "http://yoursite.com/release/build[[[BUILD_NUMBER]]].exe";
//a template to find the current build for mac
private const string UPDATE_MAC_URL_TEMPLATE = "http://yoursite.com/release/build[[[BUILD_NUMBER]]].app";
IEnumerator Start() {
/*
* Check for patch
*/
WWW patchwww = new WWW(patchUrl); //create new web connection to the build number site
yield return patchwww; // wait for download to finish
if (patchwww.text == VERSION){ //check version
Debug.Log("Up To Date");
}
else {
Debug.Log("Download New Update");
WWW downloadwww = new WWW(DownloadUpdate(patchwww.text)); // generates link to current build and downloads
yield return downloadwww;
}
}
private string DownloadUpdate(string version){
string versionNumber = version.Replace(".", ""); //remove periods in version number
string buildToDownload = "";
/*
* Check Platform and Set URL
*/
switch (Application.platform){
case RuntimePlatform.WindowsEditor:
case RuntimePlatform.WindowsPlayer:
Debug.Log("Windows " + Application.platform);
buildToDownload = UPDATE_WINDOWS_URL_TEMPLATE.Replace("[[[BUILD_NUMBER]]]", versionNumber);
break;
case RuntimePlatform.OSXEditor:
case RuntimePlatform.OSXPlayer:
Debug.Log("Mac " + Application.platform);
buildToDownload = UPDATE_MAC_URL_TEMPLATE.Replace("[[[BUILD_NUMBER]]]", versionNumber);
break;
}
Debug.Log(buildToDownload);
return buildToDownload;
}
}
I have something similar, I have the http download a text file that has the latestversion within it, if their version is lower then this, they have the option to download an installer
if you are using this on windows, you could then have unity run a external process ( a simple c# form that updates your files, or that downloads a installer waits for it to complete then executes it) [probably possible within unity as well, but this works well for me]
(you could also just point the process at the web browser with the link to the latest version this way the browser or their default file downloader will be responsible for downloading the program and will handle communication errors) this way they would know that they need to open the installed app once it is complete
import System.Diagnostics;
var path:String = "somewhere";
var foo:Process = new Process();
function Start()
{
foo.StartInfo.FileName = "someprogram";
foo.StartInfo.Arguments = path;
foo.Start();
}