String or binary data would be truncated. The statement has been terminated. While uploading profile

64,763

Check the database column you are trying to insert the data in to. The length defined for the data is less than what you are trying to insert.

For example, If you try to insert a value to a column defined as Firstname Varchar(50), and that value has a length over 50 then this will give the same exception you have mentioned.

Share:
64,763
user3642625
Author by

user3642625

Updated on May 24, 2020

Comments

  • user3642625
    user3642625 almost 4 years

    I am trying to use the asp.net Profile functionality to store the user information. I have an image in the profile properties.

    I am using the default profile provider given by asp.net in Visual Studio.

    Here is the definition of properties in web.config

      <properties>
        <add name="FirstName"/>
        <add name="MiddleName"/>
        <add name="LastName"/>
        <add name="ProfileImage" type="System.Byte[]" defaultValue='null'/>
        <add name="MobileNumber"/>
        <add name="TelephoneNumber"/>
      </properties>
    

    This is the code:

    protected void Button1_Click(object sender, EventArgs e)
            {
                var profile = HttpContext.Current.Profile;
                profile.SetPropertyValue("FirstName", TextBox1.Text);
                profile.SetPropertyValue("LastName",TextBox3.Text);
                profile.SetPropertyValue("MiddleName", TextBox2.Text);
                profile.SetPropertyValue("MobileNumber", TextBox4.Text);
                profile.SetPropertyValue("TelephoneNumber", TextBox5.Text);
    
            if (IsPostBack)
            {
                Boolean fileok = false;
                String path = Server.MapPath("~/UploadedImages/");
                path = System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(path);
    
                if (FileUpload1.HasFile)
                {
                    String fileExtension = System.IO.Path.GetExtension(FileUpload1.FileName).ToLower();
                    String[] allowedextensions = { ".gif", ".png", ".jpeg", ".jpg" };
                    for (int i = 0; i < allowedextensions.Length; i++)
                    {
                        if (fileExtension == allowedextensions[i])
                        {
                            fileok = true;
                        }
                    }
                }
                if (fileok)
                {
                    byte[] userImage = new byte[1025];
    
                    try
                    {
                       userImage = ReadFully(FileUpload1.PostedFile.InputStream);
    
    
                    }
                    catch (Exception ex)
                    {
                        //exception while getting the file
                        return;
                    }
    
                    profile.SetPropertyValue("ProfileImage", userImage);
                }
                else
                {
                  //file not okay type not image
                }
            }
    
    
        }
    //-------------------------------------------------------------Get The File in Byte Stream ---------------------------------//
        public static byte[] ReadFully(Stream input)
        {
            byte[] buffer = new byte[input.Length];
    
            using (MemoryStream ms = new MemoryStream())
            {
                int read;
                while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
                {
                    ms.Write(buffer, 0, read);
                }
                return ms.ToArray();
            }
        }
    

    But it is throwing following exception even for 34KB file which can't be right? Am I doing something wrong?

    [SqlException (0x80131904): String or binary data would be truncated.
    The statement has been terminated.]
       System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction) +1767866
       System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction) +5352418
       System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) +244
       System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady) +1691
       System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString) +269
       System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, SqlDataReader ds) +1406
       System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean asyncWrite) +177
       System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite) +205
       System.Data.SqlClient.SqlCommand.ExecuteNonQuery() +160
       System.Data.Mapping.Update.Internal.DynamicUpdateCommand.Execute(UpdateTranslator translator, EntityConnection connection, Dictionary`2 identifierValues, List`1 generatedValues) +535
       System.Data.Mapping.Update.Internal.UpdateTranslator.Update(IEntityStateManager stateManager, IEntityAdapter adapter) +262
    
    [UpdateException: An error occurred while updating the entries. See the inner exception for details.]
       System.Data.Mapping.Update.Internal.UpdateTranslator.Update(IEntityStateManager stateManager, IEntityAdapter adapter) +444
       System.Data.EntityClient.EntityAdapter.Update(IEntityStateManager entityCache) +146
       System.Data.Objects.ObjectContext.SaveChanges(SaveOptions options) +571
       System.Web.Providers.DefaultProfileProvider.SetPropertyValues(SettingsContext context, SettingsPropertyValueCollection collection) +745
       System.Configuration.SettingsBase.SaveCore() +389
       System.Configuration.SettingsBase.Save() +114
       System.Web.Profile.ProfileBase.SaveWithAssert() +31
       System.Web.Profile.ProfileBase.Save() +72
       System.Web.Profile.ProfileModule.OnLeave(Object source, EventArgs eventArgs) +9497686
       System.Web.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +136
      System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +69
    
  • DanKodi
    DanKodi over 9 years
    First of all you should not use image data type along with ntext and text data types will be removed in a future version of Microsoft SQL Server. If you have to work with it then it's fine. The image data type has a Variable-length binary data from 0 through 2^31-1 (2,147,483,647) bytes. So it does have a limit. Since the error comes for a 34kb file that shouldn't be the case.
  • user3642625
    user3642625 over 9 years
    Okay. I won' use the image datatype. But I did try to use VarBinary(MAX) too but it gave the same exception...
  • DanKodi
    DanKodi over 9 years
    Post your code for updating the database. The error is coming from there.
  • user3642625
    user3642625 over 9 years
    I am not updating it. As I mentioned, I am using the profile functionality of asp.net... The class Http.Context.Current.Profile has its own update function which I haven't tampered with. That is I haven't overloaded it. Am I supposed to do that?
  • DanKodi
    DanKodi over 9 years
    Did you try without the profileimage. It might be a different column that's throwing the exception. Try updating FirstName first and add other columns one by one. See what throws the error and check the column definition of that one.