Solved

File upload - Network path was not found

Posted on 2013-01-31
9
1,415 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
Salesforce Has Never Been Easier

Improve and reinforce salesforce training & adoption using WalkMe's digital adoption platform. Start saving on costly employee training by creating fast intuitive Walk-Thrus for Salesforce. Claim your Free Account Now

 
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
 
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

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Just a quick little trick I learned recently.  Now that I'm using jQuery with abandon in my asp.net applications, I have grown tired of the following syntax:      (CODE) I suppose it just offends my sense of decency to put inline VBScript on a…
Problem Hi all,    While many today have fast Internet connection, there are many still who do not, or are connecting through devices with a slower connect, so light web pages and fast load times are still popular.    If your ASP.NET page …
A short tutorial showing how to set up an email signature in Outlook on the Web (previously known as OWA). For free email signatures designs, visit https://www.mail-signatures.com/articles/signature-templates/?sts=6651 If you want to manage em…
Exchange organizations may use the Journaling Agent of the Transport Service to archive messages going through Exchange. However, if the Transport Service is integrated with some email content management application (such as an antispam), the admini…

733 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