Solved

File upload - Network path was not found

Posted on 2013-01-31
9
1,361 Views
Last Modified: 2013-02-03
This is mind boggling to me. I've been at this for 2 weeks. I've put debug steps and I thought I'd fixed it but still get the same error.

This is what I'm doing:
1. I build a letter in code
2. I have it as PDF
3. I want to save it in database
4. I also fax the letter using a 3rd party API. This works

Sometimes, it doesnt happen all the time...i get the error below. I've run out of ideas on what I need to do to get rid of this error...

at System.Data.SqlTypes.SqlFileStream.OpenSqlFileStream(String path, Byte[] transactionContext, FileAccess access, FileOptions options, Int64 allocationSize)     at System.Data.SqlTypes.SqlFileStream..ctor(String path, Byte[] transactionContext, FileAccess access, FileOptions options, Int64 allocationSize)     at System.Data.SqlTypes.SqlFileStream..ctor(String path, Byte[] transactionContext, FileAccess access)     at UserControl_NonMemberFax.SaveLetterDatabase(Byte[] dataLetter, String fax, String patientId, Nullable`1 nonMemberProviderId)     at UserControl_NonMemberFax.btnSubmit_onClick(Object sender, EventArgs e)========The network path was not found

I think it comes from the database when I'm trying to save the doc

My code:

byte[] file1dataLetter = BuildByteLetter();
rowGuidId = SaveLetterDatabase(file1dataLetter, faxnumber, patientId.Text, nonMemberRowId);



 private string SaveLetterDatabase(byte[] dataLetter, string fax,string patientId, int? nonMemberProviderId)
    {
        SqlConnection objSqlCon = new SqlConnection(ConfigurationManager.ConnectionStrings["armsConnectionString"].ConnectionString);

        objSqlCon.Open();
        SqlTransaction objSqlTran = objSqlCon.BeginTransaction();
        SqlCommand objSqlCmd = new SqlCommand("FileAddLetter", objSqlCon, objSqlTran);

        objSqlCmd.CommandType = CommandType.StoredProcedure;
        SqlParameter objSqlParam1 = new SqlParameter("@SystemNumber", SqlDbType.Int);
        objSqlParam1.Value = "1";

        SqlParameter objSqlParam2 = new SqlParameter("@FileType", SqlDbType.VarChar, 4);
        objSqlParam2.Value = ".pdf";

        SqlParameter objSqlParam3 = new SqlParameter("@patientId", SqlDbType.Int);
        objSqlParam3.Value = int.Parse(patientId);

        SqlParameter objSqlParam4 = new SqlParameter("@fax", SqlDbType.VarChar);
        objSqlParam4.Value = fax.Substring(1,10);

        SqlParameter objSqlParam5 = new SqlParameter("@username", SqlDbType.VarChar);
        objSqlParam5.Value = UserSession;

        SqlParameter objSqlParam6 = new SqlParameter("@NonMemberProviderId", SqlDbType.Int);
        objSqlParam6.Value = nonMemberProviderId;

        SqlParameter objSqlParamOutput = new SqlParameter("@filepath", SqlDbType.VarChar, -1);
        objSqlParamOutput.Direction = ParameterDirection.Output;

        SqlParameter objSqlParamOutputId = new SqlParameter("@NewGuid", SqlDbType.VarChar, -1);
        objSqlParamOutputId.Direction = ParameterDirection.Output;

        objSqlCmd.Parameters.Add(objSqlParam2);
        objSqlCmd.Parameters.Add(objSqlParam1);
        objSqlCmd.Parameters.Add(objSqlParam3);
        objSqlCmd.Parameters.Add(objSqlParam4);
        objSqlCmd.Parameters.Add(objSqlParam5);
        objSqlCmd.Parameters.Add(objSqlParam6);

        objSqlCmd.Parameters.Add(objSqlParamOutput);
        objSqlCmd.Parameters.Add(objSqlParamOutputId);

        DashboardData dc = new DashboardData();
        objSqlCmd.ExecuteNonQuery();

        string Path = objSqlCmd.Parameters["@filepath"].Value.ToString();

        string rowGuidId = objSqlCmd.Parameters["@NewGuid"].Value.ToString();


        objSqlCmd = new SqlCommand("SELECT GET_FILESTREAM_TRANSACTION_CONTEXT()", objSqlCon, objSqlTran);
        byte[] objContext = (byte[])objSqlCmd.ExecuteScalar();


        //Writing the byte to db

        SqlFileStream objSqlFileStream = new SqlFileStream(Path, objContext, FileAccess.Write);

        objSqlFileStream.Write(dataLetter, 0, dataLetter.Length);
        objSqlFileStream.Close();
        objSqlTran.Commit();



        return rowGuidId;
    }


    private  byte[] BuildByteLetter()
    {
        //Create Document class object and set its size to letter and give space left, right, Top, Bottom Margin
        Document doc = new Document(iTextSharp.text.PageSize.LETTER, 10, 10, 42, 35);
        MemoryStream ms = new MemoryStream();
        PdfWriter wri = PdfWriter.GetInstance(doc, ms);
        //Open Document to write
        doc.Open();
      
        iTextSharp.text.html.simpleparser.HTMLWorker hw = new iTextSharp.text.html.simpleparser.HTMLWorker(doc);
        hw.Parse(new StringReader(BuildFaxLetter()));


        doc.Close();
        return ms.ToArray();
    }


private string BuildFaxLetter()     //call DB to get info and build the letter    }
    {

Open in new window


Stored proc

INSERT INTO [dbo].[Doc_Files_letter]
 ([Id],[SystemNumber],SystemFile,FileType ,PatientId,fax,NonMemberProviderId,UpdateUser, DateSent ) --UpdateUser,
  VALUES (@ID ,@SystemNumber,CAST('' AS VARBINARY(MAX)),@FileType,@patientId,@fax,@NonMemberProviderId,@username, GETDATE()) -- @username,
  

  select @filepath = SystemFile.PathName(), @NewGuid = @Id from Doc_Files_letter where Id = @ID

Open in new window

0
Comment
Question by:Camillia
  • 5
  • 3
9 Comments
 
LVL 7

Expert Comment

by:Element1910
ID: 38841218
Can you paste the UserControl_NonMemberFax.btnSubmit_onClick(Object sender, EventArgs e) event code as well?
0
 
LVL 7

Author Comment

by:Camillia
ID: 38841397
Here it is. I put debug steps all over that submit code to see if I can capture the error and I think maybe it's coming from the store proc. Any insight would be great


 
protected void btnSubmit_onClick(object sender, EventArgs e)
    {
     //send fax  

        bool success = true;

        string faxEmails = ConfigurationManager.AppSettings["FaxEmail"];
        

        if (Page.IsValid)
        {

            ListView patientInfoListView = (ListView) this.Parent.FindControl("lvPatientDetailNonMember");
            Literal patientId = null;
            foreach (var data in patientInfoListView.Items)
            {
                patientId = (Literal) data.FindControl("lPatientId"); //get patientId from parent page
            }

            ////get patient info
            DashboardData db = new DashboardData();


            const string username = ".....";
            const string password = ".....";

            string faxnumber = "....";
            if (ConfigurationManager.AppSettings["TestFax"] == "N")
                faxnumber = string.Concat("1", fax1.Value, fax2.Value, fax3.Value);


            interfaxWebService.InterFax ifws = new interfaxWebService.InterFax();
          
            //*** save non-member provider

           // var permissionSet = new PermissionSet(PermissionState.None);

            string rowGuidId = Guid.NewGuid().ToString();// init it to guid, not empty string because if save-letter fails, we still want to save the doc
            NonMemberFaxStatus fs = new NonMemberFaxStatus();
            int? nonMemberRowId = null;
            try
            {
                // long st = ifws.Sendfax(username, password, faxnumber, BuildByteLetter(), "pdf");

             

                ARMSDataContext dc = new ARMSDataContext();
                dc.usp_debugfileUpload("1. In fax letter", UserSession);

                //***  replace above method
                byte[] file1dataLetter = BuildByteLetter();
                byte[] dataLetter = new byte[file1dataLetter.Length];
                Array.Copy(file1dataLetter, dataLetter, file1dataLetter.Length);
                string fileTypesLetter = "pdf";
                string fileSizesLetter = file1dataLetter.Length.ToString();

                dc.usp_debugfileUpload("2. after build letter", UserSession);
                DateTime postponeTimeLetter = DateTime.Now.AddDays(-2);
                // in two hours. use any PAST time to send ASAP
                int retriesToPerformLetter = 2;
                string csidLetter = "";
                string pageHeaderLetter = "";
                string subjectLetter = "DoctorAccessNow Letter Fax: " + search_physician_first_name.Text + " " +
                                       search_physician_last_name.Text;
             
                    string replyAddressLetter = faxEmails +";" + ContactEmail + ";" + txtEmail.Text;
                
                string pageSizeLetter = "A4";
                string pageorientationLetter = "Portrait";
                bool isHighResolutionLetter = false;
                //this will speed up your transmission
                bool isFineRenderingLetter = false;
                //fine will fit more graphics, while normal (false) will fit more textual documents

                dc.usp_debugfileUpload("3. before fax letter", UserSession);
                long st2Letter = ifws.SendfaxEx_2(username, password, faxnumber,
                                                  "", dataLetter, fileTypesLetter, fileSizesLetter,
                                                  postponeTimeLetter, retriesToPerformLetter, csidLetter,
                                                  pageHeaderLetter, "", subjectLetter, replyAddressLetter,
                                                  pageSizeLetter, pageorientationLetter,
                                                  isHighResolutionLetter, isFineRenderingLetter);

                dc.usp_debugfileUpload("4. after fax letter", UserSession);
                // end of sending letter

                NonMemberProvider nmp = new NonMemberProvider();
                nmp.FirstName = search_physician_first_name.Text.Trim();
                nmp.LastName = search_physician_last_name.Text.Trim();
                nmp.Fax = string.Concat(fax1.Value, fax2.Value, fax3.Value);
                nmp.Reason = new System.Data.Linq.Binary(System.Text.Encoding.UTF8.GetBytes(txtReason.Text));
                nmp.Comments = new System.Data.Linq.Binary(System.Text.Encoding.UTF8.GetBytes(txtComment.Text));
                nmp.PatientId = int.Parse(patientId.Text);
                nmp.UpdateDate = DateTime.Now;
                nmp.UpdateUser = UserSession;

                nonMemberRowId = db.SaveNonMemberProvider(nmp);

                dc.usp_debugfileUpload("5. after memberid save", UserSession);
                // save interfax status
               
                fs.UpdateUser = UserSession;
                fs.UpdateDate = DateTime.Now;
                fs.InterfaxStatus = int.Parse(st2Letter.ToString());

                fs.NonMemberProviderId = int.Parse(nonMemberRowId.ToString());
                db.SaveFaxStatus(fs);
                dc.usp_debugfileUpload("7. after fax save status", UserSession);

                // rowGuidId = SaveLetterDatabase(dataLetter, faxnumber, patientId.Text, nonMemberRowId);
                 rowGuidId = SaveLetterDatabase(file1dataLetter, faxnumber, patientId.Text, nonMemberRowId);
                 dc.usp_debugfileUpload("Last step: after fax save", UserSession);

                

            }
              catch (Exception ex)
              {
                  success = false;

                  ErrorLog el = new ErrorLog
                  {
                      UserName = UserSession,
                      PageName = "NonMemberFax Page - Letter",
                      ErrorMsg = ex.StackTrace + "========" +  ex.Message,
                      UpdateDate = DateTime.Now
                  };

                new LogAction().LogError(el);
                lmsg.Text = string.Concat("Fax letter Error: ", ex.Message);
                 
              }


            //fax files
            try
            {


                byte[] data = new byte[0];
                string fileTypes = string.Empty;
                string fileSizes = string.Empty;

                //http://www.telerik.com/help/aspnet-ajax/upload-manipulating-files.html
                if (RadUpload1.UploadedFiles.Count > 0)
                {
                    //***debug step
                    ARMSDataContext dc = new ARMSDataContext();
                    dc.usp_debugfileUpload("1. In FileUpload", UserSession);


                    //*** end of debug

                    foreach (UploadedFile file in RadUpload1.UploadedFiles)
                    {
                        //***debug step
                        dc.usp_debugfileUpload("2. " + file.FileName, UserSession);

                        //*** end of debug

                        //var readPermission = new FileIOPermission(FileIOPermissionAccess.Read, file.FileName);
                        //permissionSet.AddPermission(readPermission);


                        byte[] bytes = new byte[file.ContentLength];
                        file.InputStream.Read(bytes, 0, file.ContentLength);


                        // keep the original length
                        int orgLength = data.Length;


                        // resize the array: it should be the original length + the new one
                        data = (byte[])ResizeArray(data, orgLength + bytes.Length);


                        // add the new bytes to the array
                        Array.Copy(bytes, 0, data, orgLength, bytes.Length);


                        fileTypes = fileTypes + ";" + file.GetExtension().TrimStart('.') + ";";
                        fileSizes = fileSizes + ";" + bytes.Length + ";";


                        fileTypes = fileTypes.Remove(fileTypes.LastIndexOf(";"));
                        fileSizes = fileSizes.Remove(fileSizes.LastIndexOf(";"));

                        if (fileTypes.Substring(0, 1) == ";")
                            fileTypes = fileTypes.Remove(0, 1);

                        if (fileSizes.Substring(0, 1) == ";")
                            fileSizes = fileSizes.Remove(0, 1);


                        DateTime postponeTime = DateTime.Now.AddDays(-2);
                        // in two hours. use any PAST time to send ASAP
                        int retriesToPerform = 2;
                        string csid = "";
                        string pageHeader = "To: " + search_physician_first_name.Text + " " +
                                            search_physician_last_name.Text;
                        string subject = "DoctorAccessNow Document Fax " + pageHeader;
                        string replyAddress = faxEmails + ";" + ContactEmail + ";" + txtEmail.Text;
                        string pageSize = "A4";
                        string pageorientation = "Portrait";
                        bool isHighResolution = false;
                        //this will speed up your transmission
                        bool isFineRendering = false;
                        //fine will fit more graphics, while normal (false) will fit more textual documents


                        ////***debug step

                        dc.usp_debugfileUpload("3. Before fax ", UserSession);

                        ////*** end of debug

                        // if (permissionSet.IsSubsetOf(AppDomain.CurrentDomain.PermissionSet))
                        // {
                        long st2 = ifws.SendfaxEx_2(username, password, faxnumber,
                                               search_physician_first_name.Text + " " +
                                               search_physician_last_name.Text, data, fileTypes, fileSizes,
                                               postponeTime, retriesToPerform, csid,
                                               pageHeader, "", subject, replyAddress, pageSize, pageorientation,
                                               isHighResolution, isFineRendering);

                        fs.UpdateDate = DateTime.Now;
                        fs.InterfaxStatus = int.Parse(st2.ToString());

                        dc.usp_debugfileUpload("4. after fax ", UserSession);

                        db.SaveFaxStatus(fs);

                        dc.usp_debugfileUpload("5. After fax status ", UserSession);
                        SaveDocDatabase(data, faxnumber, patientId.Text, nonMemberRowId, rowGuidId);
                        dc.usp_debugfileUpload("6. After save fax doc ", UserSession);
                        //}
                        //else
                        //{
                        //    lmsg.Text = "File cannot be faxed. Folder permission error.";
                        //}



                        ////***debug step
                        dc.usp_debugfileUpload("4. After fax and database: " + st2, UserSession);

                        ////*** end of debug
                        
                    }

                }


            }
            catch (Exception ex)
            {
                success = false;
                ErrorLog el = new ErrorLog
                {
                    UserName = UserSession,
                    PageName = "NonMemberFax Page - Doc",
                    ErrorMsg = ex.StackTrace + "========" + ex.Message,
                    UpdateDate = DateTime.Now
                };

                new LogAction().LogError(el);
                lmsg.Text = string.Concat("Fax Document(s) Erorr: ", ex.Message);

            }

            try
            {
                if (txtEmail.Text != string.Empty)
                  db.SaveUserFaxEmail(UserSession,txtEmail.Text);

            }
            catch (Exception)
            {
               //it's ok if email is not updated. User can type it in again when they use the page again. So just redirect
                Response.Redirect("OutgoingPatientNonMember.aspx?pageTitleId=52", false);
            }


            if (success)
                Response.Redirect("OutgoingPatientNonMember.aspx?pageTitleId=52", false);

        }

    }

Open in new window

0
 
LVL 7

Author Comment

by:Camillia
ID: 38841457
0
 
LVL 7

Assisted Solution

by:Element1910
Element1910 earned 250 total points
ID: 38841725
Perform a try/catch on this:
try
            {
                rowGuidId = SaveLetterDatabase(file1dataLetter, faxnumber, patientId.Text, nonMemberRowId);
            }
            catch (Exception e1)
            {
                Response.Write("error in this function...");
            }

Open in new window

0
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
LVL 7

Author Comment

by:Camillia
ID: 38841768
I know the error is coming from that function because the code never reaches the line of debug after it:  dc.usp_debugfileUpload("Last step: after fax save", UserSession);

I can add the try catch you have as well. Now, if you look at my stored proc...is there a way to keep retrying that stored proc or anyway to keep retrying the save function. It doesnt happen all the time...it happens sometimes so I can keep retrying in the code...if possible
0
 
LVL 7

Expert Comment

by:Element1910
ID: 38842074
Yes, you can keep retrying it, but you have to code the correct if/else or try/catches and depending on the result, i.e. if (success) { next step } else { function(); }
0
 
LVL 7

Author Comment

by:Camillia
ID: 38842148
i wonder why it's happening to begin with. Is it firewall, is it connection, why it happens sometimes and why it doesnt at times...it's weird.
0
 
LVL 15

Accepted Solution

by:
angus_young_acdc earned 250 total points
ID: 38843011
To avoid this and other headaches it is good practice to not store the file in a directory somewhere then instead of storing the actual file in SQL, just store a link / directory path to where the file is stored.  

This has the benefit of not storing files in SQL (save space in your table(s)), it removes having to potentially convert a file to byte[] etc, and also should anybody modify the file for whatever reason you won't have to then update your table.
0
 
LVL 7

Author Comment

by:Camillia
ID: 38843817
>>To avoid this and other headaches it is good practice to not store the file in a directory somewhere then instead of storing the actual file in SQL, just store a link / directory path to where the file is stored.  

Isnt using SQL Server 2008's filestream recommanded by Microsoft? With Filestream, the actual file is not stored in SQL...correct?
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Resolve Dependency Issues 4 47
Entity Framework 7 32
C# guarantee sql connection close 6 30
How useful is the free version of Selenium? 3 13
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
This article aims to explain the working of CircularLogArchiver. This tool was designed to solve the buildup of log file in cases where systems do not support circular logging or where circular logging is not enabled
This Micro Tutorial hows how you can integrate  Mac OSX to a Windows Active Directory Domain. Apple has made it easy to allow users to bind their macs to a windows domain with relative ease. The following video show how to bind OSX Mavericks to …
Sending a Secure fax is easy with eFax Corporate (http://www.enterprise.efax.com). First, just open a new email message. In the To field, type your recipient's fax number @efaxsend.com. You can even send a secure international fax — just include t…

896 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

15 Experts available now in Live!

Get 1:1 Help Now