1

When I try to upload files using copy.asmx (CopyIntoItems method), I get the error "Unknown - Object reference not set to an instance of an object."

For me, even including <Fields> and <FieldInformation> I still get the same error.

And this exception occurs only for specific files, even with information (metadata) filled. Some files are uploaded correctly, others don't. When trying to re-upload the files which did not were uploaded, the same error appears.

Anyone know a reason for that?

This is my code:

public string UploadCpvtePgmtoSharePoint(
                                string filePath,
                                string fileName,
                                bool incluirTodosMetadados)
        {
            string docLibrary = "http://myportal/financeiro/";
            string libraryUrl = "ComprovantesPagamento";
            string retorno = String.Empty;

            WSCopy.Copy wsCopy = new WSCopy.Copy();

            wsCopy.Url = docLibrary + "_vti_bin/copy.asmx";
            wsCopy.Credentials = SPUtils.GetMOSSTimerCredentials();

            byte[] binaryFile = File.ReadAllBytes(filePath);

            string pasta = @"/";

            #region Fields

            // Title:
            WSCopy.FieldInformation fieldTitle = new WSCopy.FieldInformation();
            fieldTitle.DisplayName = "Title";
            fieldTitle.InternalName = "Title";
            fieldTitle.Type = WSCopy.FieldType.Text;
            fieldTitle.Value = fileName;

            WSCopy.FieldInformation[] fields = { fieldTitle };

            if (incluirTodosMetadados)
            {
                ComprovantePagamentoArquivo cpvte = new ComprovantePagamentoArquivo(filePath);

                WSHelper ob = new WSHelper();


                WSCopy.FieldInformation fcnpjCPFDest = ob.GetNewWSFieldInfo("CNPJ/CPF do Destinatário", "CNPJCPFDestinatario", WSCopy.FieldType.Text, cpvte.cnpjCPFDest);
                WSCopy.FieldInformation fcnpjCPFRem = ob.GetNewWSFieldInfo("CNPJ/CPF do Remetente", "CNPJCPFRemetente", WSCopy.FieldType.Text, cpvte.cnpjCPFRem);
                WSCopy.FieldInformation fcodAgenciaDest = ob.GetNewWSFieldInfo("Cod. Agência do Destinatário", "CodAgenciaDestinatario", WSCopy.FieldType.Text, cpvte.codAgenciaDest);
                WSCopy.FieldInformation fcodBancoDest = ob.GetNewWSFieldInfo("Cod. Banco do Destinatário", "CodBancoDestinatario", WSCopy.FieldType.Text, cpvte.codBancoDest);
                WSCopy.FieldInformation fnumeroCCDest = ob.GetNewWSFieldInfo("Conta do Destinatário", "NumeroCCDestinatario", WSCopy.FieldType.Text, cpvte.numeroCCDest);
                WSCopy.FieldInformation fnumeroCC = ob.GetNewWSFieldInfo("Conta do Remetente", "NumeroCCRemetente", WSCopy.FieldType.Text, cpvte.numeroCC);

                string sDataPgmto = "";
                if (!cpvte.dataPgmto.Trim().Equals(string.Empty))
                {
                    DateTime dataPgmto = DateTime.MinValue;
                    dataPgmto = DateTime.ParseExact(cpvte.dataPgmto, "dd/MM/yyyy", null);

                    // Converte o formato para MM/dd/yyyy
                    sDataPgmto = dataPgmto.ToString("MM/dd/yyyy");
                }

                WSCopy.FieldInformation fielddataPgmto = ob.GetNewWSFieldInfo("Data de Pagamento", "DataPagamento", WSCopy.FieldType.DateTime, sDataPgmto); 

                WSCopy.FieldInformation fidPgmto = ob.GetNewWSFieldInfo("ID do Pagamento", "IDPagamento", WSCopy.FieldType.Text, cpvte.idPgmto);
                WSCopy.FieldInformation fnomeDestinatario = ob.GetNewWSFieldInfo("Nome do Destinatário", "NomeDestinatario", WSCopy.FieldType.Text, cpvte.nomeDestinatario);
                WSCopy.FieldInformation fnomeRemetente = ob.GetNewWSFieldInfo("Nome do Remetente", "NomeRemetente", WSCopy.FieldType.Text, cpvte.nomeRemetente);
                WSCopy.FieldInformation fvalorPgmto = ob.GetNewWSFieldInfo("Valor do Pagamento", "ValorPagamento", WSCopy.FieldType.Currency, cpvte.valorPgmto.Replace(".", "").Replace(",", ".")); 
                WSCopy.FieldInformation fcodigoConvenio = ob.GetNewWSFieldInfo("Codigo Convenio", "CodigoConvenio", WSCopy.FieldType.Text, cpvte.codigoConvenio);


                WSCopy.FieldInformation[] fieldsNew = { fieldTitle, fcnpjCPFDest, fcnpjCPFRem, fcodAgenciaDest, fcodBancoDest, 
                                                    fnumeroCCDest, fnumeroCC, fidPgmto, fnomeDestinatario, fnomeRemetente, 
                                                    fvalorPgmto, fcodigoConvenio, fielddataPgmto };

                fields = fieldsNew;

                // Coloca na estrutura correta ANO\MES\DIA para upload:
                string estruturaPastas = ObtemEstruturaPastaData(cpvte.dataPgmto);
                pasta += estruturaPastas;
            }


            #endregion

            string destiny = docLibrary + 
                                libraryUrl +
                                pasta + 
                                Path.GetFileName(filePath);

            string otherDestiny = Path.GetFileName(filePath);

            string[] destinationUrl = { destiny };

            WSCopy.CopyResult resultTest = new WSCopy.CopyResult();
            WSCopy.CopyResult[] result = { resultTest };

            try
            {
                wsCopy.CopyIntoItems(otherDestiny, destinationUrl,
                                        fields, binaryFile, out result);


                if (result[0].ErrorCode != WSCopy.CopyErrorCode.Success)
                {
                    //gera uma exceção:
                    throw new ImpossivelEnviarDocumentoPortalException(
                                "Não foi possível enviar o documento ao portal: " +
                                    result[0].ErrorCode.ToString() + " - " +
                                    result[0].ErrorMessage);
                }

            }
            catch (Exception exc)
            {
                throw exc;
            }

            return retorno;
        }



        public string ObtemEstruturaPastaData(string sData)
            {
                DateTime dData;
                try
                {
                    dData = Convert.ToDateTime(sData);
                }
                catch (Exception ex)
                {
                    dData = DateTime.MinValue;
                }
                return PadraoNomeParaData(dData);
        }

        public static string PadraoNomeParaData(
                                            DateTime data)
            {
                if (data.Equals(DateTime.MinValue))
                {
                    return @"0001/" + @"01/" + @"01/";
                }
                else
                {
                    string ano = data.Year.ToString("0000");
                    string mes = data.Month.ToString("00");
                    string dia = data.Day.ToString("00");

                    return ano + @"/" + mes + @"/" + dia + @"/";
                }
        }

This is what is being transmitted (got using Fiddler):

<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><soap:Body><CopyIntoItems xmlns="http://schemas.microsoft.com/sharepoint/soap/"><SourceUrl>00413992006083000000000000187550901.html</SourceUrl><DestinationUrls><string>http://myportal/financeiro/ComprovantesPagamento/2006/08/30/00413992006083000000000000187550901.html</string></DestinationUrls>

<Fields>

<FieldInformation Type="Text" DisplayName="Title" InternalName="Title" Id="00000000-0000-0000-0000-000000000000" Value="00413992006083000000000000187550901.html" />

<FieldInformation Type="Text" DisplayName="CNPJCPFDestinatario" InternalName="CNPJCPFDestinatario" Id="00000000-0000-0000-0000-000000000000" Value="" />

<FieldInformation Type="Text" DisplayName="CNPJCPFRemetente" InternalName="CNPJCPFRemetente" Id="00000000-0000-0000-0000-000000000000" Value="15.000.000/0001-12" />

<FieldInformation Type="Text" DisplayName="CodAgenciaDestinatario" InternalName="CodAgenciaDestinatario" Id="00000000-0000-0000-0000-000000000000" Value="02432" />

<FieldInformation Type="Text" DisplayName="CodBancoDestinatario" InternalName="CodBancoDestinatario" Id="00000000-0000-0000-0000-000000000000" Value="324" />

<FieldInformation Type="Text" DisplayName="NumeroCCDestinatario" InternalName="NumeroCCDestinatario" Id="00000000-0000-0000-0000-000000000000" Value="000013000844-7" />

<FieldInformation Type="Text" DisplayName="NumeroCCRemetente" InternalName="NumeroCCRemetente" Id="00000000-0000-0000-0000-000000000000" Value="000000010512-3" />

<FieldInformation Type="Text" DisplayName="IDPagamento" InternalName="IDPagamento" Id="00000000-0000-0000-0000-000000000000" Value="000000187550901" />

<FieldInformation Type="Text" DisplayName="NomeDestinatario" InternalName="NomeDestinatario" Id="00000000-0000-0000-0000-000000000000" Value="CLIENTE LTDA ME" />

<FieldInformation Type="Text" DisplayName="NomeRemetente" InternalName="NomeRemetente" Id="00000000-0000-0000-0000-000000000000" Value="EMPRESA SA" />

<FieldInformation Type="Currency" DisplayName="ValorPagamento" InternalName="ValorPagamento" Id="00000000-0000-0000-0000-000000000000" Value="780.00" />

<FieldInformation Type="Text" DisplayName="CodigoConvenio" InternalName="CodigoConvenio" Id="00000000-0000-0000-0000-000000000000" Value="" />

<FieldInformation Type="DateTime" DisplayName="DataPagamento" InternalName="DataPagamento" Id="00000000-0000-0000-0000-000000000000" Value="08/30/2006" /></Fields>

<Stream>PCEtLUBOQU1FQDM5OTIwMDYwODMwMDAwMDAwMDAwMDAxODc1NTA5MDEtLT4KPCFET0NUWVBFIEhUTUwgUFVCTElDICItLy9XM0MvL0RURCBIVE1MIDQuMDEgVHJhbnNpdGlvbmFsLy9FTiI+CjxodG1sPgo8aGVhZD4KPHRpdGxlPiBDb21wcm92YW50ZSBQYWdhbWVudG8gLSBIU0JDIEJBTksgQlJBU0lMIFMuQS4gPC90aXRsZT4KPG1ldGEgaHR0cC1lcXVpdj0iQ29udGVudC1UeXBlIiBjb250ZW50PSJ0ZXh0L2h0bWw7IGNoYXJzZXQ9aXNvLTg4NTktMSI+CjxzdHlsZSB0eXBlPSJ0ZXh0L2NzcyI+CnRhYmxleyAKCWJvcmRlci1jb2xsYXBzZTogY29sbGFwc2U7Cglib3JkZXItY29sb3I6IGJsYWNrOwp9CnRkewoJZm9udDo4cHQvMS41ZW0sVmVyZGFuYSxBcmlhbCxTYW5zLXNlcmlmOwp9CmgzewoJZm9udC1zaXplOjhwdDsKCW1hcmdpbjo1cHg7Cn0KaDJ7C
</Stream>

</CopyIntoItems>

</soap:Body>

</soap:Envelope>

Server's response:

<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><soap:Body><CopyIntoItemsResponse xmlns="http://schemas.microsoft.com/sharepoint/soap/"><CopyIntoItemsResult>0</CopyIntoItemsResult><Results><CopyResult ErrorCode="Unknown" ErrorMessage="Object reference not set to an instance of an object." DestinationUrl="http://myportal/financeiro/ComprovantesPagamento/2006/08/30/00413992006083000000000000187550901.html" /></Results></CopyIntoItemsResponse></soap:Body></soap:Envelope>

Thanks!

  • Just a shot in the dark, it could be an encoding issue. Do you have funny characters, such as ampersands, in your filenames or in your metadata, on the files that fail? – Derek Gusoff May 21 '14 at 14:30
2

Finally got the solution!

The problem was too simple. I just don't believe it. Some files must be uploaded to specific folders, and those destination folders were not available. After creating them, the upload process worked normally.

Maybe Microsoft could improve the returned exception saying something like "Destination Folder does not exist" instead of "Unknown - Object reference not set to an instance of an object".

Thanks everyone!

| improve this answer | |
  • Hi @DouglasMendes, I am facing similar issue. Can you please explain what do you mean by Some files must be uploaded to specific folders, and those destination folders were not available. – Nikhil Chavan Jul 28 '15 at 13:51
  • Hi @NikhilChavan I meant that in my application some files had to be uploaded to specific folders, nothing related to the exception. Any more questions? – Douglas Mendes Oct 6 '15 at 17:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.