How to resolve this error with Unity's AsyncGPUReadback? - c#

I am trying to read back from the GPU a compute buffer inside of which there is an array of structs that I have defined and previously set.
var req = AsyncGPUReadback.Request(myBuffer);
if(req.hasError == false)
{
var readback = req.GetData<myStruct>();
print(readback);
}
When I put this in the code I get this error: InvalidOperationException: Cannot access the data as it is not available. The problem is that the data should be available because when I use the normal GetData method everything works just fine.
myBuffer.GetData(data);
Does anyone have an idea where I should be looking to get this error solved? Thanks!
------------------------Edit-------------------------------
I found a solution here https://github.com/keijiro/AsyncCaptureTest/blob/master/Assets/AsyncCapture.cs , but It's not very clear to me why it is working now and not before.
void Update()
{
AsyncGPUReadback.Request(myBuffer, OnCompleteReadBack);
}
void OnCompleteReadBack(AsyncGPUReadBackRequest request)
{
if(request.hasError == false)
{
var data = request.GetData<myStruct>();
}
}

Related

Invalid wire-type (String) when trying to grpc with protobuf-net grpc

I recently started receiving the following error on my protobuf-net grpc calls:
Grpc.Core.RpcException: 'Status(StatusCode=Internal, Detail="Error starting gRPC call: Invalid wire-type (String); this usually means you have over-written a file without truncating or setting the length; see https://stackoverflow.com/q/2152978/23354")'
I already went to that link, but didn't really find anything that really relates to what I am working on.
So, this error started popping up a while ago, when I did write some custom reflection code to do protobuf-net inheritance modeling dynamically via RuntimeTypeModel.
This is my code for this:
private void InitializeBindingsForGrpcService([NotNull] Type grpcService)
{
foreach (var method in grpcService.GetMethods())
{
var involvedTypes = method.GetParameters().Select(x => x.ParameterType).ToList();
involvedTypes.Add(method.ReturnType);
var cleanTypes = involvedTypes.Where(x => !x.IsGenericType).ToList();
var taskCleanTypes = involvedTypes.Except(cleanTypes).Select(x => x.CheckAndGetTaskWrappedType());
cleanTypes.AddRange(taskCleanTypes);
var genericTypes = cleanTypes.Where(x =>x.IsGenericType);
foreach (var genericType in genericTypes)
{
RegisterBaseChain(genericType);
}
var nonGenerics = cleanTypes.Where(x => !x.IsGenericType);
foreach (var type in nonGenerics)
{
if (!type.Namespace.StartsWith("System"))
{
RuntimeTypeModel.Default.Add(type, true);
}
}
}
}
private void RegisterBaseChain([NotNull] Type type)
{
var baseType = type.BaseType;
if (baseType == null || baseType == typeof(object))
{
return;
}
var baseMetaData = RuntimeTypeModel.Default.Add(baseType);
baseMetaData.AddSubType(m_protoIndex, type);
m_protoIndex++;
RegisterBaseChain(baseType);
}
So, I am now kind of curious where I might be going wrong with this. I'd love to provide more details for this case, but I just don't really know what to put in.
I did check whether all the relevant objects for the given call are properly registered, and that is the case.
Any pointers to what I should do here?

C# Hjson returns null after deserialization

I have a hjson file like this that I want to deserialize and work with:
{
"TestConfig": {
"SecondConfig": {
"ConnectionString": "Integrated Security = true; Data Source = dataPseudo; Initial Catalog = catalogPseudo; Connect Timeout = 180",
"SpecificationPseudo": "pseudo",
"NumberOfHintsPseudo": 300
},
"ThirdConfig": "pseudo"
}... // more hjson coming here.
I load it with the HjsonValue.Load method like this:
private static Foo convertJson()
{
var loadedValue = HjsonValue.Load("hjsonFile.hjson").ToString();
return new JsonSerializer<Foo>().DeserializeFromString(loadedValue);
// another failed method: return JsonConvert.DeserializeObject<Foo>(loadedValue);
// A third failed method: return JsonConvert.DeserializeObject<Dictionary<string, Foo>>(loadedValue);
}
I think my problem is in the 2 c#-coded lines, but can't figure what. Am I deserializing wrong or what seems to be the problem? I suspect that it's because it is a nested json, but can't find a way to deserialize it. Trying to use dictionary as it is a answer in a other stack-question, but it didn't work for me.
Note: The first and second tried return method don't return any errors, but they just return a nullreferenceexception since "SecondConfig" and "ThirdConfig" both are null..
Update (with help from er-sho): removed the "root"-element from the hjson (TestConfig), which solved the problem.
Removing "TestConfig" from the hjson fixed it, since it's root and the class I am working with.

How to download data from Firebase?

I'm attempting to retrieve some data from a Firebase database. I've been able to do it fine in the past, but there's something wrong with my GetValueAsync() code below. When debugging it gets stuck at the "await reference.Database" line, but I'm not sure what I'm doing wrong. When running without debugging, none of the information is ever retrieved.
I'm uncertain if the problem is with the path, or the await/async function. Debugging shows that loggedUserId is storing the value before referencing it in the next line, but the rest of the function never completes or faults. The application compiles but I'm never able to capture any info from the snapshot.
The format of my database is "users" -> 78cVqzA8qNTNigsao3VvdnM0Qol2 (Which is correct) -> (several data pairs such as level : 1, lives : 3, etc)
public static async void GetUserData()
{
FirebaseApp app = FirebaseApp.DefaultInstance;
app.SetEditorDatabaseUrl("https://narwhaltrivia.firebaseio.com/");
if (app.Options.DatabaseUrl != null) app.SetEditorDatabaseUrl(app.Options.DatabaseUrl);
DatabaseReference reference = Firebase.Database.FirebaseDatabase.DefaultInstance.RootReference;
loggedUserId = FirebaseAuth.DefaultInstance.CurrentUser.UserId;
await reference.Database.GetReference("users").Child(loggedUserId).GetValueAsync().ContinueWith(task =>
{
if (task.IsFaulted)
{
Debug.LogError("Error retrieving user data");
return;
}
if (task.IsCompleted)
{
DataSnapshot userSnapshot = task.Result;
loggedEmail = userSnapshot.Child("email").GetRawJsonValue();
loggedCurrentScore = userSnapshot.Child("currentScore").GetRawJsonValue();
loggedLevel = userSnapshot.Child("level").GetRawJsonValue();
loggedLives = userSnapshot.Child("lives").GetRawJsonValue();
loggedRound = userSnapshot.Child("round").GetRawJsonValue();
loggedTotalScore = userSnapshot.Child("totalScore").GetRawJsonValue();
return;
}
});
}

Random invalid procedure call or argument in vbscript using a COM

When I try to access my classic ASP application I get a random error of "Invalid Procedure Call or Argument". The line that causes this error calls a method from a C# component.
Here is the line that breaks in vbscript :
tmpArray2 = session.get(arrName) 'where arrName is a string
Also it cracks at this kind of line too :
if UBound(session.get("RTT_ID")) <> "-1" then
And here is the component code for the get method :
public object get(string key)
{
if (key == null || IsExpired)
{
return null;
}
if (!SessionData.ContainsKey(key))
{
var sessionData = GetDbSessionData(key);
var cachedValue = default(object);
if (sessionData == null || sessionData.Value == null || sessionData.ValueType == null)
{
LogManager.Instance.LogFormat(this, LogLevel.Warning, "Session data not found. SessionId: '{0}'; Key: '{1}'.", this.SessionInfo.Id, key);
cachedValue = null;
}
else
{
cachedValue = SessionDataSerializer.Instance.DeserializeSessionData(sessionData.Value, sessionData.ValueType);
}
var cachedSessionData = new CachedSessionData();
cachedSessionData.CachedValue = cachedValue;
cachedSessionData.DbEntity = sessionData;
SessionData.Add(key, cachedSessionData);
}
RefreshExpirationDate();
return SessionData[key].CachedValue;
}
Also, what I noticed and I do not know if it is relevant or not, this code cracks a lot on an environment that has 2 servers and makes a balancing between them when the first one is too busy. If I try it on a single server, I managed to broke it only once.
Any ideas?
Thank you for your answers. The problem was that because we wanted to increase our performance we had to serialize every object that was send to the component and deserialize it when we returned it to the vbscript. The issue was that we had one array that was containing other arrays and when we deserialize the array we could not return also the child arrays and that was causing the problem. We used for deserialization the MessageBox library.
Another thing to mention is that on our environment we had 2 servers and we are doing some balancing between them. When the application runs only on one server, the deserialization was ok and we had no problems, but when we switched to the other server we encountered this problem.
Maybe this answer will help others understand what could happen if you receive this type of error.

Type casting error while using couchbase

I have a view named "TotalPosts" in my couchbase data bucket. The design document name is "Statistics".
This is my code. I am establishing the connection over here..
protected void Page_Load(object sender, EventArgs e)
{
try
{
var client= new CouchbaseClient();
Tasks objTasks = new Tasks();
foreach (Newtonsoft.Json.Linq.JToken jt in objTasks.GetAllStatistics())
{
if (jt["key"].ToString() == "Total")
{
dt.Rows[0]["Value"] = jt["value"].ToString();
}
if (jt["key"].ToString() == "Open")
{
dt.Rows[1]["Value"] = jt["value"].ToString();
}
if (jt["key"].ToString() == "Wah")
{
dt.Rows[2]["Value"] = jt["value"].ToString();
}
}
This is my GetAllStatistics function definition code:
public IEnumerable<Newtonsoft.Json.Linq.JToken> GetAllStatistics()
{
var results = oCouchbase.GetView("Statistics", "TotalPosts");
return results;// I am getting the following error in this line
}
Cannot implicitly convert type 'Couchbase.IView' to 'System.Collections.Generic.IEnumerable'. An explicit conversion exists (are you missing a cast?)
This is my map code:
function(doc) {
emit("Total", 1);
emit("TotalParticipants", doc.participants.length);
if(doc.status == "1"){
emit("Open", 1);
} else if(doc.status == "2") {
emit("Wah", parseInt(doc.wah_points));
}
}
This is my reduce code:
function (key, values, rereduce) {
return sum(values);
}
I could not find an appropriate type casting. Kindly help me in this issue
I can't claim any knowledge of Couchbase, but the error message indicates that you can perform an explicit cast. Have you tried just doing a cast for your return?
return (Newtonsoft.Json.Linq.JToken)results;
The non-generic version of GetView returns an enumerable list of IViewRow. So instead, I would recommend changing your GetAllStatistics method to something like this:
public IEnumerable<Newtonsoft.Json.Linq.JToken> GetAllStatistics()
{
var results = oCouchbase.GetView("Statistics", "TotalPosts");
foreach(var row in results)
{
yield return oCouchbase.Get<Newtonsoft.Json.Linq.JToken>(row.ItemId);
}
}
Then your foreach loop should work as is. However, a question I have is what your documents look like. Are you serializing JToken instances as the value in your Store operations? If you are, then they will not be available in your views as only valid JSON strings will be usable within a view. If you have any questions about anything I just mentioned, please feel free to edit your question to include your Store operations and the map/reduce view code.

Categories