I am using lotus notes form as .html files and I am sending values to server as json using angular js. But I want to upload files also now. How can I send files to server and extract using lotus script?
Can you please help me someone?
Like the below post. But it is done in ASP.NET . I want to do the same using lotus notes.
File uploading angular js ASP .NET
index.html
<span ng-if="quests.type == '17'">
<input type="file" file-upload multiple id='{{quests.id}}'/>
</span>
<button type="button" ng-click="submitForm();">Submit</button>
The above button will trigger the below code to executed.
Angular Code to post to server
var email=document.getElementById("email").value;
var message={"requesttype": "saveForm","email": emailid,"username": username};
$http.post("http://test.com/ajaxprocess?openagent", message).success(success).error(failure);
The above mentioned agent(lotusscript) will parse the above json and save the document as shown below.
ajaxprocess Agent code
'getting document context
Set docContext = sess.DocumentContext
If docContext.hasItem("REQUEST_CONTENT") Or docContext.hasItem("REQUEST_CONTENT_000") Then
'using openNTF lotus script classes to parse document to json object
Set userDataInfo=getJSONObjectFromDocument(docContext, "")
Dim fieldsobj As New JSONArray
'getting the fields array sent as json array
Set fieldsobj=userDataInfo.GetItemValue("fields")
fieldtype=Field.mGetItemValue("type")(0)
Dim doc As NotesDocument
Dim fieldname As String
ForAll Field In fieldsobj.Items
fieldname=Field.mGetItemValue("Fieldname")(0)
Call doc.Replaceitemvalue(fieldname,Field.mGetItemValue("value")(0))
End ForAll
call doc.save(true,false)
End If
Everything works fine expect file attachments. How can I send files to server with json and save using lotus script or is there any other workaround is there?
I finally found tip and made the solution as follows to get the base64 String and convert to attachment in lotusscript.
http://www-10.lotus.com/ldd/bpmpblog.nsf/dx/creating-a-mime-email-with-attachment?opendocument&comments
Dim s As New NotesSession
Dim stream As NotesStream
Dim body As NotesMIMEEntity
Dim header As NotesMIMEHeader
Dim StringInBase64 As String
StringInBase64=getbase64() 'your base64 string
Dim db As NotesDatabase
Set db=s.Currentdatabase
Dim tempdoc As NotesDocument
Set tempdoc=db.Createdocument()
Set stream = s.CreateStream
Call stream.WriteText(StringInBase64)
Set body = tempdoc.CreateMIMEEntity
Set header = body.createHeader("content-disposition")
Call header.setHeaderVal({attachment;filename="Onchange.xlsx"}) ' file name and type should be configurable
Call body.SetContentFromText(stream, "", ENC_BASE64)
Call stream.Close
tempdoc.form="Attachment"
Call tempdoc.save(True,False)
This works as expected. Thanks all for time you spent.
Here is the code for Multiple attachments, enhancement from Vijayakumar.
Dim session As New NotesSession
Dim db As NotesDatabase
Dim doc As NotesDocument
Set db = session.CurrentDatabase
Set doc = db.CreateDocument
Dim s As New NotesSession
Dim stream As NotesStream
Dim body As NotesMIMEEntity
Dim child As NotesMimeEntity
Dim header As NotesMIMEHeader
Set body = doc.CreateMIMEEntity
topString = Split(BASE64, ",")
Dim tmp_array() As String
i = 0
For i = 0 To Ubound(topString)
Redim Preserve tmp_array(i)
tmp_array(i) = topString(i)
Set child = body.CreateChildEntity()
Set header = child.CreateHeader("Content-Type")
Call header.SetHeaderVal("multipart/mixed")
Set header =child.createHeader("Content-Disposition")
Call header.setHeaderVal({attachment; filename=test} &Cstr(i)& {.jpg}) 'file name and type should be configure
Set header =child.CreateHeader("Content-ID")
Call header.SetHeaderVal("test" &Cstr(i)& ".jpg")
Set stream = s.CreateStream()
Call stream.WriteText(topString(i))
Call child.SetContentFromText(stream, "", ENC_BASE64)
Next
doc.form="Attachment"
'doc.Attachment = tmp_array
Call doc.save(True,False)
Call stream.Close()
s.ConvertMIME = True ' Restore conversion
Related
Frequency should be 1 hour for creating an XML file. Once created, it needs to be sent through API. It has an API key for authenciation. It needs to be connected to a database first in order to get the data for creating the xml file. I need this functionality in VB (.NET)
Dim msgList As XElement
Dim xDoc As XDocument
Dim sw As New StringWriter()
Dim list As String = ""
Dim xmitList As String = ""
Dim xmitArray As New ArrayList
Dim xmlWriter As StringWriter = New StringWriter()
Dim SQLStatement As String = ""
Dim SQLErr As String = ""
Dim SQLResult As String = ""
Dim SQLResultTable As New DataTable
'********************
' Create the XML Document (XDeclaration sets the header information, and the XElement is the first node)
xDoc = New XDocument(
New XDeclaration("1.0", "UTF-16", "yes"),
New XElement("MessageList")
)
' Get the first node (<MessageList>) so we can then add child nodes to it when getting the data to send
msgList = xDoc.FirstNode
I came this far for creating the file in XML. Before this it needs to be connected to DB to grab the data and then start the process.
I tried creating the XML file but still stuck on completing that. Still left with two major steps excluding this, connecting to DB and sending the XML file using HTTP request. I need this functionality in VB (.NET).
On link Google drive link
I have value of JSON like
{
"APP_Name":"ThunderStorm",
"Version":"2.0.0.0",
"Download_URL":"PathToExe",
"Release_Info":"Info"
}
In my vb.net code when i use link to download that string
Dim client As New Net.WebClient
Dim Root_JSON As String = client.DownloadString("https://drive.google.com/open?id=1grin5l7VUa_Yw48H6ScFCKbMWv-Y-QpF")
I get bunch of HTML data. I need to download only JSON value so i would be able to deserialize it
Dim o_Json As t_Update.JSON_Application = JsonConvert.DeserializeObject(Of JSON_Application)(Root_JSON)
I have been trying to parse a bit of JSON data from an API as part of a larger project and due to my limited experience with VBA/Json I am having difficulties figuring out what the problem is with my VBA code.
I have used the following VBA Json Parsers and all basically stop working at the same point and give me an "incomplete parse".
vba-json https://code.google.com/archive/p/vba-json
vbjson www.ediy.co.nz/vbjson-json-parser-library-in-vb6-xidc55680
The Json I am trying to parse is the following:
{"links":[],"content":{"carrier":{"allowedToOperate":"Y","bipdInsuranceOnFile":"1000","bipdInsuranceRequired":"Y","bipdRequiredAmount":"750","bondInsuranceOnFile":"0","bondInsuranceRequired":"N","brokerAuthorityStatus":"N","cargoInsuranceOnFile":"0","cargoInsuranceRequired":"N","carrierOperation":{"carrierOperationCode":"A","carrierOperationDesc":"Interstate"},"commonAuthorityStatus":"A","contractAuthorityStatus":"A","crashTotal":19,"dbaName":null,"dotNumber":124871,"driverInsp":974,"driverOosInsp":33,"driverOosRate":3.38809034907597535934291581108829568789,"driverOosRateNationalAverage":"5.51","ein":460396676,"fatalCrash":0,"hazmatInsp":0,"hazmatOosInsp":0,"hazmatOosRate":0,"hazmatOosRateNationalAverage":"4.5","injCrash":6,"isPassengerCarrier":"N","issScore":null,"legalName":"A&A EXPRESS LLC","oosDate":null,"oosRateNationalAverageYear":"2009-2010","phone":"6055822402","phyCity":"BRANDON","phyCountry":"US","phyState":"SD","phyStreet":"1015 9TH AVENUE NORTH","phyZipcode":"57005","reviewDate":"2016-09-23","reviewType":"N","safetyRating":"S","safetyRatingDate":"2008-08-29","safetyReviewDate":"2016-09-23","safetyReviewType":"N","snapshotDate":"1485493200000","statusCode":"A","totalDrivers":237,"totalPowerUnits":253,"towawayCrash":13,"vehicleInsp":477,"vehicleOosInsp":58,"vehicleOosRate":12.15932914046121593291404612159329140461,"vehicleOosRateNationalAverage":"20.72"},"links"
my VBA code looks like the following:
Public Sub PARSEJSON()
Dim reader As New XMLHTTP60
Dim api As Object
Dim WS As Worksheet
Dim item As Variant
reader.Open "GET", "https://mobile.fmcsa.dot.gov/qc/services/carriers/124871?webKey=APIKEY", False
reader.send
Set WS = ActiveSheet
Set api = JSON.parse(reader.responseText)
For Each item In api
WS.Range("a3").Value = item("")
Next
End Sub
I cannot get into the JSON to reference the values that I need because the parser yields a result like:
photo of watcher in VBA
it seems like the Json parser is only breaking down part of the Json string from the API, it is from a government website so I am assuming it should be in a common Json format. I hope I included enough detail in this post to encompass the scope of my issue
I solved this issue, I looked further into how to reference a dictionary and realized I was using the wrong syntax to reference and adding in extra steps that were not needed.
new VBA code yields the results I want:
Public Sub PARSEJSON()
Dim reader As New XMLHTTP60
Dim dict As Object
Dim api As New Scripting.Dictionary
Dim json As New Class1
Dim WS As Worksheet
Dim key As Variant
Dim item As Variant
reader.Open "GET", "https://mobile.fmcsa.dot.gov/qc/services/carriers/124871?webKey=APIKEY", False
reader.send
Set WS = ActiveSheet
Set api = json.parse(reader.responseText)
MsgBox api("content")("carrier").Count
MsgBox api.item("content")("carrier")("driverOosInsp")
WS.Range("a1").value = api.item("content")("carrier")("driverOosInsp")
End Sub
I must write a program that periodically reads a web page and copies certain data from a table on that page to an Excel spreadsheet. I don't know where to start or what programming language is suitable for this project. I know a little C++ and Matlab programming. Can anyone offer advice to point me in the right direction or suggest open source projects which do something similar?
I can use wget(linux) or fget1(matlab) to download the webpages, but I don't know how can I save certain data from source of this webpages into Excel.
I will assume you have room for learning C#. Since you have to extract the table from a web page, you need a special library/framework to deal with web browsing such as Watin. After getting the table, it's matter of saving into Excel spreadsheet. For convenience, you can write a CSV format (comma separated text) and excel can open the file. Hope it helps
I used the following code vb.net to parse multiple html table from a saved web page to a datatable (the table must have the same structure) (using Html-Agility-Pack) and save it to Xml file:
Imports System.Net
Public Sub ParseHtmlTable(byval HtmlFilePath as String)
Dim webStream As Stream
Dim webResponse = ""
Dim req As FileWebRequest
Dim res As FileWebResponse
req = WebRequest.Create("file:///" & HtmlFilePath)
req.Method = "GET" ' Method of sending HTTP Request(GET/POST)
res = req.GetResponse ' Send Request
webStream = res.GetResponseStream() ' Get Response
Dim webStreamReader As New StreamReader(webStream)
Dim htmldoc As New HtmlAgilityPack.HtmlDocument
htmldoc.LoadHtml(webStreamReader.ReadToEnd())
Dim nodes As HtmlAgilityPack.HtmlNodeCollection = htmldoc.DocumentNode.SelectNodes("//table/tr")
Dim dtTable As New DataTable("Table1")
Dim Headers As List(Of String) = nodes(0).Elements("th").Select(Function(x) x.InnerText.Trim).ToList
For Each Hr In Headers
dtTable.Columns.Add(Hr)
Next
For Each node As HtmlAgilityPack.HtmlNode In nodes
Dim Row = node.Elements("td").Select(Function(x) x.InnerText.Trim).ToArray
dtTable.Rows.Add(Row)
Next
dtTable.WriteXml("G:\1.xml", XmlWriteMode.WriteSchema)
End Sub
After that import the file to Excel
Read this Article to import XML into excel
Hope it helps
Right I'm trying to send an Email form an excel spreadsheet though lotus notes, it has an attachment and the body needs to be in HTML.
I've got some code that from all I've read should allow me to do this however it doesn't.
Without the HTML body the attachment will send, when I impliment a HTML body the Email still sends but the attachment dissapears, I've tried rearanging the order of the code cutting out bits that might not be needed but all is invain.
(You need to reference Lotus Domino Objects to run this code.
strEmail is the email addresses
strAttach is the string location of the attachment
strSubject is the subject text
strBody is the body text
)
Sub Send_Lotus_Email(strEmail, strAttach, strSubject, strBody)
Dim noSession As Object, noDatabase As Object, noDocument As Object
Dim obAttachment As Object, EmbedObject As Object
Const EMBED_ATTACHMENT As Long = 1454
Set noSession = CreateObject("Notes.NotesSession")
Set noDatabase = noSession.GETDATABASE("", "")
'If Lotus Notes is not open then open the mail-part of it.
If noDatabase.IsOpen = False Then noDatabase.OPENMAIL
'Create the e-mail and the attachment.
Set noDocument = noDatabase.CreateDocument
Set obAttachment = noDocument.CreateRichTextItem("strAttach")
Set EmbedObject = obAttachment.EmbedObject(EMBED_ATTACHMENT, "", strAttach)
'Add values to the created e-mail main properties.
With noDocument
.Form = "Memo"
.SendTo = strEmail
'.Body = strBody ' Where to send the body if HTML body isn't used.
.Subject = strSubject
.SaveMessageOnSend = True
End With
noSession.ConvertMIME = False
Set Body = noDocument.CreateMIMEEntity("Body") ' MIMEEntity to support HTML
Set stream = noSession.CreateStream
Call stream.WriteText(strBody) ' Write the body text to the stream
Call Body.SetContentFromText(stream, "text/html;charset=iso-8859-1", ENC_IDENTITY_8BIT)
noSession.ConvertMIME = True
'Send the e-mail.
With noDocument
.PostedDate = Now()
.Send 0, strEmail
End With
'Release objects from the memory.
Set EmbedObject = Nothing
Set obAttachment = Nothing
Set noDocument = Nothing
Set noDatabase = Nothing
Set noSession = Nothing
End Sub
If somone could point me in the right direction I'd be greatly appreciated.
Edit:
I've done a little more investigating and I've found an oddity, if i look at the sent folder the emails all have the paperclip icon of having an attachment even though when you go into the email even in the sent the HTML ones don't show an attachment.
I have managed to solve my own problem.
In teh same way you create a MIME entry and stream in the HTML you need to do the same with the attachment, you also need to put them both inside a MIME entry within the email itself to hold both the HTML and Attachment at the same level otherwise you end up with a situation of the email with the body and a child entry of the attachment which is within another attachment. (it's odd but true)
Thus this is my solution:
Sub Send_Lotus_Email(Addresses, Attach, strSubject, strBody)
'Declare Variables
Dim s As Object
Dim db As Object
Dim body As Object
Dim bodyChild As Object
Dim header As Object
Dim stream As Object
Dim host As String
Dim message As Object
' Notes variables
Set s = CreateObject("Notes.NotesSession")
Set db = s.CurrentDatabase
Set stream = s.CreateStream
' Turn off auto conversion to rtf
s.ConvertMIME = False
' Create message
Set message = db.CreateDocument
message.Form = "memo"
message.Subject = strSubject
message.SendTo = Addresses
message.SaveMessageOnSend = True
' Create the body to hold HTML and attachment
Set body = message.CreateMIMEEntity
'Child mime entity which is going to contain the HTML which we put in the stream
Set bodyChild = body.CreateChildEntity()
Call stream.WriteText(strBody)
Call bodyChild.SetContentFromText(stream, "text/html;charset=iso-8859-1", ENC_NONE)
Call stream.Close
Call stream.Truncate
' This will run though an array of attachment paths and add them to the email
For i = 0 To UBound(Attach)
strAttach = Attach(i)
If Len(strAttach) > 0 And Len(Dir(strAttach)) > 0 Then
' Get the attachment file name
pos = InStrRev(strAttach, "\")
Filename = Right(strAttach, Len(strAttach) - pos)
'A new child mime entity to hold a file attachment
Set bodyChild = body.CreateChildEntity()
Set header = bodyChild.CreateHeader("Content-Type")
Call header.SetHeaderVal("multipart/mixed")
Set header = bodyChild.CreateHeader("Content-Disposition")
Call header.SetHeaderVal("attachment; filename=" & Filename)
Set header = bodyChild.CreateHeader("Content-ID")
Call header.SetHeaderVal(Filename)
Set stream = s.CreateStream()
If Not stream.Open(strAttach, "binary") Then
MsgBox "Open failed"
End If
If stream.Bytes = 0 Then
MsgBox "File has no content"
End If
Call bodyChild.SetContentFromBytes(stream, "application/msexcel", ENC_IDENTITY_BINARY)' All my attachments are excel this would need changing depensding on your attachments.
End If
Next
'Send the email
Call message.Send(False)
s.ConvertMIME = True ' Restore conversion
End Sub
Here is my actual code. I'm not even using strong type.
Dim mobjNotesSession As Object ' Back-end session reference'
Dim bConvertMime As Boolean
Dim stream As Object
Dim mimeHtmlPart As Object
Const ENC_QUOTED_PRINTABLE = 1726
mobjNotesSession = CreateObject("Lotus.NotesSession")
mobjNotesSession.Initialize()
mobjNotesDatabase = mobjNotesSession.GetDatabase("HQ2", "tim4")
mobjNotesDocument = mobjNotesDatabase.CreateDocument
bConvertMime = mobjNotesSession.ConvertMime
mobjNotesSession.ConvertMime = False
stream = mobjNotesSession.CreateStream()
Call stream.WriteText(txtBody.Text)
mobjNotesBody = mobjNotesDocument.CreateMIMEEntity("Body")
mimeHtmlPart = mobjNotesBody.CreateChildEntity() 'This returns "Type Mismatch" error'
Call mimeHtmlPart.SetContentFromText(stream, "text/html; charset=""iso-8859-1""", ENC_QUOTED_PRINTABLE)
Call stream.Close()
mobjNotesSession.ConvertMime = bConvertMime
Call mobjNotesDocument.CloseMIMEEntities(True, "Body")
No sorry I didn't i was running this in VBA which isn't strong typed so i can get away with not knowing the actual variable type for the body identity. i 've not been able to test this but I belive you need to reset the declarations to
Dim bodyChild As NotesMIMEEntity
this is the one you have trouble with the ones bellow you may find cause problems as well
Dim s As New NotesSession
Dim db As NotesDatabase
Dim body As NotesMIMEEntity
Dim header As NotesMIMEHeader
Dim stream As NotesStream
Dim host As String
Dim message As NotesDocument
Hope this helps