-2

With the code below I am able to save files to folder.

My problem is only two upload fields are mandatory and the remaining three are not. The code works if all the upload fields have a files selected otherswise its throws a NullReferenceException.

if (AnnualReport != null || ProjectReports != null || Publications != null || Other != null || RegistDoc != null) {
  int filesize = AnnualReport.PostedFile.ContentLength;
  int filesizeP = ProjectReports.PostedFile.ContentLength;
  int filesizePub = Publications.PostedFile.ContentLength;
  int filesizeOther = Other.PostedFile.ContentLength;
  int filesizeReg = RegistDoc.PostedFile.ContentLength;
  if (filesize > 2097152 && filesizeP > 2097152 && filesizePub > 1048576 && filesizeOther > 1048576 && filesizeReg > 1048576) {
    ScriptManager.RegisterStartupScript(this, this.GetType(), "popup", "alert('Maximum File size  For Annual/Project reports is 1.5MB and for the Publications/Other Attachemnets is 1MB');", true);
  } else {
    const string ReportDirectory = "REPORTS/";
    //Other Document
    string OtherPath = ReportDirectory + Other.FileName;
    string fileNameWithoutExtensionOther = System.IO.Path.GetFileNameWithoutExtension(Other.FileName);
    int iterationOther = 1; 
    while (System.IO.File.Exists(Server.MapPath(OtherPath))) {
      OtherPath = string.Concat(ReportDirectory, fileNameWithoutExtensionOther, "-", iterationOther, ".pdf");
      iterationOther++;
    }
    //Registration Document
    string RigisDocPath = ReportDirectory + RegistDoc.FileName;
    string fileNameWithoutExtensionRegis = System.IO.Path.GetFileNameWithoutExtension(RegistDoc.FileName);
    int iterationRE = 1; 
    while (System.IO.File.Exists(Server.MapPath(RigisDocPath))) {
      RigisDocPath = string.Concat(ReportDirectory, fileNameWithoutExtensionRegis, "-", iterationRE, ".pdf");
      iterationRE++;
    }
    //Annual Reports
    string ReportPath = ReportDirectory + AnnualReport.FileName;
    string fileNameWithoutExtension = System.IO.Path.GetFileNameWithoutExtension(AnnualReport.FileName);
    int iteration = 1; 
    while (System.IO.File.Exists(Server.MapPath(ReportPath))) {
      ReportPath = string.Concat(ReportDirectory, fileNameWithoutExtension, "-", iteration, ".pdf");
      iteration++;
    }
    //Project Report
    string ProjecttPath = ReportDirectory + ProjectReports.FileName;
    string fileNameWithoutExtensionP = System.IO.Path.GetFileNameWithoutExtension(ProjectReports.FileName);
    int iterationP = 1; 
    while (System.IO.File.Exists(Server.MapPath(ProjecttPath))) {
      ProjecttPath = string.Concat(ReportDirectory, fileNameWithoutExtensionP, "-", iterationP, ".pdf");
      iterationP++;
    }
    //publication 
    string publicationPath = ReportDirectory + Publications.FileName;
    string fileNameWithoutExtensionPub = System.IO.Path.GetFileNameWithoutExtension(Publications.FileName);
    int iterationPub = 1; 
    while (System.IO.File.Exists(Server.MapPath(publicationPath))) {
      publicationPath = string.Concat(ReportDirectory, fileNameWithoutExtensionPub, "-", iterationPub, ".pdf");
      iterationPub++;
    }
    ProjectReports.SaveAs(Server.MapPath(ProjecttPath));
    AnnualReport.SaveAs(Server.MapPath(ReportPath));
    Publications.SaveAs(Server.MapPath(publicationPath));
    RegistDoc.SaveAs(Server.MapPath(RigisDocPath));
    Other.SaveAs(Server.MapPath(OtherPath));
mason
  • 31,774
  • 10
  • 77
  • 121
  • 1
    You might be a beginner, but you should still format the code in your post so it's easy to read. You should also tell us where you throw the exception rather than making us guess. – mason Apr 08 '15 at 13:34
  • possible duplicate of [What is a NullReferenceException and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – mason Apr 08 '15 at 13:34
  • This is not an answer but more a suggestion of a different approach. For each of the objects that you are checking against for null, you could create an interface or abstract class which off of those class objects implement. This way, you can pass an instance of that base object or object that implements said interface, and check if it is null. If not, determine it's type and handle it appropriately. This would help reduce some of the clutter in your code and make it easier to read and interpret. If you need an example, I'd be happy to throw one together. – James Shaw Apr 08 '15 at 13:56
  • @JamesShaw, please do – Isaiah Otieno Apr 09 '15 at 05:03
  • @mason. I have updated the question. can you please remove the possible duplicate of What is a NullReferenceException and how do I fix it? – Isaiah Otieno Apr 09 '15 at 07:26
  • I have rolled back your edit, because you changed the nature of the question. If your question is now different, then ask a new one. Don't change a question if it invalidates existing answers. – mason Apr 09 '15 at 13:14

2 Answers2

0

The code you posted is very poorly formated. However, the solution to your immediate problem is to move the null checks down to each individual document.

Instead of doing a huge if line (which has questionable logic, as it only checks if ANY of the documents were uploaded)

You can just check if the required documents are present. (looking at your exising code, present means document name object is not null) If not, throw an error.

If they are, then proceed with the rest of the code, but wrap the individual processing of optional documents in their own null check if-s.

ie.

if (AnnualReport != null) {
//the block that does stuff with the anual report object
}
irreal
  • 2,217
  • 18
  • 23
0

I did beak down the code into diferent methods like @irreal suggested, like below;

public void PublicationReporting() {

            //connection for the datareader
            string csoWConn = ConfigurationManager.ConnectionStrings["RegisterCon"].ToString();
            SqlConnection csoW_connection = new SqlConnection(csoWConn);
            string database = csoW_connection.DataSource.ToString();
            csoW_connection.Open();

            if (Publications == null)
            {
                Publications.Dispose();

                ////
                String MyString = @"UPDATE tb_Quadrennial_Report SET PublicationsPath='' WHERE Org_ID = '" + Accrediated_Orgs.SelectedValue + "'";
                SqlCommand MyCmd = new SqlCommand(MyString, csoW_connection);
                int LastInsertedRecordID;

                LastInsertedRecordID = Convert.ToInt32(MyCmd.ExecuteScalar());


            }
            else
            {
                int filesizeP = Publications.PostedFile.ContentLength;

                if (filesizeP > 2097152)
                {
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "popup", "alert('Maximum File size  For Publication is 2.0 MB');", true);
                }

                else
                {

                    const string ReportDirectory = "REPORTS/";

                    //publication 
                    string publicationPath = ReportDirectory + Publications.FileName;
                    string fileNameWithoutExtensionPub = System.IO.Path.GetFileNameWithoutExtension(Publications.FileName);

                    int iteration = 1; while (System.IO.File.Exists(Server.MapPath(publicationPath)))
                    {
                        publicationPath = string.Concat(ReportDirectory, fileNameWithoutExtensionPub, "-", iteration, ".pdf");
                        iteration++;
                    }


                    Publications.SaveAs(Server.MapPath(publicationPath));

                    String MyString = @"UPDATE tb_Quadrennial_Report SET PublicationsPath='" + publicationPath + "' WHERE Org_ID = '" + Accrediated_Orgs.SelectedValue + "'";
                    SqlCommand MyCmd = new SqlCommand(MyString, csoW_connection);
                    int LastInsertedRecordID;

                    LastInsertedRecordID = Convert.ToInt32(MyCmd.ExecuteScalar());
                }

            }

        }

I then called it o the click event

  try{
                              PublicationReporting();
                        }

                          catch (Exception ex)
                        {

                            pgError.Text = "Publication Exception Message: " + ex.Message;

                        }

                          finally
                          {
                              csoW_connection.Close();
                          }

From here it was pretty easy to figure out the problem.

I just needed to dispose the content in the upload field if no file was selected like this

public void PublicationReporting() {

            //connection for the datareader
            string csoWConn = ConfigurationManager.ConnectionStrings["RegisterCon"].ToString();
            SqlConnection csoW_connection = new SqlConnection(csoWConn);
            string database = csoW_connection.DataSource.ToString();
            csoW_connection.Open();

            if (Publications == null)
            {
                Publications.Dispose();

                ////
                String MyString = @"UPDATE tb_Quadrennial_Report SET PublicationsPath='' WHERE Org_ID = '" + Accrediated_Orgs.SelectedValue + "'";
                SqlCommand MyCmd = new SqlCommand(MyString, csoW_connection);
                int LastInsertedRecordID;

                LastInsertedRecordID = Convert.ToInt32(MyCmd.ExecuteScalar());


            }
            else{

//program continues}