Click here to Skip to main content
15,850,299 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I got problem when I choose picture with size 500 Kb from my gallery and my application force close. But if i choose picture with size 100-499kb it is success load image and send base64 to my database. Could you help me how to fix it ?

What I have tried:

This is my coding from mobile app:
async void SavePicture(object sender, EventArgs e)
 {
        file = await CrossMedia.Current.PickPhotoAsync(new PickMediaOptions
        {
            PhotoSize = PhotoSize.Small
            //CompressionQuality = 100,

        });

        if (file == null)
            return;


        //Convert image to string
        FileStream fs = new FileStream(file.Path, FileMode.Open, FileAccess.Read);
        byte[] ImageData = new byte[fs.Length];
        fs.Read(ImageData, 0, System.Convert.ToInt32(fs.Length));
        fs.Close();
        string imgResized = Convert.ToBase64String(ImageData);

        imageResize.Source = file.Path;

        api = RestService.For<ApiInterface> 
        ("http://192.168.0.190/webservice/webservice.asmx");

        String idgoogle = "";

        var id = Application.Current.Properties["Id"].ToString();

        var stringimage = imgResized;


        User user = new User(idgoogle);
        user.Profile_Image = stringimage;
        user.Id = id;


        var responseupdate = await api.UpdateGoogle(new UpdateGoogleQuery(user));

        if (responseupdate.isSuccess)
        {
            Loading.toast("Sukses Menyimpan Foto");
        }
        else
        {
            LoadingFailed.toast("Gagal Menyimpan Foto");
        }

}

This is my coding from webservice:
public void update(User dtGoogle)
{
        String sql = $"UPDATE google SET profile_image = ('{dtGoogle.Profile_Image}') WHERE id = ('{dtGoogle.Id}')";
        Connection.executeSql(sql);
}



[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public void UpdateGoogle(String jsonOfData)
{
   Tools.Log("Check Update Google First", "AppDebugGoogle.txt");
   DbAccessConnection conn = getActiveConnection();

   if (conn == null)
     return;

   try
   {
      beginTransaction(conn);

      Google google = new Google(conn);
      Tools.Log("Check Update Google Second", "AppDebugGoogle.txt");
      User users = Tools.convertJsonIncludeDerivedTypes<User>(jsonOfData);
      Tools.Log("Check Update Google Third", "AppDebugGoogle.txt");

      google.update(users);
      Tools.Log("Check Update Google Four", "AppDebugGoogle.txt");

      commitTransaction(conn);
      Tools.Log("Check Update Google Five", "AppDebugGoogle.txt");
      Responder.writeResponse(true, "Success Update Data User Google");
    }
      catch (Exception ex)
      {
        Tools.Log("Check Update Google Six", "AppDebugGoogle.txt");
        rollbackTransaction(conn);
        Responder.writeResponse(false, ex.Message, ex.StackTrace);
       }
    }


It is message error when i choose picture with 500kb from my phone:
Refit.ApiException: 'Response status code does not indicate success: 500 (Internal Server Error).'

I try use log entry in method UpdateGoogle in web service it is success create AppDebugGoogle.txt and print log entry when i choose picture with size 100-499 kb from my phone. But if i choose picture with size 500 kb from my phone and i check AppDebugGoogle.txt it is not printed log entry.
Posted
Updated 3-Jan-20 20:56pm
v2
Comments
Richard MacCutchan 4-Jan-20 4:53am    
Why are you converting it to a Base64 string? Just save the data as a simple byte array. That will also save you using up all the extra memory when you convert the image to a string.
OriginalGriff 4-Jan-20 5:28am    
It may be to save processing time on output: no need to convert it to a base64 string each time you display / embed the image. With the cost of storage and a "relatively small" file size it's not a major problem to store 750KB instead of the raw 500K. Inefficient, but if it's a small number of images that are used frequently ...

But probably, it's because he doesn't know how to save non-text data.
Richard MacCutchan 4-Jan-20 5:35am    
Yes, and probably the same reason he does System.Convert.ToInt32(fs.Length).
OriginalGriff 4-Jan-20 5:48am    
That's probably because it's a long and the compiler complained about no matching method ... I can't be bothered to teach him about casting today ... :sigh:

1 solution

Simple: you are doing this in a very, very dangerous way.
Never concatenate strings to build a SQL command. It leaves you wide open to accidental or deliberate SQL Injection attack which can destroy your entire database. Always use Parameterized queries instead.

When you concatenate strings, you cause problems because SQL receives commands like:
SQL
SELECT * FROM MyTable WHERE StreetAddress = 'Baker's Wood'
The quote the user added terminates the string as far as SQL is concerned and you get problems. But it could be worse. If I come along and type this instead: "x';DROP TABLE MyTable;--" Then SQL receives a very different command:
SQL
SELECT * FROM MyTable WHERE StreetAddress = 'x';DROP TABLE MyTable;--'
Which SQL sees as three separate commands:
SQL
SELECT * FROM MyTable WHERE StreetAddress = 'x';
A perfectly valid SELECT
SQL
DROP TABLE MyTable;
A perfectly valid "delete the table" command
SQL
--'
And everything else is a comment.
So it does: selects any matching rows, deletes the table from the DB, and ignores anything else.

So ALWAYS use parameterized queries! Or be prepared to restore your DB from backup frequently. You do take backups regularly, don't you?

Fix that throughout your whole app - including the code above - and the problem you have noticed here will go as well: SQL has a maximum command text length of 64K * the network packet size (it's smaller on earlier versions) and Base64 strings are 4/3 longer than the data you input ...
 
Share this answer
 
Comments
Reyhan M.T 4-Jan-20 3:05am    
yes, i will rewrite my code in void update. Thank you so much,i use medium text in field profile_image in table google. But if i use command drop in public void Update it is will delete table google in my database sql
Christian Graus 4-Jan-20 5:22am    
THAT'S HIS POINT!!! Injection allows someone to delete your tables
jsc42 4-Jan-20 12:33pm    
Also check the size of the field in the database that the data is being saved into. A large image will need a large amount of storage and (as has already been mentioned) converting to Base64 inflates the size by 1/3. If the resultant size is bigger than the max size that the field can hold then the database update will fail.500Kb will need a field that can hold 682668 bytes.
OriginalGriff 4-Jan-20 12:40pm    
Twice that if the field is declared as Unicode (NVARCHAR instead of VARCHAR) as it allocates a byte-pair per character.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900