I have created an application in ASP.NET using VB. I have written following code.
It is giving an error in localhost but when I am running it from my application, it is working fine.
I have checked DCOMCNFG --> Outlook/Office entry is not present.
Please advise me how to open Outlook with the attachment from my application at localhost/server?
ByVal recipients As List(Of String),
ByVal smtpAddress As String,
ByVal attachments As List(Of String))
' Create a new MailItem and set the To, Subject, and Body properties.
'Dim application As New Outlook.Application
Dim application As New Outlook.Application()
Threading.Thread.Sleep(2000)
Dim newMail As Outlook.MailItem = DirectCast(application.CreateItem(Outlook.OlItemType.olMailItem), Outlook.MailItem)
' Set up all the recipients.
For Each recipient In recipients
newMail.Recipients.Add(recipient)
Next
If newMail.Recipients.ResolveAll() Then
newMail.Subject = subject
newMail.Body = body
For Each attachment As String In attachments
newMail.Attachments.Add(attachment, Outlook.OlAttachmentType.olByValue)
Next
End If
newMail.Display(True)
You need to use any third-party components that can deal with .pst files without Outlook involved.
Microsoft does not currently recommend, and does not support, Automation of Microsoft Office applications from any unattended, non-interactive client application or component (including ASP, ASP.NET, DCOM, and NT Services), because Office may exhibit unstable behavior and/or deadlock when Office is run in this environment.
If you are building a solution that runs in a server-side context, you should try to use components that have been made safe for unattended execution. Or, you should try to find alternatives that allow at least part of the code to run client-side. If you use an Office application from a server-side solution, the application will lack many of the necessary capabilities to run successfully. Additionally, you will be taking risks with the stability of your overall solution. Read more about that in the Considerations for server-side Automation of Office article.
Related
I need to send emails but preview them first before sending. I am using Visual Studio 2019 and my Outlook version is 2016 32-bit on a Windows 10 development machine.
I get an error
FileNotFoundException: Could not load file or assembly 'office, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c'. The system cannot find the file specified.
Yet I installed the COM libraries via browse to C:\Windows\assembly\GAC_MSIL\Microsoft.Office.Tools.Excel.v9.0\15.0.0.0
I use Outlook version 16 and from what I can tell there is no version 16 of the COM library.
Is there another way to get this working?
private void SendEmail()
{
try
{
Outlook.MailItem mailItem = (Outlook.MailItem)this.CreateItem(Outlook.OlItemType.olMailItem);
mailItem.Subject = "This is the subject";
mailItem.To = "someone#example.com";
mailItem.Body = "This is the message.";
mailItem.Importance = Outlook.OlImportance.olImportanceLow;
mailItem.Display(false);
}
catch (Exception eX)
{
throw new Exception("cDocument: Error occurred trying to create an Outlook e-mail"
+ Environment.NewLine + eX.Message);
}
}
This is the VB code I used to run Outlook on local machine.
Public Sub SendEmail(ByVal sTo As String, ByVal sSubject As String, ByVal sBody As String)
Try
If Not Process.GetProcessesByName("OUTLOOK").Any() Then
System.Diagnostics.Process.Start("Outlook.exe")
End If
'Dim oApp As Outlook._Application
'oApp = New Outlook.Application()
Dim oApp As Object
' Create a new MailItem.
'Dim oMsg As Outlook._MailItem
Dim oMsg As Object
Const olMailItem As Long = 0 'à commenter si marche pas
oApp = CreateObject("Outlook.Application") 'à commenter si marche pas
'oMsg = oApp.CreateItem(Outlook.OlItemType.olMailItem)
oMsg = oApp.CreateItem(olMailItem)
oMsg.Subject = sSubject
oMsg.Body = sBody
' TODO: Replace with a valid e-mail address.
oMsg.To = sTo
' Send
oMsg.Send()
' Clean up
oMsg = Nothing
oApp = Nothing
Catch ex As Exception
Debug.Print(ex.ToString)
End Try
End Sub
Is this really asp.net and a web based application???? You do realize the VAST difference between windows desktop software and web based, right? You can't use or display or show ANYTHING from a desktop program in a client side web browser. I have to assume you taking about desktop ONLY software here, and not web based? I mean, even if you could use Outlook in code, it would run on the web server, and the user would not see outlook running on that one web server computer box, would they?
And you certainly can't use and launch Outlook on the end user's client side machine. I mean, it would be really cool then if you come to my web site to view a cat picture, and I can now use YOUR copy of outlook, or Excel. Hey, why not launch your banking application and steal all that information? Or search your local hard drive for a Excel sheet called passwords? If you think about this, if that was possible, then ZERO people would EVER risk using the internet, right?
so, you have ZERO ability to use or mess with MY computer. You can't even search or look for a file on MY computer. It is my computer, and if just going to some web site could let you mess IN ANY WAY with my computer would be the worlds largest security hole.
You can certainly put up a nice big text box, even a send to box as a web form or web page. But sending that email will be based on YOUR own email settings and account that you setup on the web site. I mean, you think that YOUR web site is going to use MY email system and email password and information? Really? So I can now use YOUR software on YOUR computer from my web site? You really have to stop and think about what you asking? As noted, if you think about this, then you will well realize that this type of approach to web software is not possible, but it should ALSO be VERY obvious that such operations with web software could not be possible, since if it was, then no one would ever risk or even consider using the internet to do anything.
Even when you use a up-load file control, you can NEVER EVER even set the file to be picked for up-load - only the end user can do that. Your server side software cannot touch, see, know ANYTHING about the client side computer. Besides, that client computer might be a iPad, a smartphone, or your Apple Mac computer anyway - you have no idea, can't have any idea, and it can't matter.
so, client side software and files are 100% hands off. The end user has a browser sitting on their desktop. You can ONLY send it some HTML for that browser to then display.
And trying to use server side software? Well, if you did manage to do that, then on the server you would see outlook pop up on the computer. But the end user? They would not see anything - since you not able to see and use software.
It would be cool when you go to buy something on amazon, that you web browser lets YOU mess around with software on THEIR web server??
All you can do with a web system is create a web page and pass it down to the end user, and their browser will THEN render and display the markup. What you run on that web server (which is just a computer) is up to you, but you ONLY have the ability to pump out some HTML down to the users browser - nothing more, nothing less. Any windows program launched on the web server would only be seen if you were sitting at the console on and at the web server.
so, what would I do for a template? I would toss up a text box, or web form, and SAVE some template say to a database.
And if you REALLY smart you adopt ckedit, or a screen that allows you to enter markup. So, now you can drop in any graphics or fonts or whatever.
Say like this:
So, what I do with above is "save" my email templates into a database. I then have a simple routine that search/replace the fields like [Email] with the data from the database. So fonts, graphics etc? I can just edit and build and cut + paste in graphics.
But, I certainly can't really use outlook for this purpose. And the "sending" email address will have to be one for the web site - it can't be any old sending email.
We have a simple ASP.NET web Application that reads Excel files via an upload page and inserts rows in a database.
Users are uploading an Excel file that fills up a table in a MSSQL Database.
We are reading the Excel file via a simple code block like this.
Dim con As New OleDb.OleDbConnection()
con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source= " & filePath & ";Extended Properties=Excel 12.0"
'Get data from Exel into a DataFile
Try
con.Open()
Dim cmd As New OleDb.OleDbCommand("SELECT * FROM [Sheet1$]", con)
Dim da As New OleDb.OleDbDataAdapter()
da.SelectCommand = cmd
Dim ds As New DataSet()
da.Fill(ds, "DataSet")
Return ds.Tables(0)
Catch ex As Exception
HttpContext.Current.Session("Error") = "err: " & ex.Message
Throw ex
Return New DataTable()
Finally
con.Close()
End Try
Can the reading of an malitios Excel file through our app infect the server running the page?
Is Jet Engine so powerful that it may run malicious code embedded in an infected Excel file when accessing rows through the code?
The simple answer is yes, it's possible.
There is two types of malicious standard office documents in the world :
Macro based malicious activity
Macro based infected files are not so dangerous in your case because they are some extra objects embed in document and triggered by user interaction or some codes in your application which execute the macro automatically, so if you don't have any code to execute macros inside office documents, don't worry about office douments which infected by Macro scripts!
Exploit malicious activity
On other hand there is infected documents which contains exploits that target some bugs or logical features and etc. this files is so dangerous because they exploit the standard feature of documents (like parser). So if your underlying API or engine that parse this type of files implement and use this feature that was exploited, your program can be affected!
Finally if you want to protect the server from infection by this scenario, you should implement or use existing sandbox products which prevent the executed file from change anything on system and prevent the network and IO activity of executed file and for more security it's better to do the parse process in separate machine or VM not directly on main server and just return the result to server. but in general the sandbox solution is enough.
For example here is list of some Jet driver exploits that found just by Googling "Microsoft Jet driver Exploit":
MS08-028
CVE-2000-0325
CVE-2005-0944
CVE-2005-0944
Maybe it does not happen at all because of code reviews, fuzzing, penetration testing and bug bounty behind popular softwares and tools by the security experts before releases and that's the reason why you see so much less exploits for underlying popular software and tools like Jet driver, but even in security nothing is absolute and no one can claim that his product is safe.
At the end it depends on the platform you developing and how security important to you and your product. my answer is academic and may not occur. but even it's absolutely possible. so you should choose the best solution depending on your need and risk ;)
I have tricky problem, which I'm struggling quite a bit with.
The current solution, consists of a Classic ASP site hosted on some Win2K3 server, that calls some Client-side DLL's on XP machines coded in VB6.
These client-side DLL's then again can call some other COM objects, in this particular case it calls IBM Louts Notes (Lotus Domino Objects 1.2).
Now for different reasons these DLL's has to be converted to .NET (still x86), at this stage, this is the only change to be done. This works quite well except for one piece of code which throws an error.
COMException when calling the Lotus Notes COM object
ASP script calling the DLL
Set objLotus = CreateObject("OpenLotusNotes_FU_v2.clsMain")
sRet = objLotus.OpenLotus_mail()
Client-side DLL
Dim session As NotesSession = New NotesSession() 'works well
Dim objNotesWrkSp As Object
objNotesWrkSp = Activator.CreateInstance(Type.GetTypeFromProgID("Notes.NotesUIWorkspace")) 'crashes
Exception
Retrieving the COM class factory for component with CLSID {29131502-2EED-1069-BF5D-
00DD011186B7} failed due to the following error: 80080005
Server execution failed (Exception from HRESULT: 0x80080005 (CO_E_SERVER_EXEC_FAILURE)).
When I try to run this code in console application on the same computer, it works. So it has to be some permissions(?), I have tried changing basically everything I can think of.
Any help would be much appreciated!
Updated 01.09.2014
What I see is when I trigger the code from ASP, is that it creates a new process of Notes everytime, but only in the background, no UI what so ever. When I trigger the code from a console application, I get the Notes UI, which asks me for password, if I don't already have notes running.
I believe that I'm getting the Exception because it eventually times out.
Have a read of this article , your dealing with an Out Of Process COM component which may not initialize properly for some reason.
Another possibility is that the COM threading model is not supported in a free threaded component which .NET is by default compiled with. You can compile you DLL with a STA attribute, but as far am I'm aware that only effects console applications. You might find some additional information in this article from MS, if you have not already read it of course. Hope something there helps you solve your problem.
Consult with your admins first, but for this scenario you can set no password for the ID the Lotus Notes uses.
I did resolve this, so if anyone else would run in to this…
First of all configure the “Notes Link” Component Service to run as a “The interactive user” and that the process owner has permissions in "Launch and Activation Permissions" and "Access permissions".
Then this should be possible
Dim objNotesWrkSp As Object
Dim objWorkspace As Type = Type.GetTypeFromProgID("Notes.NotesUIWorkspace")
objNotesWrkSp = Activator.CreateInstance(objWorkspace)
As it turned out in this particular case I could only get it to work with late-binding, when I tried to this it just opened a conhost.exe process and then never responed:
Dim session as New NotesSession
session.Initialize()
Among other similar issues... So then I only used late-binding for all communication with Notes.
Dim mailServerPath, mailFile As String
objWorkspace.InvokeMember("OpenDatabase", Reflection.BindingFlags.InvokeMethod, Nothing, objNotesWrkSp, New Object() {mailServerPath, mailFile})
And so on...
I am converting and saving a word document to SQL Server database as varbinary. I can save the data. I want to display the uploaded Word document back to the user just like how a resume looks in Word, as if the actual Word document was embedded in the web page itself.
I have the below code, which is downloading the saved Word document as a Word file. Please tell me which is the best control to display the word document also inside the browser.
byte[] fileContent = new byte[fuResume.PostedFile.ContentLength];
fuResume.PostedFile.InputStream.Read(fileContent, 0, fuResume.PostedFile.ContentLength);
//lblAppliedMessage.Text = ByteArrayToString(fileContent);
//lblAppliedMessage.Text = BitConverter.ToString(fileContent).Replace("-", string.Empty);
byte[] btYourDoc;
btYourDoc = fileContent;
Response.ContentType = "application/ms-word";
Response.AddHeader("Content-Disposition",
"inline;filename=yourfilename.doc");
Response.BinaryWrite(btYourDoc);
Response.End();
Provided that you have word on the web server or on the application server, I would save to a temp file the stream coming from the database, open it with word, save as html and render this html in the web browser.
Edit:
as mentioned in the link provided in the comment: http://support.microsoft.com/default.aspx?scid=kb;EN-US;257757 you should possibly avoid usage of Word/Excel Automation on server side code, here an extract from this article from MS:
Microsoft does not currently recommend, and does not support,
Automation of Microsoft Office applications from any unattended,
non-interactive client application or component (including ASP,
ASP.NET, DCOM, and NT Services), because Office may exhibit unstable
behavior and/or deadlock when Office is run in this environment.
Suggested solutions/alternatives are:
Word Automation Services Overview
Excel Services Overview
I know this may be a simple answer or at least to most people but I'm not getting anywhere when attempting this on my own or through the various resources I have looked up. I'm pretty sure I'm just physically searching the wrong terminology or phrases to get my answers.
Here is my issue:
I am using ASP/VB.NET to build this integration. Visual Studio 2008. I previously had asked a question on API Integration on here and utilized that information to successfully perform the next steps. As this API is written differently I may not be grasping the appropriate functions correctly.
A company has given me several addresses for .ASMX portals. I add these into my service references. I can successfully see objects in my object browser and see all the procedures, etc., but further from here I'm unable to correctly use any objects. I attempted to replicate the integration based on my last API question and advice: Connecting to an API offered by a Company. When I'm attempting to use an object or simply relate a field to something on my script I continually get an error.
For example:
Dim A as New API.AddFunction
A.AccountNo = "123"
When running the page:
Object reference not set to an instance of an object.
Here is only one .ASMX I was given. I cannot release any more, until I receive permission to do so from the provider, I apologize.
http://cert1.tpayment.com:14935/Terminal.asmx
Anyhow, the root of my question is really how do I correctly interface with this API? What information do responders require so I can clarify this question more? Understandably you cannot guess at the problems until more information is shared. Is there a primer I can read through online?
The word you are looking for is XML web service or SOAP web service. This will help you with getting further with finding information on how to use such API. Specifically, your task is to "consume an XML web service using ASP.NET".
By having a quick look at the sample web service you provided it looks more than manageable. However, one thing you have to always remember that a web service operates on a "request - response" basis even though it is somewhat concealed when you add it as service reference to your project and it starts to look like just ordinary classes with methods and properties.
Here's a quick example to get you started. Let's assume you have a button "Button1" and a label "Label1" on your aspx page and that you added your example service as service reference with the namespace "Terminal". Here's a little server-side code for the click event of the button:
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
Dim SoapClient As New Terminal.TerminalSoapClient
Dim Credentials As New Terminal.OnBoardCredentials
Dim DataStructure As New Terminal.TerminalDataStructure
Dim ErrorMessages() As Terminal.OBAErrorMessage
Dim result As Boolean
Credentials.UserName = "username"
Credentials.PassWord = "password"
DataStructure.AccountNo = "123"
DataStructure.TerminalID = "123"
result = SoapClient.Add(Credentials, DataStructure, ErrorMessages)
Label1.Text = result.ToString & "; " & ErrorMessages(0).ErrorCode & " : " & ErrorMessages(0).ErrorMessage
End Sub
As you can see to start working with the web service you need a SOAP client. The client will expose the methods of the service such as "AddTerminal" in the example service.
Then you need to put together the arguments for that operation, which in the case of AddTerminal are "OnBoardCredentials", "terminal" (represented by the generic TerminalDataStructure class) and "ErrorMessage). Also note that this particular operation requires an array of ErrorMessages since the web service can return more than one in a single response.
Once you have specified the properties of each argument you are ready to call the operation (i.e. send the request) and use the returned value(s) (i.e. the response).
Technically, the response of this particular operation contains an overall result of the Add operation as boolean as well as error messages if any. However, only the overall result is returned by the TerminalSoapClient.Add operation whilst the error messages are added back to your array of OBAErrorMessage.
Lastly, for demo purposes I present the results back to label on the page. When I try it I get
False; 13000 : Error during Login
since I don't have valid credentials to log in to the service.
Though very crude I hope this example helps to get you started.