How to send data form to server using json in unity - c#

I want to using json to send the form to my server
here is my C# code
public string db_url="http://localhost/";
IEnumerator SaveAllPlayerPrefs(object[] parms)
{
string ourPostData = "{\"bone\":\"42\"}";
Hashtable headers = new Hashtable();
headers.Add("Content-Type", "application/json");
headers.Add("Cookie", "Our session cookie");
byte[] pData = System.Text.Encoding.UTF8.GetBytes(ourPostData);
WWW webRequest = new WWW(db_url + "SaveAllPlayerPref.php", pData, headers);
yield return webRequest;
}
and here is my php code:
<?php
$sql_connect = mysql_connect("localhost", "root", "") or die ("no DB Connection");
mysql_select_db("example") or die ("DB not found");
$bone = $_POST['bone'];
mysql_query("INSERT INTO save_game (bone) VALUES ('$bone');");
mysql_close($sql_connect);
?>
When i run it this code its running, but when i check the database, its not save the value of bone. It's save the empty string to bone, i want it to save 42..
it insert new row in my database, but with empty value of "bone"
in my database bone is varchar(100) and utf8_general_ci.
Can someone explain to me?
thx before:)

Try var_dump($_POST) to see what you receive.

Related

Not posting to database

I'm pretty new with this Database / server stuff, so please bear with me. I'm having trouble figuring out why these variables aren't posting to my DB from Unity.
My DB connection information is correct, as other posts are working.
here's my php:
- I've replaced the $_POST variables below with non-post variables and they work just fine! So I'm relatively happy with my php code.
<?php
$servername = "localhost";
$DBusername = "id*****_zingzingzingbah";
$DBpassword = "*******";
$DBName = "id430563_fitness2017";
$firstname = $_POST["firstnamePOST"];
$lastname = $_POST["lastnamePOST"];
$username = $_POST["usernamePOST"];
$email = $_POST["emailPOST"];
$password = $_POST["passwordPOST"];
//$firstname = "aaaa";
//$lastname = "aaaa";
//$username = "aaaa";
//$email = "aaaa";
//$password = "aaaa";
// Make Connection
$conn = new mysqli($servername,$DBusername, $DBpassword, $DBName);
// Check Connection
if (!$conn) {
die ("Connection Failed. ". mysqli_connect_error());
} else { echo "Connection Success" ; // display some text or info on the screen }
$sql = "INSERT INTO user_info (firstname, lastname, username, email, password) VALUES('".$firstname."','".$lastname."','".$username."','".$email."','".$password."')";
$result = mysqli_query($conn, $sql);
if(!$result) {
echo "there was an error creating user specific table";
} else {
echo "Everything OK2";
}
?>
See Unity C# code below...
- I have two CreateUser functions below so that the void one, can be accessed from Unity... I had trouble accessing IEnumerator functions otherwise.
- the code gets stuck after insertUserInfo = new WWW (InsertUserInfoURL,form);
- the yield return isn't returning.
public void CreateUser(string inputFirstname, string inputLastname, string inputUsername,string inputEmail,string inputPassword ){
StartCoroutine (CreateUser2 (inputFirstname,inputLastname,inputUsername,inputEmail,inputPassword));
}
private IEnumerator CreateUser2(string inputFirstname, string inputLastname, string inputUsername,string inputEmail,string inputPassword ){
WWWForm form = new WWWForm ();
inputFirstname = "bbb";
inputLastname = "bbb";
inputUsername = "bbb";
inputEmail = "bbb";
inputPassword = "bbb";
form.AddField ("firstnamePOST", inputFirstname);
form.AddField ("lastnamePOST", inputLastname);
form.AddField ("usernamePOST", inputUsername);
form.AddField ("emailPOST", inputEmail);
form.AddField ("passwordPOST", inputPassword);
print("getting here ok");
insertUserInfo = new WWW (InsertUserInfoURL,form);
yield return insertUserInfo;
print("why aren't you getting here");
I'm sure the URL is correct (base on test without POST variables)
I'm sure the DB info is correct (base on test without POST variables)
I'm sure the SQL code is correct (base on test without POST variables)
I'm definitely calling the CreateUser functions (both of them)
would appreciate any tips on troubleshooting this stuff, because I feel like I'm fumbling in the dark
thanks guys!
Ok, so I finally figured it out...
I was changing my scene in Unity before the WWW request had time to resolve..
probably down to horrible coding on my behalf!
thanks everyone for your comments

C# Extracting data from Json or DataSets - Porting from Python (Json to Dict)

I have the following Python script which I need to port to C#. This gets a JSON response from a URL and then pops it into a dictionary. Then it checks for the data next_page and if there is data (it's not empty) it then returns true. Underneath I'll paste the C# code I have but I'm really struggling to do the final part. I don't know and I certainly don't want to understand the data in the JSON response, I just want to know if the field next_page is there.
# Gets JSON response
response = requests.get(url, auth=(user, pwd))
if response.status_code != 200:
print('Status:', response.status_code, 'Problem with the request. Exiting.')
exit()
data = response.json()
if(data['next_page']):
return True
else:
return False
So this is the c# code I've got:
using Newtonsoft.Json;
string response = "";
using (WebClient client = new WebClient())
{
client.UseDefaultCredentials = true;
client.Credentials = new NetworkCredential(user, password);
try
{
response = client.DownloadString(url);
} catch (Exception e)
{
throw e;
}
}
XmlDocument xml = JsonConvert.DeserializeXmlNode(json, "RootObject");
XmlReader xr = new XmlNodeReader(xml);
DataSet ds = new DataSet("Json Data");
ds.ReadXml(xr);
From what I've seen on the web DataSets work best when you know what the data inside of it is. I just want to know if there is a field called next_page and if there is, is it empty or does it have data. I'm just struggling to get anything out of the DataSet.
You will want to include the JSON.net nuget package (http://james.newtonking.com/json) this lets you deserialize the JSON response into a dictionary (or preferably a new class) allowing you to access the response.
eg add this into your try catch after including the library
var dict = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, string>>(response);
Alternativly you could create a new class that represents the expected JSON and deserialize into that
public class ResponseObject
{
public string next_page { get; set; }
}
var responseResult = Newtonsoft.Json.JsonConvert.DeserializeObject<ResponseObject>(response);

Unity 3D secure authentication with SQL

I'm developing an android application in unity 3d that will have network communications for user accounts updating said accounts as well as controlling everything on the back end of the app. I use the WWW class in unity to send info to the server. The backend is php and all the data is stored in a mysql database. How can I make a secure connection between the app and the backend without someone just simply getting the servers address and blocking it in their hosts file and feeding the app false info and going online with it.(as an example) I'm no security expert but I'm not sure what I need to look in too in order to create secure connections between server and client. Any help would be greatly apericiated. Thank you.
you just need to implement the www class
void start()
{
StartCoroutine(retrieveHighscores()); //Start out by getting the current scores.
}
IEnumerator retrieveHighscores()
{
var form = new WWWForm(); // create a new form
form.AddField("Nipun",name); // add the data you want to retrieve in the form fields
var rawData = form.data;
var headers = form.headers; // here headers will be used to authenticate the credentials of the person trying to access
headers["Authorization"]="Basic " + System.Convert.ToBase64String(System.Text.Encoding.ASCII.GetBytes("username:password"));
WWW webRequest = new WWW("https://abc.com/test.php", rawData, headers); //
yield return webRequest;
if (webRequest != null) {
//here you have successfully got the response back from the server , here i am adding the whole response in a string and then splitting the string based on the format of the data i received.
string x = webRequest.text;
string[] lines = webRequest.text.Split(new string[] { System.Environment.NewLine }, System.StringSplitOptions.RemoveEmptyEntries); //Split the response by newlines.
Debug.Log(x); // to check what you received
scores = new Dictionary<string, int>(); //Always reset our scores, as we just got new ones.
foreach (string line in lines) //Parse every line
{
// code here how you want to use the split up data you received
}
}
else
Debug.Log("error");
}
}

How to get the facebook signed request in c#

I'm new to Facebook apps. I'm trying to create an MVC 4 application with Facebook Application as my Project Template.
I'm trying to catch the page id on which the page tab is created and I've got it somehow.
My problem here is when someone visits my app, I want to know the page id through which they are viewing the page tab. I've searched a lot where I got to know that I've to use FacebookSignedRequest for this. But this class is not available to me.
Thanks in advance for any help.
If you are simply trying to parse the signed_request parameter from Facebook, you can do so using the following C# code.
This code also verifies the hash using your own app_secret param, to ensure the signed_request originated from Facebook.
public static string DecodeSignedRequest(string signed_request)
{
try
{
if (signed_request.Contains("."))
{
string[] split = signed_request.Split('.');
string signatureRaw = FixBase64String(split[0]);
string dataRaw = FixBase64String(split[1]);
// the decoded signature
byte[] signature = Convert.FromBase64String(signatureRaw);
byte[] dataBuffer = Convert.FromBase64String(dataRaw);
// JSON object
string data = Encoding.UTF8.GetString(dataBuffer);
byte[] appSecretBytes = Encoding.UTF8.GetBytes(app_secret);
System.Security.Cryptography.HMAC hmac = new System.Security.Cryptography.HMACSHA256(appSecretBytes);
byte[] expectedHash = hmac.ComputeHash(Encoding.UTF8.GetBytes(split[1]));
if (expectedHash.SequenceEqual(signature))
{
return data;
}
}
}
catch
{
// error
}
return "";
}
private static string FixBase64String(string str)
{
while (str.Length % 4 != 0)
{
str = str.PadRight(str.Length + 1, '=');
}
return str.Replace("-", "+").Replace("_", "/");
}
All I had to do was create a Facebook Client object and call the ParseSignedRequest method with the app secret.
var fb = new FacebookClient();
dynamic signedRequest = fb.ParseSignedRequest(appSecret, Request.Form["signed_request"]);
This returns a Json object which we have to parse using JObject.Parse

Desktop app to create event through a facebook page

I have a facebook fanpage and I am trying to make a desktop application which can create events through this fanpage, however I'm having trouble understanding how the story goes with acces tokens, id, user permissions... If I am not mistaken once I have the accesstoken I can create an event using the facebookSDK from codeplex and the following function:
public string CreateEvent(string accessToken)
{
FacebookClient facebookClient = new FacebookClient(accessToken);
Dictionary<string, object> createEventParameters = new Dictionary<string, object>();
createEventParameters.Add("name", "My birthday party )");
createEventParameters.Add("start_time", DateTime.Now.AddDays(2).ToUniversalTime().ToString());
createEventParameters.Add("end_time", DateTime.Now.AddDays(2).AddHours(4).ToUniversalTime().ToString());
createEventParameters.Add("owner", "Balaji Birajdar");
createEventParameters.Add("description", " ( a long description can be used here..)");
//Add the "venue" details
JsonObject venueParameters = new JsonObject();
venueParameters.Add("street", "dggdfgg");
venueParameters.Add("city", "gdfgf");
venueParameters.Add("state", "gfgdfgfg");
venueParameters.Add("zip", "gfdgdfg");
venueParameters.Add("country", "gfdgfg");
venueParameters.Add("latitude", "100.0");
venueParameters.Add("longitude", "100.0");
createEventParameters.Add("venue", venueParameters);
createEventParameters.Add("privacy", "OPEN");
createEventParameters.Add("location", "fhdhdfghgh");
Add the event logo image
FacebookMediaObject logo = new FacebookMediaObject()
{
ContentType = "image/jpeg",
FileName = #"C:\logo.jpg"
};
logo.SetValue(File.ReadAllBytes(logo.FileName));
createEventParameters["#file.jpg"] = logo;
JsonObject resul = facebookClient.Post("/me/events", createEventParameters) as JsonObject;
return resul["id"].ToString();
}
Do I always need an application to do this?
I have a test application and I can get an access token from it using:
public string getToken(string strURL)
{
string strURL = "https://graph.facebook.com/oauth/access_token?client_id=149585851811979&client_secret=blablablablabalalbal&grant_type=client_credentials";
Uri Uri = new Uri(strURL);
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(Uri);
HttpWebResponse HWResponse = (HttpWebResponse)request.GetResponse();
StreamReader sr = new StreamReader(HWResponse.GetResponseStream());
string token = sr.ReadToEnd();
sr.Close();
token = token.Replace("access_token=", "");
return token;
}
I tried it like this but it obviously didn't work.
So my questions:
Do I always need an application? If yes, how do i connect it to my existing fan page?
Where do I set my user permissions? And how do I then login with the user?
I just think the documentation is a bit vague :s Sorry if my questions are stupid.
Any help/pseudocode is appreciated!
I am using BatchFB to create events in an App Engine app, it works for me, here is the code
// Some Date math that is from my App, but I am using Joda DateTime for output
// formatting.. I have found that if the start_time is malformed by FB standards it will
// to create an event, and give you an eventid, but the event never really gets created.
long hour = { your data }
DateTime start_time = new DateTime(d).plusHours((int)hour);
String stime = start_time.toString(ISODateTimeFormat.dateTime());
Batcher batcher = new FacebookBatcher(token);
Later<NewFeedItem> event = batcher.post(
"/events", NewFeedItem.class,
new Param("name", edata.getStringProperty(EventData.Schema.Name)),
new Param("start_time", stime )
);
long eventid = event.get().id;
I generate token on the client side with FBJS, and pass it to the server.
NewFeedItem is just a class defining an long variable, see batchFB's site..
With that said, I am thinking of switching to RestFB because I can't get BatchFB to support binary parameters with trying to post images. Also RestFB is documented better.. They seem to be related projects and refer to each other often.
I am not adding in Venue data yet, but I have read that for the GraphAPI to work, they need to be top level parameters. i.e. add in street, city, state at the same level as location and privacy..
When you try to read the event it will come in the venue parameter, but it needs to be top level when creating.. Also fallback to just using name and start_time, the only required parameters and add to that once it's working.
-John Gentilin

Categories