Struggling with Windows Azure Mobile Services and data serialization issues

I'm facing a challenge trying to integrate my model type with Windows Azure Mobile Services. It's functioning well, except for when I introduce the following member:

    [DataMemberJsonConverter(ConverterType = typeof(DictionaryJsonConverter))]
    public IDictionary<Tuple<int, int>, BoardSpaceState> pieceLocations { get; set; }


    /**
     * There might be a more efficient way to handle this serialization,
     * but I've already invested significant time in making it work.
     */
    public class DictionaryJsonConverter : IDataMemberJsonConverter 
    {
        public static Tuple<int, int> tupleOfString(string str)
        {
            var match = Regex.Match(str, @"\((\d+), (\d+)\)");
            // need to grab indexes 1 and 2 because 0 is the entire match
            return Tuple.Create(int.Parse(match.Groups[1].Value), int.Parse(match.Groups[2].Value));
        }

        public object ConvertFromJson(IJsonValue val)
        {
            var dict = JsonConvert.DeserializeObject<Dictionary<string, string>>(val.GetString());
            var deserialized = new Dictionary<Tuple<int, int>, BoardSpaceState>();
            foreach (var pieceLoc in dict)
            {
                deserialized[tupleOfString(pieceLoc.Key)] = (BoardSpaceState) Enum.Parse(typeof(BoardSpaceState), pieceLoc.Value);
            }
            return deserialized;
        }

        public IJsonValue ConvertToJson(object instance)
        {
            var dict = (IDictionary<Tuple<int, int>, BoardSpaceState>)instance;
            IDictionary<Tuple<int, int>, string> toSerialize = new Dictionary<Tuple<int, int>, string>();
            foreach (var pieceLoc in dict)
            {
                /** There may be an easier way to convert the enums to strings
                 * http://stackoverflow.com/questions/2441290/json-serialization-of-c-sharp-enum-as-string
                 * By default, Json.NET just converts the enum to its numeric value, which is not helpful.
                 * There could also be a way to do these dictionary conversions in a more functional way.
                 */
                toSerialize[pieceLoc.Key] = pieceLoc.Value.ToString();
            }

            var serialized = JsonConvert.SerializeObject(toSerialize);
            return JsonValue.CreateStringValue(serialized);
        }
    }

BoardSpaceState.cs:

public enum BoardSpaceState
    {
        FriendlyPieceShort,
        FriendlyPieceTall,
        OpponentPieceShort,
        OpponentPieceTall,
        None
    }

The data persists to Azure without any issues, and I can view it in the management portal. However, when attempting to retrieve the data using toListAsync(), I encounter the following exception:

{"Object must implement IConvertible."} System.Exception {System.InvalidCastException}

at System.Convert.ChangeType(Object value, Type conversionType, IFormatProvider provider)\r\n
at Microsoft.WindowsAzure.MobileServices.TypeExtensions.ChangeType(Object value, Type desiredType)\r\n   
at Microsoft.WindowsAzure.MobileServices.MobileServiceTableSerializer.Deserialize(IJsonValue value, Object instance, Boolean ignoreCustomSerialization)\r\n   
at Microsoft.WindowsAzure.MobileServices.MobileServiceTableSerializer.Deserialize(IJsonValue value, Object instance)\r\n   
at Microsoft.WindowsAzure.MobileServices.MobileServiceTableSerializer.Deserialize[T](IJsonValue value)\r\n   
at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()\r\n   
at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)\r\n   
at Microsoft.WindowsAzure.MobileServices.TotalCountList`1..ctor(IEnumerable`1 sequence)\r\n   
at Microsoft.WindowsAzure.MobileServices.MobileServiceTable`1.<ToListAsync>d__3f.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()\r\n   
at chivalry.DataManager.<withServerData>d__2.MoveNext() in c:\\Users\\Rosarch\\Documents\\Visual Studio 2012\\Projects\\chivalry\\chivalry\\DataManager.cs:line 35" string

The HRESULT is -2147467262.

Any ideas on what might be causing this issue?

Update:

The error occurs at the line:

private IMobileServiceTable<Game> gameTable = App.MobileService.GetTable<Game>();
// ...
var games = await gameTable.ToListAsync();  // error here

Interestingly, I face the same error even if I simply return

new Dictionary<Tuple<int, int>, BoardSpaceState>()
from
DictionaryJsonConverter.ConvertFromJson
.

Answer №1

It appears that there is an issue with the Azure Mobile Services client SDK - I will report this to the product team. Thank you for bringing it to our attention.

In the meantime, there is a workaround that should resolve the issue: instead of defining the pieceLocations variable with the interface type, declare it with the dictionary type. Here is the code snippet that has been tested and confirmed to work:

public sealed partial class MainPage : Page
{
    // Code goes here...
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Preserve data across all pages using sessions

On my website, I have a pagination system where each page displays 10 data entries. Whenever a user clicks on the pagination buttons, it triggers a request to the database to fetch the corresponding records. Each data entry also includes a button that can ...

How to change a value within an array stored in local storage using Vanilla JavaScript?

I recently started learning vanilla JavaScript and followed a tutorial on creating a shopping cart. While the tutorial was helpful, it was cut short and I had to figure out how to update a value in a local storage array by clicking a button on my own. Can ...

Exploring objects as strings to retrieve data with Javascript

In a scenario where I receive an object of varying length that I do not control, I am required to extract specific data from it. The response I receive is in the form of a formatted string: { "questionId": 18196101, "externalQuestionId": "bcc38f7 ...

"Updating the date and time on an Android device

I am looking to modify the datetime type from dd.MM.yyyy after parsing a JSON file. Although I have written some code to change the datetime format, the time remains constant. For instance, if the date is 2.3.2014, this is my current code: Calendar cal = ...

jQuery AJAX event handlers failing to trigger

It's driving me crazy! I've been using jquery's ajax for years, and I can't seem to figure out why the success, error, and complete events won't fire. The syntax is correct, the service it's calling works fine, but nothing hap ...

Error message in Angular: Unable to locate a differ that supports the object '[object Object]' of type 'object.' NgFor is only able to bind to iterables like Arrays

When making an API call in my Angular project, I receive the following JSON response: { "data": { "success": true, "historical": true, "date": "2022-01-01", "base": "MXN&quo ...

Attempting to extract individual strings from a lengthy compilation of headlines

Looking for a solution to organize the output from a news api in Python, which currently appears as a long list of headlines and websites? Here is a sample output: {'status': 'ok', 'totalResults': 38, 'articles': [{ ...

Transfer the folder from the DBFS location to the user's workspace directory within Azure Databricks

I am in need of transferring a group of files (Python or Scala) from a DBFS location to my user workspace directory for testing purposes. Uploading each file individually to the user workspace directory is quite cumbersome. Is there a way to easily move f ...

I am looking to dynamically generate HTML elements using AngularJS based on data from a JSON file

Although there are existing answers to this question, I have a specific approach that I need help with. I've already made progress but could use some guidance. This is my Controller : angular.module('dynamicForm.home-ctrl',[]) .con ...

The Controller is encountering an empty child array when attempting to JSON.stringify it

After examining numerous similar questions, I am uncertain about what sets my configuration apart. I've experimented with various ajax data variations and JSON formatting methods, but the current approach seems to be the closest match. This issue is ...

What is the proper way to provide JSON input for a PUT JAX-RS API that accepts data of type Map<Person, Person>?

I am working on a JAX-RS REST endpoint of PUT type where I need to pass a Map to the API. @PUT @Path("/some/path") @Consumes({ MediaType.TEXT_PLAIN, MediaType.APPLICATION_XML, MediaType.TEXT_XML, MediaType.APPLICATION_JSON }) @Produces({ MediaType ...

Confirming authenticity using (C# Program <> PHP Program)

Currently, we are working on a C# application that needs to store data in a central location. The user will be authenticated by the server, which will then return a session via the headers. Subsequently, the C# application will utilize the CDN for sendin ...

How can you show a different value in a select menu with AngularJS on selection?

When designing my menu to display US States for selection, I wanted to show both the 2-letter state code and the full name of the state initially. However, once the user selects a state, I only want to display the 2-letter code. This is how my menu looks: ...

json is failing to retrieve the correct information from the database array

I ran a query and received two rows of data, after testing it in phpadmin. However, when I checked Firebug, I could only view the information from one row. What might be causing this discrepancy? $data = mysql_fetch_assoc($r); } } head ...

"Unraveling Vue.js: A guide to fetching JSON data one object at a time

I am facing a challenge with a large JSON file (40 MB) that includes data on countries, their IDs, and a total sum that I need to calculate. { "0": { "id": 0, "country": "usa", "sum": 201, }, ...

Extract a Key from a JSON Dictionary using Python

I've recently started working on a script as part of my practice routine. The purpose of the script is to take user input and then store it inside a Json file. Here's how the code looks: import json command = int(input("Do You Want To Add, Or Re ...

Transforming a collection of Plain Old Java Objects into JSON will solely display the "id" attributes

I encountered an unusual issue with my project setup. I created a REST endpoint by bootstrapping a mvn archetype using Jersey, Grizzly2, and Moxy. This endpoint is supposed to return a Set of all POJOs in the DataSource. However, when I make a @GET request ...

Performing cross-origin GET request

I need help with a scenario involving a link and some JavaScript code. The setup is as follows: <a id="link" href="https://yahoo.com" target="blank">Link</a> Here is the script I'm using: var security = function() { var link ...

Real-time data feeds straight from JSON

Currently, I have a JSON file that is generated dynamically and it contains match information along with a unique id. This JSON data is categorized into live, upcoming, and recent arrays. Being new to Javascript, I am unsure about the best approach to crea ...

Arrays form when multiple tables merge in a many-to-many relationship

How do I retrieve book information in this specific format? { title: 'Avengers', description:'Good book', tags: [{id:1, name: 'Drama'},{id:2, name: 'Horror'}], authors: [{id:1, name: 'Alex'}, ...