So I want to connect to my Azure Sql Database using in a unity project,
I used this code provided in the readme of app services Github project:
public class AzureConnect : MonoBehaviour {
private MobileServiceClient _client;
private MobileServiceTable<Score> _table;
// Use this for initialization
void Start () {
_client = new MobileServiceClient("https://myService.azurewebsites.net"); // <- add your app url here.
_table = _client.GetTable<Score>("Score");
ReadItems();
}
private void ReadItems()
{
StartCoroutine(_table.Read<Score>(OnReadItemsCompleted));
}
private void OnReadItemsCompleted(IRestResponse<Score[]> response)
{
if (!response.IsError)
{
Debug.Log("OnReadCompleted: " + response.Url + " data: " + response.Content);//content shows the content of the table properly
Score[] items = response.Data;//Data is always null
Debug.Log("Todo items count: " + items.Length);
}
else
{
Debug.LogWarning("Read Error Status:" + response.StatusCode + " Url: " + response.Url);
}
}
}
The code works perfectly and connects to my DB just fine but for some reason the response DATA is always null although the response CONTENT returns a string with the data in the scores table just fine Any Idea what could be the problem?
PS: the url of the App service is not the real one I use just for demo purpose.
Well I've been struggling with this for hours , and after 6 min of posting the question I figure out the answer so here is the Answer so anyone that faces this problem can know the cause:
The Problem was that I didn't declare my Score Class as [Serializable] as soon as I declared it this way it worked perfectly.
Related
I am using Firesharp for my app in c# winforms. This database is also connected to my ReactJS website which deals with the same information.
I have noticed that when I make .SetAsync calls to my app on the website and then log in to my Winforms app, my WinForms app will automatically perform the last action I did on my website to my database which is a .setAsync() action which adds some user information to a list of other user's information. Now it will not stop. Anytime I log on to my c# app, it runs it.
It makes me think there is a queue of orders in firesharp?
here is my react code. From what I can tell, it is nothing out of the ordinary:
async function handleSubmit(e) {
e.preventDefault()
var date = moment().format("MM/DD/YYYY" )
setError("")
setLoading(true)
// grab user info first then use that.
await firebaseApp.database().ref("Users/" + currentUser.uid + "/UserData").on('value', snapshot => {
if (snapshot.val() != null) {
setContactObjects({
...snapshot.val()
})
firebaseApp.database().ref("Projects/" + projectGUIDRef.current.value + "/queueList/" + userIdRef.current.value).set({
"EntryTimeStamp": date + " " + moment().format("hh:mm:ss a"),
"IsSyncing": false,
"UserId": userIdRef.current.value,
"UserName": usernameRef.current.value,
})
}
})
history.push("/Demo")
setLoading(false)
}
here is my c# winforms code of where the code is executing. For some reason, when this executes, it also updates the EntryTimeStamp field of the react code and completely sets all the information even if I delete it. It also happens if I run .set().
updateLastLogin2(authLink);
private async void updateLastLogin2(FirebaseAuthLink authLink)
{
IFirebaseConfig config = new FireSharp.Config.FirebaseConfig
{
AuthSecret = this.authLink.FirebaseToken,
BasePath = Command.dbURL,
};
IFirebaseClient client = new FireSharp.FirebaseClient(config);
string newDateTime = DateTime.Now.ToString();
if (authLink.User.DisplayName.Contains(adUserId) && authLink.User.DisplayName.Contains(adUserId))
{
await client.SetAsync("Users/" + this.authLink.User.LocalId + "/UserData/DateLastLogin", newDateTime);
}
}
Any and all help is appreciated, I've been at this for a day and a half now.
I have never used fire-sharp but this is my guess
You are calling await firebaseApp.database().ref("Users/" + currentUser.uid + "/UserData").on('value' in your react, and then in your Csharp you are calling client.SetAsync("Users/" + this.authLink.User.LocalId .
What happens is the both listeners are listening to each other and then causing a loop.
In that case it's probably better to use once instead of on if you are just using it once.
In cases where you cannot use .once, then you should use .off to turn off the listener once you are done.
firebaseApp.database().ref("Users/" + currentUser.uid + "/UserData").once('value'`
You also shouldn't be using await here since ref().on creates a listener, it doesn't return a promise.
You should also move history.push("/Demo") into your firebase database callback function so it's called after you have set data
I would like to generate a 3D scenario for a traffic simulation.
The main idea would be having SUMO running a simulation and then getting the direction, speed and coordinates (X,Y) from each vehicle, so that I would create 3D models for this cars.
For this purpose, I was thinking about using some kind of TCP/IP communication between Unity and SUMO. Since this is possible while communicating SUMO with a network simulator such as OMNeT++, I was wondering if this would also be possible. I don't need to control the simulation in SUMO from Unity, just retrieve data regarding the vehicles in the network.
Unfortunately, I have no remarkable experience with Unity, so I cannot provide any code trying to achieve this...
EDIT:
As requested, I included some code. However, I only have code in Java.
String configFile = "test/resources/sumo_maps/Test2/Test2.sumo.cfg";
SumoTraciConnection trial = new SumoTraciConnection(configFile,-1);
trial.runServer();
Collection<Vehicle> vehicles = trial.getVehicleRepository().getAll().values();
for(Vehicle car : vehicles){
bw.write(time + " // The vehicle with ID: " + car.getID()+ " is driving "
+ "with a speed of "+ car.getSpeed() + " and is in coordinates x: " +car.getPosition().getX()+
" and y: " + car.getPosition().getY());
bw.newLine();
}
Now, let's proceed to get a bit into the class SumoTraciConnection and its methods. This class is part of the mentioned (in the comments) library Traci4j.
It can be found in GitHub in case you need more info: https://github.com/egueli/TraCI4J/blob/master/src/java/it/polito/appeal/traci/SumoTraciConnection.java
The constructor:
public SumoTraciConnection(String configFile, int randomSeed) {
this.randomSeed = randomSeed;
this.configFile = configFile;
}
Now the runServer() method (I put the one with a boolean argument because if no parameter is given then it is automatically called with a false) Basically, this boolean is used to determine wheter the GUI version of SUMO or the console version will be ran:
public void runServer(boolean withGui) throws IOException, InterruptedException {
retrieveFromURLs(); //Checks if the configFile given has an "http://" at the beggining, in order to download the file
int port = findAvailablePort(); //creates a Socket and finds a port with ServerSocket.getLocalPort()
runSUMO(port, withGui); //It is used to run SUMO with different options, such as the configFile for the simulation, the remote port... sumoProcess is set here as: sumoProcess = Runtime.getRuntime().exec(argsArray);, where argsArray contains the different options mentioned
tryConnect(InetAddress.getLocalHost(), port, sumoProcess); // tryConnect basicaly calls this method tryConnectOnce, which connects as a client to the sumo process mentioned before, and does some checks that everything is correct.
postConnect(); //I will explain this function after
}
postConnect() initialices the DataInput and DataOutput streams and creates the repositories. I show now the relevant parts of the code:
dis = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
dos = new DataOutputStream(new BufferedOutputStream(socket.getOutputStream()));
vehicles = new HashMap<String, Vehicle>();
edgeRepo = new Repository.Edges(dis, dos, newIDListQuery(Constants.CMD_GET_EDGE_VARIABLE));
addStepAdvanceListener(edgeRepo);
laneRepo = new Repository.Lanes(dis, dos, edgeRepo, newIDListQuery(Constants.CMD_GET_LANE_VARIABLE));
vehicleListQuery = newIDListQuery(Constants.CMD_GET_VEHICLE_VARIABLE);
addStepAdvanceListener(new StepAdvanceListener() {
public void nextStep(double step) {
vehicleListQuery.setObsolete();
}
});
vehicleListBefore = new HashSet<String>(vehicleListQuery.get());
vehicleRepo = new Repository.Vehicles(dis, dos, edgeRepo, laneRepo, vehicles, vehicleListQuery);
addStepAdvanceListener(vehicleRepo);
Where one StepAdvanceListener is just the following(I cannot explain exactly what is this for but I understand that is something that allow us to realize the new simulationstep has been done, so we have to update the repositories):
//Interface for an object that can be notified when the simulation advances by one step.
public interface StepAdvanceListener {
/**
* Callback for step advancement.
* #param step the new simulation time, in seconds
*/
void nextStep(double step);
}
Up to here, it would be the part related to the connection with SUMO. In the next edit (I need some rest right now..) I'll put the parts related with the Repositories and the Data retrieval
Thanks in advance!
I run into the problem, that my Game works fine in the Unity 3d IDE, but the moment i compile it, it stops at a certain moment. In fact, when my sqlite code is executed. But not just at the initialization!
So this code runs just fine:
/// <summary>
/// Basic initialization of SQLite This will be activated by the manager script
/// </summary>
public static void SQLiteInit ()
{
string SQL_DB_LOCATION = #"URI=file:C:\temp\inlusio_data\InlusioDB.sqlite";
mConnection = new SqliteConnection(SQL_DB_LOCATION);
mCommand = mConnection.CreateCommand();
mConnection.Open();
ExecuteQuerry("PRAGMA page_size = " + "4096" + ";");
ExecuteQuerry("PRAGMA synchronous = " + "1" + ";");
mConnection.Close();
}
The ExecudeQuerry code seems to work fine, as the above part of my code worked. Here the ExecudeQuerry code:
public static void ExecuteQuerry (string sqlcomand)
{
Debug.Log(sqlcomand);
mCommand.CommandText = sqlcomand;
mCommand.ExecuteNonQuery();
}
problematic part, at which the game gets stuck:
public static void InitialSavingsToDB (string chiffre, string EasyDelay, string HardDealy, string session)
{
/// Subject code
ExecuteQuerry("INSERT INTO 'Subject'('Subject_Number','EasyDifficultyLevel','HardDifficultyLevel') VALUES ('" + chiffre + "','" + EasyDelay + "','" + HardDealy + "');");
}
I tried it like this, too :
public static void InitialSavingsToDB (string chiffre, string EasyDelay, string HardDealy, string session)
{
/// Subject code
mConnection.Open();
mCommand.CommandText = "INSERT INTO 'Subject'('Subject_Number','EasyDifficultyLevel','HardDifficultyLevel') VALUES ('" + chiffre + "','" + EasyDelay + "','" + HardDealy + "');";
mCommand.ExecuteNonQuery();
mConnection.Close();
}
It is maybe worth mentioning, that i call the InitialSavingsToDB function from my ManagerScript, that is declared as
public class ManagerScript : MonoBehaviour {
...
...
...
private void Start ()
{
...
testofsql.SQLiteInit(); // initialisation of the Data Base
...
...
...
}
...
...
}
So my code works fine, the data is saved perfectly when i test the Game from the Unity 3d Editor. The moment I compile it, it just does not continue ingame. No errors, nothing. I can even run around. But the game is stuck.
I honestly don`t knew how to solve this. Have googled since 2 weeks to make sqlite working in Unity, tried to avoid errors, debuged everything, till i found the source of the problem and am clueless ... i hope somebody can help.
Thank you very much!
Cheers,
petr
What is your the target platform? Android, IOS, ...?
Be aware, that for different platforms unity3d uses different sqlite assemblies.
Try to check the following project
https://github.com/codecoding/SQLite4Unity3d and compare data in Plugins folder with what is used in your project.
I would suggest trying to use a library designed for Unity. Personally this is what I have been doing to handle multi-platform SQLite handling. I would highly suggest this library/wrapper
SQLite made easy for Unity3d http://codecoding.github.io/SQLite4Unity3d
I am currently in the process of improving upon that and making it even more easy to work with. However this is probably a good starting point!
GOOD LUCK!
I'm trying to use libgit2sharp to push to my repo on bitbucket. I'm trying to do this:
repo.Network.Push(repo.Branches[branchName], pushOptions);
Everything seems fine, no exceptions are thrown and I get no errors in the callback, but when I check on bitbucket none of my commits are there. Other methods seem to work fine (ie I can create a new branch on bitbucket and then use libgit2sharp to fetch and see that I now have that branch locally). Is there anything that I might be missing here?
edit:
Tried to just make a small sample program to see if I can get this working no go. I don't know if my code will help but here it is:
class Program
{
static void Main(string[] args)
{
PushOptions options = new PushOptions();
Credentials creds = new Credentials();
creds.Username = "username";
creds.Password = "password";
options.Credentials = creds;
options.OnPackBuilderProgress = Program.packBuilderProgressHandler;
options.OnPushTransferProgress = Program.pushTransferProgressHandler;
options.OnPushStatusError = Program.pushStatusErrorHandler;
Repository repo = new Repository("E:/Ohad/Work/libgitTest");
repo.Network.Push(repo.Branches["origin/master"], options);
Console.WriteLine("Press enter to close...");
Console.ReadLine();
}
public static bool packBuilderProgressHandler(PackBuilderStage stage, int current, int total)
{
Console.Out.WriteLine("packBuilder => " + current + " / " + total);
return true;
}
public static bool pushTransferProgressHandler(int current, int total, long bytes)
{
Console.Out.WriteLine("pushTransfer => " + current + " / " + total + " , " + bytes);
return true;
}
public static void pushStatusErrorHandler(PushStatusError error)
{
Console.Out.WriteLine("error => " + error.Message);
}
}
Just make a new repo on bitbucket and add the above code (changing the stuff thats hard coded) and it should be reproducible. I just made a random change, added and commited it and then used the program to try to push to bitbucket. The output that I am getting from the above is:
pushTransfer => 0 / 0 , 12
pushTransfer => 0 / 0 , 32
Press enter to close...
The 0/0 looks suspicious to me but I don't know what I'm doing wrong =/. Thanks for any help!!
edit 2:
I just added this:
repo.Branches.Update(repo.Head, delegate(BranchUpdater updater)
{
updater.Remote = "origin";
updater.UpstreamBranch= repo.Head.CanonicalName;
})
to before when I push and it fixed the issue. Not sure exactly why but I'll take it =).
I think that you're willing to push your local master branch rather than the remote tracking one.
repo.Network.Push(repo.Branches["master"], options);
Update:
*The branch 'master' ("refs/heads/master") that you are trying to push does not track an upstream branch. *
Provided you have no "origin" remote, the following should work.
Remote remote = localRepo.Network.Remotes.Add("origin", url);
repo.Branches.Update(repo.Head, -> (A)
b => b.Remote = remote.Name, -> (B)
b => b.UpstreamBranch = repo.Head.CanonicalName); -> (C)
The code above should be read as "The branch pointed at by the HEAD (A) on this local repository will be, by default, configured to track a branch bearing the same name (C) in the distant repository identified by this remote (B)."
I wanted to write to a NFC tag information about which application should start and add some text data to it. LaunchApp was working fine till I want to transmitt this additional message. When I added additional message LaunchApp stopped working. It is better explained in the code at the end of: private void LaunchMesssageTransmitted(ProximityDevice sender, long publishedMessageId)
How to make LaunchApp work and pass this string: GlobaIPTextBox.Text + ";" + PortTextBox.Text + ";" + LocalIPTextBox.Text to the tag.
public partial class MainPage : PhoneApplicationPage {
private long subscribedMessageID, publishedMessageId;
private ProximityDevice proximityDevice;
public MainPage() {
InitializeComponent();
createTagService();
}
private void createTagService() {
string appId = "{39989b95-a54a-4810-b4ee-35b33265a680}";//HomeSecurityClient Application ID
string args = "param=test";
string launchAppMessage = args + "\tWindowsPhone\t" + appId;
DataWriter dataWriter = new DataWriter() { UnicodeEncoding = UnicodeEncoding.Utf16LE };
dataWriter.WriteString(launchAppMessage);
proximityDevice = ProximityDevice.GetDefault();
proximityDevice.PublishBinaryMessage("LaunchApp:WriteTag", dataWriter.DetachBuffer(), LaunchMesssageTransmitted);
}
private void LaunchMesssageTransmitted(ProximityDevice sender, long publishedMessageId) {
sender.StopPublishingMessage(publishedMessageId);
/* Deployment.Current.Dispatcher.BeginInvoke(() => {
DataWriter dataWriter = new DataWriter() { UnicodeEncoding = UnicodeEncoding.Utf8 };
dataWriter.WriteString(GlobaIPTextBox.Text + ";" + PortTextBox.Text + ";" + LocalIPTextBox.Text);
sender.PublishBinaryMessage("Windows:WriteTag.NetworkData", dataWriter.DetachBuffer(), networkDataMessageTransmitted);
});*/ //IF I UNCOMMENT THIS TO TRANSMITT ADDITIONAL MESSAGE LAUNCHING APP STOPS WORKING
}
private void networkDataMessageTransmitted(ProximityDevice sender, long publishedMessageId) {
sender.StopPublishingMessage(publishedMessageId);
Deployment.Current.Dispatcher.BeginInvoke(() => {
MessageBox.Show("The data is written");
});
sender.StopPublishingMessage(publishedMessageId);
}
}
You can't write two seperate NDEF messages onto one tag. The last message will always overwrite any previous message. What you can do, however, is to write both records (the LaunchApp record and your customized record) to the tag within one NDEF message. For this to work, you would use the PublishBinaryMessage() method together with the message type "NDEF:WriteTag". That way you can pass the properly formatted(!) NDEF message to the tag. A way to create a properly formatted NDEF message would be to use the free NFC library from http://ndef.mopius.com/.