server error when reading in an xml file - asp.net

I have some xml files which contain the source data for populating dropdown lists in my pages. These dropdowns are re-populated based on selected items from other dropdwons. I am getting a server error
Could not find a part of the path
X:\ASP.Net\CommodDisplay\DataFiles\dataXML.xml'.
Even though this is a valid path.
Here is the code im using to call it;
Dim doc As New XmlDocument()
'Load XML from the file into XmlDocument object
doc.Load(HttpContext.Current.Server.MapPath("~/DataFiles/dataXML.xml"))
Dim root As XmlNode = doc.DocumentElement
'Select all nodes with the tag Book
Dim nodeList As XmlNodeList = root.SelectNodes("futures")
For Each node As XmlNode In nodeList
ddlMainsub1.Items.Add(node.SelectSingleNode("product").InnerText)
Next
I also tried it just using Server.MapPath and I get the same error. These files are in a networked drive. Does that matter?

You asp.net service is running under a different user account then your own. You should be sure the service account has access to the path:
X:\ASP.Net\CommodDisplay\DataFiles\dataXML.xml
If part of the path is a network mapping it is possible that it is mapped for you but not for the service account running your website. Put all files local and try if that helps.

Related

how to add new connection string in web.config run time programatically in asp.net?

I am working on construction ERP.
When user adds new structure i have to create new database for each structure.Whether it is possible using script?
at the same time as i am creating new database for each structure then it is necessary to create one additional connection string in web.config file
very first i am trying to add new connection string in config file.for that i have written some code.but it gives me error.
string path = Server.MapPath(#"Web.config"); 'or' string path = Server.MapPath("~/Web.config");
var configuration = WebConfigurationManager.OpenWebConfiguration(path);
var section = (ConnectionStringsSection)configuration.GetSection("connectionStrings");
section.ConnectionStrings.Add(new ConnectionStringSettings(txtStructName.Text, txtStructName.Text, "System.Data.SqlClient"));
configuration.Save();
Error is :The relative virtual path is not allowed here.
help me to solve this problem.....
You shouldn't need to specify web.config.
Just do
WebConfigurationManager.OpenWebConfiguration("~");

System.InvalidOperationException error when attaching files to System.Net.Mail.MailMessage

I am getting an odd error when attaching one or more files to a System.Net.Mail.MailMessage object from an ASP.NET page.
I create a List(Of Attachment) and add new Attachment objects for each attached file requested by the user. These are files that reside on the web server's file system. For example, the code looks similar to the below, but rather than having hard-coded file paths it's getting them from the database. But while debugging I see that the file paths are valid, pointing to existing files that I can view from Explorer given the full file path or from the website using the virtual address (~/Documents/resume.pdf, for example).
Dim attachments As New List(Of Attachment)
attachments.Add(New Attachment("C:\Websites\Documents\resume.pdf"))
attachments.Add(New Attachment("C:\Websites\Documents\map.png"))
...
After constructing my attachments collection I send the email, adding each Attachment object to the Attachments collection like so:
Dim message As MailMessage = New MailMessage(from, toAddress, subject, body)
If attachments IsNot Nothing Then
For Each att As Attachment In attachments
message.Attachments.Add(att)
Next
End If
Dim mailClient As SmtpClient = New SmtpClient
mailClient.Send(message)
However, when I run the code I get the following error:
System.InvalidOperationException: One of the streams has already been used and can't be reset to the origin.
System.Web.HttpUnhandledException: Exception of type 'System.Web.HttpUnhandledException' was thrown. ---> System.Net.Mail.SmtpException: Failure sending mail. ---> System.InvalidOperationException: One of the streams has already been used and can't be reset to the origin.
at System.Net.Mime.MimePart.ResetStream()
at System.Net.Mail.Attachment.PrepareForSending()
at System.Net.Mail.MailMessage.SetContent()
at System.Net.Mail.MailMessage.Send(BaseWriter writer, Boolean sendEnvelope)
at System.Net.Mail.SmtpClient.Send(MailMessage message)
--- End of inner exception stack trace ---
...
I've tried replacing my logic that adds attachments based on a database query to one that adds a single file with a hard-coded file path. I've tried using different SMTP clients (my web host provider's SMTP server and GMail). I get the same error regardless.
Thanks
Found the answer... the problem was because I was trying to send two separate emails using the same attachments collection.
The email sending logic was in a function that was called like so:
SendEmail(from, to, subject, body, attachments)
If SomethingOrOther Then
SendEmail(from, someoneElse, subject, body, attachments)
End If
My (cheesy) workaround was to just create two attachments lists, one for the first call to SendEmail, another one for the second call.
I think better solution is to set your message object to nothing and your client option to nothing as well, before looping back around for the second message. Good luck!

File not found in EAR packaging

Inside my .ear
-META-INF
-lib
-ejb-shared.jar
-ejb.jar
-com/ejb/... (classes)
-fileXml.xml (file I'm trying to access)
-web.war
Some description:
"ejbshared" contains some ejbs and JPA entities
"ejb" contains some ejbs and JPA entities and uses "ejb-shared" project
The problem is that I can't access fileXml.xml. Inside an EJB bean (of ejb.jar) I've done:
File f = new File("fileXml.xml");
System.out.println(f.exists()); // returns false!
I don't know why, but it seems that fileXml.xml is not in the classpath, althougth it's present in the .ear, or maybe I'm doing things in the wrong way!
Using new File("fileXml.xml") will reference a file in the current working directory of the application server JVM, not relative to your specific application. Try using:
URL url = getClass().getResource("/fileXml.xml");
boolean exists = url != null;
System.out.println(exists);
InputStream input = url.openStream();
// ... read and close input stream

Webservice pdf file works in Debug but not after publish

We have a frankenstein webservice that I've been fixing a problem with pdf production and everything is working as expected in Debug but when I publish to the test IIS7 server it runs but I don't get the PDF.
The website callse this function and passes in the claimId
Public Function QServices_QAudit_GetWorkersCompCoverPage(ByVal claimId As Long) As Byte()
Dim sess As General.Session = Session.Item("sessionObject")
Dim pdfDocument As System.IO.MemoryStream
If Not AuthorizeUser(sess, Context, "qaudit") Then Return Nothing
pdfDocument = QAudit.QAuditData.GetWorkersCompCoverPage(claimId, sess)
If pdfDocument Is Nothing Then Return Nothing
Dim retValue As Byte()
ReDim retValue(0 To pdfDocument.Length - 1)
Dim i As Long
pdfDocument.Seek(0, IO.SeekOrigin.Begin)
For i = 0 To pdfDocument.Length - 1
retValue(i) = pdfDocument.ReadByte()
Next
Return retValue
End Function
Which in turn calls a function which reads in a pdf form, populates the fields saves it to the file system then converts it to a memory stream and returns it. Its converted to a byte stream and sent back to the website. Everything works great in debug but after publish, the pdf never gets saved. I'm thinking a permissions issue on either the folder that holds the blank pdf form or the folder that we write the completed form to, but I've given every permission I can think of including Network Services. IUSR, IIS_USRS and Authenticated Users but no change in the result. I've set the Application pool to Network Service, Local Service, Local System and the default and still no joy.
Any ideas on if there is another permission set I'm missing or something else in IIS7 that is preventing the file reading/writing?
Finally getting back to this one but learned it was a combination of IIS 7 loosing folder permissions every time we published the website and the app pool permissions of the webservice since it was running on a different level of .net. Basically we moved the pdf logic from the webservice to the website appcode folder and gave the local iis user permissions on this folder (through IIS, not through windows explorer) and everything is stable.

asp.net 2.0 asp:FIleUpload control saving uploaded files to a different server

I'm trying to use an asp:FileUpload Control to allow users to upload files (.doc, .gif, .xls, .jpg) to a server that is outside of our DMZ and not the Web Server. We want to have the ability to look at these files for viruses, structure, etc prior to saving them into another directory that would allow access to outside users. From what I have read about this control is that it will allow for files to be uploaded to the web server. Can this control be used to upload files to a server other than the web server? If it can be done where should I look for this type of functionality or how do I force it to go to https:\servername\folder name (Where server name is not the web server)? Would I have to read the file then write it to the other server?
Thanks,
Erin
FileUoload control can only upload data to the web server. If you need to save file to a different server, you need handle the POST request, read data from the Fileupload control and save them to your UNC share.
As far I know, using the fileupload control you actually upload contents to webserver which inturn gets rendered to your client (page) when requested; I don't think you can upload files to different server other than webserver; that shouldn't happen as well. Take a look at the below URL for fileupload if you want
http://msdn.microsoft.com/en-us/library/aa479405.aspx
http://www.asp.net/data-access/tutorials/uploading-files-cs
Thanks.
This depends on your web server setting and permission granted to the application. If it is DMZ then I would assume that a very minimal permission is granted to the application. In such scenario the application will not be able to access any resource other than webserver unless an explicit permission is granted to the account running application to access the network resource (which is not recommended). However, if the nework server you are trying to save the file has ftp enabled, then you could write the bytes streamed in file upload control to the network server with authenticated ftp account that has necessary permission.
You may use the below function:
Imports System.Net
Imports System.IO
Public Function Upload(ByVal FileByte() As Byte, ByVal FileName As String, ByVal ftpUserID As String, ByVal ftpPassword As String, ByVal ftpURL As String) As Boolean
Dim retValue As Boolean = False
Try
Dim ftpFullPath As String = ftpURL + "/" + FileName
Dim ftp As FtpWebRequest = FtpWebRequest.Create(New Uri(ftpFullPath))
ftp.Credentials = New NetworkCredential(ftpUserID, ftpPassword)
ftp.KeepAlive = True
ftp.UseBinary = True
ftp.Method = WebRequestMethods.Ftp.UploadFile
Dim ftpStream As Stream = ftp.GetRequestStream()
ftpStream.Write(FileByte, 0, FileByte.Length)
ftpStream.Close()
ftpStream.Dispose()
retValue = True
Catch ex As Exception
Throw ex
End Try
Return retValue
End Function
Function Call:
Upload(FileUploadControl.FileBytes, "filename.ext" "user", "password", "ftppath")

Resources