"Cannot include control characters in a HTTP header" using Parse - c#

I've implemented a login manager in my game using Parse, and everything worked well.
So I've added an online leaderboard, but now each time Unity executes a method like this:
void UpdateOnlineScore(string id, int newScore)
{
var query = ParseObject.GetQuery("tableName").WhereEqualTo("userid", id);
query.FirstAsync().ContinueWith(t => {
if (t.IsFaulted)
{
Debug.LogWarning("ID not found");
// user stats not found create from scratch
}
else
{
Debug.Log("Record found");
ParseObject obj = t.Result;
int savedScore = (int) obj.Get<int>("score");
// check record
}
});
}
it stops at query.FirstAsync().ContinueWith(...) throwing this exception:
ArgumentException: Cannot include control characters in a HTTP header, either as key or value.
UnityEngine.WWW.CheckSecurityOnHeaders (System.String[] headers) (at C:/BuildAgent/work/d63dfc6385190b60/Runtime/Export/WWW.cs:98)
UnityEngine.WWW..ctor (System.String url, System.Byte[] postData, System.Collections.Generic.Dictionary`2 headers) (at C:/BuildAgent/work/d63dfc6385190b60/artifacts/EditorGenerated/Utils.cs:88)
Parse.PlatformHooks.GenerateWWWInstance (System.String uri, System.Byte[] bytes, System.Collections.Hashtable headerTable)
Parse.PlatformHooks+<>c__DisplayClass30+<>c__DisplayClass36.b__29 ()
Parse.PlatformHooks+d__3c.MoveNext ()
UnityEngine.Debug:LogException(Exception)
Parse.d__3c:MoveNext()
I have no idea what I'm doing wrong.
What's strange is that I get this error only debugging on Web Player platform.
On Windows Standalone it doesn't show up.
Am I missing something?
I'm usign Unity 4.6.0f3.

Related

conn_7 Error control message: ClientId[6528662]:ErrorId[8]: Error on incoming message

I am currently creating a firebase realtime database transaction in unity c# and keep getting this error:
[Error log]
[conn_7] Error control message: ClientId[6528662]:ErrorId[8]: Error on incoming message
UnityEngine.Debug:LogError (object)
Firebase.Platform.FirebaseLogger:LogMessage (Firebase.Platform.PlatformLogLevel,string) (at /Users/runner/work/firebase-unity-sdk/firebase-unity-sdk/app/platform/Unity/FirebaseLogger.cs:95)
Firebase.LogUtil:LogMessage (Firebase.LogLevel,string) (at /Users/runner/work/firebase-unity-sdk/firebase-unity-sdk/app/src/LogUtil.cs:69)
Firebase.LogUtil:LogMessageFromCallback (Firebase.LogLevel,string) (at /Users/runner/work/firebase-unity-sdk/firebase-unity-sdk/app/src/LogUtil.cs:77)
Firebase.AppUtil:PollCallbacks () (at /Users/runner/work/firebase-unity-sdk/firebase-unity-sdk/android_unity/armeabi-v7a/app/swig/Firebase.App_fixed.cs:4604)
Firebase.Platform.FirebaseAppUtils:PollCallbacks () (at /Users/runner/work/firebase-unity-sdk/firebase-unity-sdk/app/platform/FirebaseAppUtils.cs:33)
Firebase.Platform.FirebaseHandler:Update () (at /Users/runner/work/firebase-unity-sdk/firebase-unity-sdk/app/platform/Unity/FirebaseHandler.cs:208)
Firebase.Platform.FirebaseMonoBehaviour:Update () (at /Users/runner/work/firebase-unity-sdk/firebase-unity-sdk/app/platform/Unity/FirebaseMonoBehaviour.cs:45)
Source Code:
public void SendjointPoints()
{
if (!TransactionComplete)
{
Debug.Log("not finished Transaction. skip a frame.");
return;
}
TransactionComplete = false;
DatabaseReference reference = FirebaseDatabase.DefaultInstance.GetReference("jointPoints");
Debug.Log("Running Transaction...");
reference.RunTransaction(SendTransaction)
.ContinueWithOnMainThread(task => {
if (task.Exception != null)
{
TransactionComplete = true;
Debug.Log(task.Exception.ToString());
}
else if (task.IsCompleted)
{
TransactionComplete = true;
Debug.Log("Transaction complete.");
}
});
}
This error freezes Unity. any more transaction is not working until Unity Stop.
My code wants 1~2 transaction per a second.
Any idea why this is happening?
My code is trying to navigate through the various levels of mutabledata I got from my database reference.
Unity version 2021.3.5f1
Building for Android and Window
IDE: Microsoft Visual Studio
firebase_unity_sdk_9.4.0 (dotnet4 : FirebaseDatabase.unitypackage)

Serialization error with firebase on Unity

I'm trying to run a transaction with realtime database to change an object, with the following code :
void tryBeHost()
{
string path = "weeks/" + week + "/games/" + gameId + "/gameInfo";
_dbRef.Child(path).RunTransaction(mutableData =>
{
GameInfo gameInfo = mutableData.Value as GameInfo;
if (gameInfo == null)
{
gameInfo = new GameInfo();
}
else if (gameInfo.host != null && gameInfo.host != myId)
{
return TransactionResult.Success(mutableData);
}
gameInfo.host = myId;
mutableData.Value = gameInfo;
return TransactionResult.Success(mutableData);
});
}
so I'm getting this weird error :
Exception in transaction delegate, aborting transaction
Firebase.Database.DatabaseException: Failed to parse object Serializables.GameInfo ---> System.ArgumentException: Invalid type Serializables.GameInfo for conversion to Variant
at Firebase.Variant.FromObject (System.Object o) [0x001df] in Z:\tmp\tmp.EaS8iXpRBh\firebase\app\client\unity\proxy\Variant.cs:117
at Firebase.Database.Internal.Utilities.MakeVariant (System.Object value) [0x00000] in Z:\tmp\tmp.sZ8vrpcx53\firebase\database\client\unity\proxy\Utilities.cs:25
--- End of inner exception stack trace ---
at Firebase.Database.Internal.Utilities.MakeVariant (System.Object value) [0x0000d] in Z:\tmp\tmp.sZ8vrpcx53\firebase\database\client\unity\proxy\Utilities.cs:27
at Firebase.Database.MutableData.set_Value (System.Object value) [0x00000] in Z:\tmp\tmp.sZ8vrpcx53\firebase\database\client\unity\proxy\MutableData.cs:136
at InternetShit.b__10_0 (Firebase.Database.MutableData mutableData) [0x00045] in /Users/sandukhan/Unity/projects/Ronda/Assets/Scripts/InternetShit.cs:73
at Firebase.Database.Internal.InternalTransactionHandler.DoTransaction (System.Int32 callbackId, System.IntPtr mutableData) [0x00022] in
Z:\tmp\tmp.sZ8vrpcx53\firebase\database\client\unity\proxy\InternalTransactionHandler.cs:49
UnityEngine.Debug:LogWarning(Object)
Firebase.Platform.FirebaseLogger:LogMessage(PlatformLogLevel, String) (at Z:/tmp/tmp.BbQyA8B710/firebase/app/client/unity/src/Unity/FirebaseLogger.cs:92)
Firebase.LogUtil:LogMessage(LogLevel, String) (at Z:/tmp/tmp.EaS8iXpRBh/firebase/app/client/unity/proxy/LogUtil.cs:68)
Firebase.Database.Internal.InternalTransactionHandler:DoTransaction(Int32, IntPtr) (at Z:/tmp/tmp.sZ8vrpcx53/firebase/database/client/unity/proxy/InternalTransactionHandler.cs:51)
Firebase.AppUtilPINVOKE:PollCallbacks()
Firebase.AppUtil:PollCallbacks() (at Z:/tmp/tmp.EaS8iXpRBh/firebase/app/client/unity/proxy/AppUtil.cs:32)
Firebase.Platform.FirebaseAppUtils:PollCallbacks() (at Z:/tmp/tmp.EaS8iXpRBh/firebase/app/client/unity/proxy/FirebaseAppUtils.cs:33)
Firebase.Platform.FirebaseHandler:Update() (at Z:/tmp/tmp.BbQyA8B710/firebase/app/client/unity/src/Unity/FirebaseHandler.cs:205)
Firebase.Platform.FirebaseMonoBehaviour:Update() (at Z:/tmp/tmp.BbQyA8B710/firebase/app/client/unity/src/Unity/FirebaseMonoBehaviour.cs:45)
my GameInfo Class is the following :
using System;
using Serializables;
namespace Serializables
{
[Serializable]
public class GameInfo
{
public string gameId;
public string host;
public string[] playersIds;
public string[] playersPics;
public string[] playersNames;
}
}
if anyone has an idea to solve this I will be grateful
I think you figured out the basics: You can only submit bool, string, long, double, IDictionary, and List<Object> to Value.
There's some interesting notes that I'd like to layer on top of this though! I like to use Unity's JsonUtility in conjunction with SetRawJsonValueAsync and GetRawJsonValue from GetValueAsync. Your code will look a bit like this:
async void SendGameInfo(string path, GameInfo info) {
try {
await _database
.GetReference(path)
.SetRawJsonValueAsync(JsonUtility.ToJson(info));
Debug.Log($"Successfully wrote {info}");
} catch (AggregateException e) {
Debug.LogWarning($"Failed with {e}");
}
}
async Task<GameInfo> ReadGameInfo(string path) {
try {
var dataSnapshot = await _database
.GetReference(path)
.GetValueAsync();
return JsonUtility.FromJson<GameInfo>(info);
} catch (AggregateException e) {
Debug.LogWarning($"Failed with {e}");
return null;
}
}
Also, if you can, having spent time digging through the library I like to consider IDictionary<string, object> the "basic primitive" of Realtime Database. This will be used as an intermediary format when you set RawJson if you step through the disassembly. Also, since Transactions don't provide access to raw json, this will give you a more uniform interface to RTDB (unless your data looks like an array, then your primitive is List<object> - "looks like" meaning that your keys are numbers and the range of numbers RTDB is aware of is about half full).
Of course, the team actively monitors the quickstart github page and you can use the new "feature request" template to request a change to any of this if it will help 😃.
I think RTFM always works, I found out that there are specific types that are accepted for mutableData.Value : bool, string, long, double, IDictionary and List{Object} where Object is one of previously listed types. So I got this error because my class GameInfo is not accepted and I have to convert my object to an IDictionary.
source : https://firebase.google.com/docs/reference/unity/class/firebase/database/mutable-data#class_firebase_1_1_database_1_1_mutable_data_1a4833f23246b3079078332d57c5649254

"Process is terminating due to StackOverflowException", reason for it in the following code

A class which in it of itself contains its own object instantiated,when creating an object of that class in main method in c#, it gives stackoverflowExeption. Why?? I want the reason for it, not the solution.Thanks
namespace project_1
{
class check
{
check checkobject = new check();// Line-1
/*I have not access Line-1 in main method.
But due to Line-1 or Line-2, output says "Process is terminating due to StackOverflowException". Why??
I do not need the solution, I want to know the reason for it.
Removing " new check() " from Line-1, then it works fine.
*/
public void Display() {
Console.WriteLine("It worked");
}
}
class DemoProgram
{
static void Main(string[] args)
{
check ob1 = new check();// Line-2
ob1.Display();
}
}
}
This is because when you create a new check object from your main method, it triggers the initialization of the instance variable, checkobject, which again creates an object of class check. This is an infinite procedure, hence the memory alloted to your program is exhausted.
You call your class constructor every time the class is initialised. The line marked as line 1 is the one you shouldn't have. It means you call your constructor recursively.
If you try to debug your program, you see the similar output to the following. If you know almost nothing why it happens, at least you can guess something is wrong subject to the constructor.
Compilation succeeded - 1 warning(s)
jdoodle.cs(5,11): warning CS0414: The private field `check.checkobject' is assigned
but its value is never used
Stack overflow: IP: 0x5647646e1705, fault addr: 0x7fffc422eff8
Stacktrace:
at <unknown> <0xffffffff>
at (wrapper alloc) object.AllocSmall (intptr,intptr) <0x00103>
<...>
at check..ctor () [0x00000] in <db1fd2bd96e041fab014c4ec28898e03>:0
at check..ctor () [0x00000] in <db1fd2bd96e041fab014c4ec28898e03>:0
at check..ctor () [0x00000] in <db1fd2bd96e041fab014c4ec28898e03>:0
at check..ctor () [0x00000] in <db1fd2bd96e041fab014c4ec28898e03>:0
at check..ctor () [0x00000] in <db1fd2bd96e041fab014c4ec28898e03>:0
at check..ctor () [0x00000] in <db1fd2bd96e041fab014c4ec28898e03>:0
at check..ctor () [0x00000] in <db1fd2bd96e041fab014c4ec28898e03>:0
at check..ctor () [0x00000] in <db1fd2bd96e041fab014c4ec28898e03>:0
........
........
........
........
........
at check..ctor () [0x00000] in <db1fd2bd96e041fab014c4ec28898e03>:0
output Limit reached.
Your problem is an endless recursion caused by a field initializer.
Example
public class Test
{
Type FieldName = SomeValue;
A field initializer is executed before constructor bodies. The important take-home point here is, they are always executed.
Which means you can't do this, it runs when the class initialises.
check checkobject = new check();
Every time you new up (initialise) this class, it's going to run the above code, which by its very nature new's up another instances of itself due to the *field initializers, which in-turns runs the above again so-on-and-so-forth until you run out of stack.
If you really want a self-referencing property like this, and you want it initialised (in an automatic sense), use a lazy loading technique, eg.
private Check _checkObject;
public Check CheckObject => _checkObject?? (_checkObject = new Check());

Having trouble in initializing Matlab MCR when using a DLL, generated by matlab, in Unity3D

I am developing a Kinect based gesture recognizing application on Unity3D. I have to utilize an algorithm that has been written in Matlab. Thus I decided to generate a .Net DLL with Matlab deploytool and I successfully did so. Then I tested the DLL in a standalone .Net application project(in Visual Studio 2017) where it worked perfectly. BUT, when I turned to Unity3D, that DLL never worked...... What I got is shown as below:
enter image description here
System.TypeInitializationException: An exception was thrown by the type initializer for Untitled1.ADD ---> System.NotImplementedException: The requested feature is not implemented.
at System.Security.Principal.WindowsIdentity.GetCurrent (Boolean ifImpersonating) [0x00000] in /Users/builduser/buildslave/mono/build/mcs/class/corlib/System.Security.Principal/WindowsIdentity.cs:166
at MathWorks.MATLAB.NET.Utility.MWMCR.EvaluateFunction (System.String functionName, Int32 numArgsOut, Int32 numArgsIn, MathWorks.MATLAB.NET.Arrays.MWArray[] argsIn) [0x00000] in <filename unknown>:0
at MathWorks.MATLAB.NET.Utility.MWMCR.EvaluateFunction (Int32 numArgsOut, System.String functionName, MathWorks.MATLAB.NET.Arrays.MWArray[] argsIn) [0x00000] in <filename unknown>:0
at MathWorks.MATLAB.NET.Utility.MWMCR.setBuilderUserData () [0x00000] in <filename unknown>:0
at MathWorks.MATLAB.NET.Utility.MWMCR..ctor (System.String componentId, System.String componentPath, System.IO.Stream embeddedCtfStream, Boolean isLibrary) [0x00000] in <filename unknown>:0
at Untitled1.ADD..cctor () [0x00000] in <filename unknown>:0
--- End of inner exception stack trace ---
at dlltest.Start () [0x00000] in E:\Unity\mPrj\Assets\dlltest.cs:40
UnityEngine.Debug:Log(Object)
dlltest:Start() (at Assets/dlltest.cs:46)
From the Log, it seemed that the initializing of MCR was failed, but I just can not find why after viewing the C# source code generated by Matlab(who ever has done this job before must know what I am talking about).
Is there someone who is experienced in this kind of work and can explain to me this happened and how to solve? Thank you so much!
The namespace of the DLL is Untitled1(got no time to give it a name...) and the name of the class in the DLL is ADD.
Followings are the related code in this process(test samples):
Matlab source code add.m:
function y = add(n,m)
y = n+m;
The C# Code, which is generated by Matlab during building the M file into DLL, is too long to paste here, so I just show the code that defines the constructor, at which the error in Unity3D happen according to the Log:
static ADD()
{
if (MWMCR.MCRAppInitialized)
{
Assembly assembly= Assembly.GetExecutingAssembly();
string ctfFilePath= assembly.Location;
int lastDelimiter= ctfFilePath.LastIndexOf(#"\");
ctfFilePath= ctfFilePath.Remove(lastDelimiter, (ctfFilePath.Length - lastDelimiter));
string ctfFileName = "Untitled1.ctf";
Stream embeddedCtfStream = null;
String[] resourceStrings = assembly.GetManifestResourceNames();
foreach (String name in resourceStrings)
{
if (name.Contains(ctfFileName))
{
embeddedCtfStream = assembly.GetManifestResourceStream(name);
break;
}
}
mcr= new MWMCR("",
ctfFilePath, embeddedCtfStream, true);
}
else
{
throw new ApplicationException("MWArray assembly could not be initialized");
}
}
The code that successfully used the DLL in a standalone .Net Application:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MathWorks.MATLAB.NET.Utility;
using MathWorks.MATLAB.NET.Arrays;
using Untitled1;
namespace AddDllTest
{
class Program
{
static void Main(string[] args)
{
ADD myAdd = new ADD();
Console.WriteLine(myAdd.add((MWArray)1, (MWArray)1));
}
}
}
And the code, which is a Unity3D script, that failed to use the DLL in Unity3D(some comments have been deleted):
using UnityEngine;
using System.Collections;
using System.Runtime.InteropServices;
using RootSystem = System;
using System;
using System.Reflection;
using System.IO;
using Untitled1;
using MathWorks.MATLAB.NET.Arrays;
using MathWorks.MATLAB.NET.Utility;
public class dlltest : MonoBehaviour {
MWArray test1 = 1;
MWArray ref0 = 2;
MWArray result;
ADD myADD;
//Use this for initializations
void Start () {
try
{
myADD = new ADD();
}
catch (Exception e)
{
Debug.Log("EXCEPTION");
Debug.Log(e.ToString());
}
}
// Update is called once per frame
void Update () {
result = myADD.add(test1,ref0);
Debug.Log(result);
}
}
Looks like the static ctor of MWMCR class is calling into an unsupported method in Mono classlib:
(https://github.com/Unity-Technologies/mono/blob/uniy-trunk/mcs/class/corlib/System.Security.Principal/WindowsIdentity.cs#L166)
The reason your test worked as a standalone .Net is that you probably is running it on CLR.
When you try to run your Unity project it uses Mono (in most cases) and then you get this error.
It should work if you build your Unity project as a "Windows Store App" (because in this case your "game" will run using CLR)

C# MongoDB bulk Upsert - A bulk write operation resulted in one or more errors

WHY IT HAPPENS
Because in certain cases upsert can't automatically generate an _id
for the object you are manipulating.
SOLUTION A
Use [BsonIgnoreIfDefault] in the _id field of your model.
SOLUTION B
You can manually generate an _id before to upsert using
ObjectId.GenerateNewId()
MORE INFO
Here and here.
ORIGINAL POST
Following the official documentation, I wrote this method. When i run it I receive this cryptic error message: "A bulk write operation resulted in one or more errors". Any idea what could be causing it? Everything looks fine. I already have bulk insert and remove methods working correctly.
public bool BulkUpsertReplaceOne (List<AppModel> records,
string collectionName)
{
try
{
var bulk = _database.
GetCollection(collectionName).
InitializeUnorderedBulkOperation();
foreach(AppModel am in records)
{
IMongoQuery mongoQuery = Query.EQ ("Url", am.Url);
bulk.Find (mongoQuery).Upsert().ReplaceOne(am);
}
bulk.Execute();
return true;
}
catch(Exception e)
{
logger.Info (e.Message);
}
}
EDIT COMPLETE ERROR
at MongoDB.Driver.Operations.BulkWriteBatchResultCombiner.CreateResultOrThrowIfHasErrors (IEnumerable`1 remainingRequests) in <filename unknown>:line 0
at MongoDB.Driver.Operations.BulkMixedWriteOperation.Execute (MongoDB.Driver.Internal.MongoConnection connection) in <filename unknown>:line 0
at MongoDB.Driver.MongoCollection.BulkWrite (MongoDB.Driver.BulkWriteArgs args) in <filename unknown>:line 0
at MongoDB.Driver.BulkWriteOperation.ExecuteHelper (MongoDB.Driver.WriteConcern writeConcern) in <filename unknown>:line 0
at MongoDB.Driver.BulkWriteOperation.Execute () in <filename unknown>:line 0
at SharedLibrary.Wrappers.MongoDB.MongoDBWrapper.BulkUpsertReplaceOne (System.Collections.Generic.List`1 records, System.String collectionName) in <filename unknown>:line 0"
EDIT2
I don't know if this is related, but if I check the database after the error, only ONE item of the bulk upsert have been inserted, and hasObjectId("000000000000000000000000").
Version: MongoDB 2.6.1, MongoC# driver 2.0.1
Looks like you have an issue with your AppModel's id record values. Looks like they are missing or all '000000000000000000000000'

Categories

Resources