Need help on loading data

SaeedP

Well-known member
Joined
Oct 21, 2020
Messages
96
Programming Experience
3-5
Hi,

I'm doing a web app in blazor for Instagram. I use instaApiSharp:

Should I use load state from stream or loading state from String??

When I use " loadStateFromStream" ,
When I run nothing happens and just I see:
this message: Message: Loading state from file
and there is no exception.

C#:
if (File.Exists(stateFile))
    
             {
                    
                 message = "Loading state from file";
    
                 using (var fs = File.OpenRead(stateFile))
    
                 {
                        
                     _instaApi.LoadStateDataFromStream(fs);
    
                 }
             }
         }

and when using"loadStateFromString":

C#:
if (File.Exists(stateFile))
             {
                    
                 message = "Loading state from file";
    
                 using (var fs = File.OpenRead(stateFile))
                 {
                    _instaApi.LoadStateDataFromString(new StreamReader(fs).ReadToEnd());
                        
                 }

I encounter this exception:

ExceptionMessage: error: Newtonsoft.Json.JsonReaderException: Unexpected character encountered while parsing value: . Path '', line 1, position 1. at Newtonsoft.Json.JsonTextReader.ParseValue() at Newtonsoft.Json.JsonReader.ReadAndMoveToContent() at Newtonsoft.Json.JsonReader.ReadForType(JsonContract contract, Boolean hasConverter) at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(JsonReader reader, Type objectType, Boolean checkAdditionalContent) at Newtonsoft.Json.JsonSerializer.DeserializeInternal(JsonReader reader, Type objectType) at Newtonsoft.Json.JsonSerializer.Deserialize(JsonReader reader, Type objectType) at Newtonsoft.Json.JsonConvert.DeserializeObject(String value, Type type, JsonSerializerSettings settings) at Newtonsoft.Json.JsonConvert.DeserializeObject[T](String value, JsonSerializerSettings settings) at InstagramApiSharp.API.InstaApi.LoadStateDataFromString(String json) at InstaSite1.Pages.Enterance.StartInstagram() in

I'm doing my project in blazor and the API recommends to
"loadStateFromString"


You can see the whole code here:

C#:
@code{

    public static IInstaApi _instaApi;

    public static string username { get; set; }
    public static string password { get; set; }

    public static string message = string.Empty;

    public static string ExceptionMessage = string.Empty;



    private static async Task StartInstagram()
    {
        var userSession = new UserSessionData
        {
            UserName = Enterance.username,
            Password = Enterance.password
        };

        var _instaApi = InstaApiBuilder.CreateBuilder()
    .SetUser(userSession)
    .UseLogger(new DebugLogger(LogLevel.Exceptions))
    .Build();


        const string stateFile = "state.bin";
        try
        {
            // load session file if exists
            if (File.Exists(stateFile))
            {
                //Console.WriteLine("message = "";");
                message = "Loading state from file";

                using (var fs = File.OpenRead(stateFile))
                {
                    //_instaApi.LoadStateDataFromStream(fs);
                    //_instaApi.LoadStateDataFromString(new StreamReader(fs).ReadToEnd());
                    ////////////////////////////////////////////////////////////////////

                    //_instaApi.LoadStateDataFromString(new StreamReader(fs).ReadToEnd());

                    _instaApi.LoadStateDataFromStream(fs);

                }
            }
        }

        catch (Exception e)
        {
            ExceptionMessage = $" error: {e}";
        }
        if (!_instaApi.IsUserAuthenticated)
        {
            // login


            message = $"Logging in as {userSession.UserName}";
            var logInResult = await _instaApi.LoginAsync();
            if (!logInResult.Succeeded)
            {
                //Console.WriteLine($"Unable to login: {logInResult.Info.Message}");
                message = $"Unable to login: {logInResult.Info.Message}";
                return;
            }
        }

        // save session in file
        var state = _instaApi.GetStateDataAsStream();

        using (var fileStream = File.Create(stateFile))
        {
            state.Seek(0, SeekOrigin.Begin);
            state.CopyTo(fileStream);
        }

    }



}


What is your idea? Please inform me.

Regards,

Saeed


What is your idea?

Saeed
 
Based on your other question in another forum, as well as in this forum, it looks like the file actually contains binary data based on the filename "state.bin". It looks like LoadStateFromString() is expecting to find a valid JSON string, not some kind of binary data.
 
Yes. Read the exception text. It says that the JSON it was trying read had an invalid character at line 1, position 1. There is a very high probability that the file contains binary data instead of a JSON text string when that is the case.
 
Look at the source code of the library that you are using. See the highlighted lines below.

C#:
/// <summary>
///     Loads the state data from stream.
/// </summary>
/// <param name="stream">The stream.</param>
public void LoadStateDataFromStream(Stream stream)
{
    var data = SerializationHelper.DeserializeFromStream<StateData>(stream);
    LoadStateDataFromObject(data);
}
/// <summary>
///     Set state data from provided json string
/// </summary>
public void LoadStateDataFromString(string json)
{
    var data = SerializationHelper.DeserializeFromString<StateData>(json);
    LoadStateDataFromObject(data);
}

:

public static T DeserializeFromStream<T>(Stream stream)
{
#if !WINDOWS_UWP
    IFormatter formatter = new BinaryFormatter();
    stream.Seek(0, SeekOrigin.Begin);
    return (T)formatter.Deserialize(stream);
#else
    var json = new StreamReader(stream).ReadToEnd();
    return DeserializeFromString<T>(json);
#endif
    }

public static T DeserializeFromString<T>(string json)
{
    return JsonConvert.DeserializeObject<T>(json);
}

Since you are writing a web app for Blazor, it is not a UWP app. Hence the code in the #if !WINDOW_UWP is active. Notice that it is using a binary formatter, not a string like in the UWP case.
 
I wasn't telling you to replace anything. I was just telling you why you are getting that exception.

Who exactly is recommending that you use loadStateFromString()? Have you tried asking them what to do? I assume you can't ask FaceBook because you are using an unauthorized, undocumented API.
 
OMG! That library stores the username and password to the filesystem unencrypted. If that doesn't send shivers down your spine, you shouldn't be writing code that deals with user's account credentials.
 
Yes, recently I have asked but still got no answer.
You can see here:



Can you say clearly what is your suggestion?
 
I'm doing my project in blazor and the API recommends to
"loadStateFromString"
I'm asking who was recommending this. I'm not asking who else you have asked for help.
 
Okay. So presumably you also got the state using GetStateDataAsString() and saved the string somewhere. So you get the string from that somewhere and feed it back into LoadStateDataFromString().
 
OMG! That same sample code tells you exactly what to do:
C#:
// in .net core or uwp apps don't use LoadStateDataFromStream
// use this one:
// _instaApi.LoadStateDataFromString(new StreamReader(fs).ReadToEnd());
// you should pass json string as parameter to this function.

:

// in .net core or uwp apps don't use GetStateDataAsStream.
// use this one:
// var state = _instaApi.GetStateDataAsString();
// this returns you session as json string.

 
I don't use that library, and I personally wouldn't recommend it to anybody consider that:
1) It is not using the official InstaGram APIs;
2) It goes against the InstaGram terms of use;
3) I don't use InstaGram; and
4) It is insecure because it saves passwords and tokens in clear text.

All the information that you need is in post #12 and #13.
 
Last edited:
Back
Top Bottom