Get js confirm method value in asp.net 3.5 code behind button click.? - asp.net-3.5

I want to get this script value in the code behind?
Dim js As [String] =
(vbCr & vbLf & " if(confirm('Do you want to delete?')==true)" & vbCr & vbLf & "
document.getElementById('" & txtRespuesta.ClientID & "').value='true';"
& vbCr & vbLf & " else" & vbCr & vbLf & "
document.getElementById('") + txtRespuesta.ClientID & "').value='false';" & vbCr & vbLf & " "
ScriptManager.RegisterStartupScript(Me, Me.[GetType](), "Key", js, True)
If txtRespuesta.Text = "true" Then
'Action 1
Else
'Action 2
End If
how to capture this script value?
If i click YES = true, No=false..

onClick="if(confirm('do you really want to delete this?'))
{
delete()
}
else
{
//donothing or whatever
}
Also, missed the part 'should not work in the client script'. don't really know what you mean by that, but javascript is a clientside scripting language and you will need to use some sort of HttpRequest to communicate with the server.

Related

Calling REST API from Visual Basic

I keep getting a 404 error.
It works fine if I call the REST API from SoapUI.
I’m using Visual Basic VS2015.
I have a sample function which I’m calling from a simple forms project. This is just to get the REST API to work. The REST API call will go into a Visual Basic Windows Service once I get it working,
There is a form named form1 which has a txtURL textbox, a button to call sub Main(), and an output textbox called textbox1.
Public Shared Sub Main()
Try
Dim myHttpWebRequest As HttpWebRequest = CType(WebRequest.Create(Form1.txtURL.Text), HttpWebRequest)
With myHttpWebRequest
.Method = "POST"
.ContentType = "application/json"
.Accept = "application/json"
.MediaType = "jsonp"
With .Headers
.Add("Authorization", "Bearer ABCDabcd1234=")
.Add("riskLevelStatus", "6897")
.Add("userId", "12345")
.Add("applicationName", "MyApp")
End With
End With
Dim myHttpWebResponse As HttpWebResponse = CType(myHttpWebRequest.GetResponse(), HttpWebResponse)
Form1.TextBox1.Text = Form1.TextBox1.Text & myHttpWebResponse.ToString() & vbCrLf
myHttpWebResponse.Close()
'Catch exception if trying to add a restricted header.
Catch e As ArgumentException
Form1.TextBox1.Text = Form1.TextBox1.Text & "Error-ArgumentException: " & e.Message & vbCrLf
Catch e As WebException
Form1.TextBox1.Text = Form1.TextBox1.Text & "Error-WebException: " & e.Message & vbCrLf
If e.Status = WebExceptionStatus.ProtocolError Then
Form1.TextBox1.Text = Form1.TextBox1.Text & "Error-Status Code: " & CType(e.Response, HttpWebResponse).StatusCode & vbCrLf
Form1.TextBox1.Text = Form1.TextBox1.Text & "Error-Status Description: " & CType(e.Response, HttpWebResponse).StatusDescription & vbCrLf
Form1.TextBox1.Text = Form1.TextBox1.Text & "Error-Server: " & CType(e.Response, HttpWebResponse).Server & vbCrLf
End If
Catch e As Exception
Form1.TextBox1.Text = Form1.TextBox1.Text & "Error-Exception: " & e.Message & vbCrLf
End Try
End Sub 'Main
Here is what is outputted to textbox1:
Error -WebException: The remote server returned an Error: (400) Bad Request.
Error -Status Code: 400
Error -Status Description
Error -Server
What should be returned is a single line JSON, similar to this:
{“quid”: “jhgdsjdshg-hdbw-akjhjk-kdhbfsihg”}
It works fine when calling from SoapUI.
I believe this issue is how do I add data to the body?
I figured it out. I cannot believe nobody had an answer.
Public Sub Try01(URL)
Try
Dim myReq As HttpWebRequest
Dim myResp As HttpWebResponse
Dim myReader As StreamReader
myReq = HttpWebRequest.Create(URL)
myReq.Method = "POST"
myReq.ContentType = "application/json"
myReq.Accept = "application/json"
myReq.Headers.Add("Authorization", "Bearer LKJLMLKJLHLMKLJLM839800K=")
Dim myData As String = "{""riskLevelStatus"":""0001"",""userId"":""10000004030"",""applicationName"":""MyTestRESTAPI""}"
myReq.GetRequestStream.Write(System.Text.Encoding.UTF8.GetBytes(myData), 0, System.Text.Encoding.UTF8.GetBytes(myData).Count)
myResp = myReq.GetResponse
myReader = New System.IO.StreamReader(myResp.GetResponseStream)
TextBox1.Text = myReader.ReadToEnd
Catch ex As Exception
TextBox1.Text = TextBox1.Text & "Error: " & ex.Message
End Try
End Sub

Send email with attachment from any email program

I need to send an email from an MS Access database with an attachment (not an Access object, but a separate file), but not tied to any one email software (Groupwise, Outlook, etc). I have found code to send an email with an attachment using Groupwise and Outlook, and there is the generic DoCmd.SendObject which only appears to support attaching Access objects. Is there a way to send an email from Access with an attachment, regardless of the email client configured on the user's PC?
Rationale: There's complications with software rollout here. The machine I work on has Access 2013 and Outlook 2013 installed. The users of the database are running Access 2010, but when I compile the database into a .accde in 2013, it does not work on 2010. The only way I can get it to work is to compile it on a much older PC also running Access 2010. However, this old PC does not have Outlook and IT won't/can't install Outlook on it. This means I can't compile the database using the Outlook library, as there is no Outlook library on the machine.
Here is code I use to send e-mails using Gmail:
Public Function SendEmailViaGmail(SendTo As String, Optional Subject As String = "", Optional TextBody As String = "", Optional ReplyTo As String = "", Optional AttachedFiles As Variant = "") As String
On Error GoTo send_emailErr
Dim ErrNum As Long
Dim ErrDes As String
SendEmailViaGmail = ""
ErrNum = 0
Set cdomsg = CreateObject("CDO.message")
With cdomsg.Configuration.Fields
.Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2 'NTLM method
.Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "smtp.gmail.com"
.Item("http://schemas.microsoft.com/cdo/configuration/smptserverport") = 587
.Item("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = 1
.Item("http://schemas.microsoft.com/cdo/configuration/smtpusessl") = True
.Item("http://schemas.microsoft.com/cdo/configuration/smtpconnectiontimeout") = 60
.Item("http://schemas.microsoft.com/cdo/configuration/sendusername") = sendusername '
.Item("http://schemas.microsoft.com/cdo/configuration/sendpassword") = sendpassword
.Update
End With
' build email parts
With cdomsg
.To = SendTo
.FROM = sendusername
.Subject = Subject
.TextBody = TextBody & vbCrLf & vbCrLf & vbCrLf & "--" & vbCrLf & "Sent using Marlan Data-Systems"
If IsArray(AttachedFiles) Then
For Each AttachedFile In AttachedFiles
If Len(AttachedFile) > 3 Then .AddAttachment AttachedFile
Next
Else
If Len(AttachedFiles) > 3 Then .AddAttachment AttachedFiles
End If
.send
End With
SendEmailViaGmail = "Done!"
send_emailExit:
Set cdomsg = Nothing
Exit Function
send_emailErr:
ErrNum = Err.Number
ErrDes = Err.Description
Select Case Err.Number
Case -2147220977 'Likely cause, Incorrectly Formatted Email Address, server rejected the Email Format
SendEmailViaGmail = "Please Format the Email Address Correctly."
Case -2147220980 'Likely cause, No Recipient Provided (No Email Address)
SendEmailViaGmail = "Please Provide an Email Address"
Case -2147220960 'Likely cause, SendUsing Configuration Error
SendEmailViaGmail = "SendUsing Configuration Error"
Case -2147220973 'Likely cause, No Internet Connection
SendEmailViaGmail = "Please Check Internet Connection"
Case -2147220975 'Likely cause, Incorrect Password
SendEmailViaGmail = "Please Check Password"
Case Else 'Report Other Errors
SendEmailViaGmail = ""
End Select
SendEmailViaGmail = SendEmailViaGmail & " Error number: " & Err.Number & " Description: " & Err.Description
'If ErrNum = -2147220975 Then
' cdomsg.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smptserverport") = 465
' Resume
'End If
Resume send_emailExit
End Function
AttachedFiles is a String, or an Array of Strings, representing full paths to file or files that are to be attached to the email.
CDO.message is a Microsoft windows object.
You can replace value of smtpserver to some other mailing service. If you do so, please be sure to modify other parameters as well.
Code is based on code I found on the web.

ASP Contact form error Server object error 'ASP 0177 : 800401f3'

One of my websites contact/reservations form has suddenly stopped working and I now receive the following error.
Server object error 'ASP 0177 : 800401f3'
Server.CreateObject Failed
/contact2.asp, line 51
I've done a bit of research and it seems to relate to classic ASP commands but
my knowledge of ASP is limited.
Here is the full code:-
<%
name = request.form("name")
email = request.form("email")
phone = request.form("phone")
guests = request.form("guests")
datum2 = request.form("datum2")
info = request.form("info")
time_hour = request.form.item("time_hour")
time_minute = request.form.item("time_minute")
moda_event = request.form.item("modaEvent")
sign_up = request.form.item("signup")
If name="" or email="" Then
url = "reservations.asp?reqd=* indicates required field&name=" & mname & "&email=" & memail
If name="" Then
url = url & "&mname=*"
End if
If email="" Then
url = url & "&memail=*"
End if
response.redirect url & "&foobar=foobar#form"
response.end
End if
Dim objCDONTS ' Email object
Dim strFromName ' From persons' real name
Dim strFromEmail, strToEmail ' Email addresses
Dim strSubject, strName, strPhone, strEmail, strGuests, strDate, strHour, strMinute, strEvent, strInfo, strSignup 'Message
Dim misccompo
strSubject = "Reservation Form"
strFromName = Trim(Request.Form("name"))
strFromEmail = Trim(Request.Form("email"))
strToEmail = "reservations#modarestaurant.co.uk"
strName = Trim(Request.Form("name"))
strPhone = Trim(Request.Form("phone"))
strEmail = Trim(Request.Form("email"))
strGuests = Trim(Request.Form("guests"))
strDate = Trim(Request.Form("datum2"))
strHour = Trim(Request.Form.Item("time_hour"))
strMinute = Trim(Request.Form.Item("time_minute"))
strEvent = Trim(Request.Form.Item("moda_event"))
strInfo = Trim(Request.Form("info"))
strSignup = Trim(Request.Form.Item("signup"))
Set objCDONTS = Server.CreateObject("CDONTS.NewMail")
objCDONTS.From = strFromName & " <" & strFromEmail & ">"
objCDONTS.To = strToEmail
objCDONTS.Subject = strSubject
objCDONTS.Body = "--------------------------------------" & vbcrlf & vbcrlf & "Name: " & strName & vbcrlf & "Contact Number: " & strPhone & vbcrlf & "Email Address: " & strEmail & vbcrlf & "No. of Guests: " & strGuests & vbcrlf & "Date: " & strDate & vbcrlf & "Time: " & strHour & ":" & strMinute & vbcrlf & "Event: " & strEvent & vbcrlf & "Additional Info: " & vbcrlf & strInfo & vbcrlf & "Newsletter Signup: " & strSignup &vbcrlf & "--------------------------------------------------------------" & vbcrlf & "MESSAGE ENDS: End of info"
objCDONTS.Send
Set objCDONTS = Nothing
response.redirect "thank-you.asp"
response.end
%>
The line 51 error is this line;
Set objCDONTS = Server.CreateObject("CDONTS.NewMail")
Any help would be greatly appreciated.
The error
Server object error 'ASP 0177 : 800401f3'
Server.CreateObject Failed
/contact2.asp, line 51
means that the object could not be created because it could not find the appropriate DLL for the object requested. In other words, it is looking for the CDONTS COM component that was included with NT SP4 as the file cdont.dll. CDONTS was deprecated in Windows 2000 and completely removed in Windows 2003. Therefore, if you are using Window 2003, Windows 2008 or Windows 2012 server this error makes sense since the DLL is not present.
To fix this problem try the following - use CDOSYS. CDOSYS (cdosys.dll) is a library file provided as part of IIS for Windows 2000, Windows 2003 Server, and Windows 2008 Server. This DLL enabled applications to route SMTP messages across multiple platforms and added much more functionality over the older CDONTS library.
Here is a greatly simplified example to model some changes on
Dim Message As New CDO.Message
sch = "http://schemas.microsoft.com/cdo/configuration/"
Set cdoConfig = CreateObject("CDO.Configuration")
with cdoConfig.Fields
.item(sch & "sendusing") = 2
.Item(sch & "smtpserver") = "mail.xxxx.com" ' your SMTP mail server
.Item(sch & "smtpserverport") = 2525
.update
end with
'Create CDO message object
Set Message = CreateObject("CDO.Message")
With Message
set .configuration = cdoConfig
'Set email adress, subject And body
.From = strFromName
.To = strToEmail
.Subject = strSubject
.TextBody = TextBody
'Send the message
.Send
End With

Classic ASP amazon s3 rest authorisation

I am confused on what I am doing wrong here...
<script language="javascript" runat="server">
function GMTNow(){return new Date().toGMTString()}
</script>
<%
Const AWS_BUCKETNAME = "uk-bucketname"
Const AWS_ACCESSKEY = "GOES HERE"
Const AWS_SECRETKEY = "SECRET"
LocalFile = Server.Mappath("/test.jpg")
Dim sRemoteFilePath
sRemoteFilePath = "/files/test.jpg" 'Remote Path, note that AWS paths (in fact they aren't real paths) are strictly case sensitive
Dim strNow
strNow = GMTNow() ' GMT Date String
Dim StringToSign
StringToSign = Replace("PUT\n\nimage/jpeg\n\nx-amz-date:" & strNow & "\n/"& AWS_BUCKETNAME & sRemoteFilePath, "\n", vbLf)
Dim Signature
Signature = BytesToBase64(HMACSHA1(AWS_SECRETKEY, StringToSign))
Dim Authorization
Authorization = "AWS " & AWS_ACCESSKEY & ":" & Signature
Dim AWSBucketUrl
AWSBucketUrl = "http://s3.amazonaws.com/" & AWS_BUCKETNAME
With Server.CreateObject("Microsoft.XMLHTTP")
.open "PUT", AWSBucketUrl & sRemoteFilePath, False
.setRequestHeader "Authorization", Authorization
.setRequestHeader "Content-Type", "image/jpeg"
.setRequestHeader "Host", AWS_BUCKETNAME & ".s3.amazonaws.com"
.setRequestHeader "x-amz-date", strNow
.send GetBytes(LocalFile) 'Get bytes of local file and send
If .status = 200 Then ' successful
Response.Write "<a href="& AWSBucketUrl & sRemoteFilePath &" target=_blank>Uploaded File</a>"
Else ' an error ocurred, consider xml string of error details
Response.ContentType = "text/xml"
Response.Write .responseText
End If
End With
Function GetBytes(sPath)
dim fs,f
set fs=Server.CreateObject("Scripting.FileSystemObject")
set f=fs.GetFile(sPath)
GetBytes = f.Size
set f=nothing
set fs=nothing
End Function
Function BytesToBase64(varBytes)
With Server.CreateObject("MSXML2.DomDocument").CreateElement("b64")
.dataType = "bin.base64"
.nodeTypedValue = varBytes
BytesToBase64 = .Text
End With
End Function
Function HMACSHA1(varKey, varValue)
With Server.CreateObject("System.Security.Cryptography.HMACSHA1")
.Key = UTF8Bytes(varKey)
HMACSHA1 = .ComputeHash_2(UTF8Bytes(varValue))
End With
End Function
Function UTF8Bytes(varStr)
With Server.CreateObject("System.Text.UTF8Encoding")
UTF8Bytes = .GetBytes_4(varStr)
End With
End Function
%>
Now getting the error.
msxml3.dll error '800c0008'
The download of the specified resource has failed.
/s3.asp, line 39
I'd like to explain how S3 Rest Api works as far as I know.First, you need to learn what should be the string to sign Amazon accepts.
Format :
StringToSign = HTTP-Verb + "\n" +
Content-MD5 + "\n" +
Content-Type + "\n" +
Date + "\n" +
CanonicalizedAmzHeaders +
CanonicalizedResource;
Generating signed string :
Signature = Base64( HMAC-SHA1( YourSecretAccessKeyID, UTF-8-Encoding-Of( StringToSign ) ) );
Passing authorization header:
Authorization = "AWS" + " " + AWSAccessKeyId + ":" + Signature;
Unfortunately you'll play byte to byte since there is no any SDK released for classic asp. So, should understand by reading the entire page http://docs.amazonwebservices.com/AmazonS3/latest/dev/RESTAuthentication.html
For string to sign as you can see above in format, there are three native headers are reserved by the API. Content-Type, Content-MD5 and Date. These headers must be exists in the string to sign even your request hasn't them as empty without header name, just its value. There is an exception, Date header must be empty in string to sign if x-amz-date header is already exists in the request. Then, If request has canonical amazon headers, you should add them as key-value pairs like x-amz-headername:value. But, there is another exception need to be considered for multiple headers. Multiple headers should combine to one header with values comma separated.
Correct
x-amz-headername:value1,value2
Wrong
x-amz-headername:value1\n
x-amz-headername:value2
Most importantly, headers must be ascending order by its group in the string to sign. First, reserved headers with ascending order, then canonical headers with ascending order.
I'd recommend using DomDocument functionality to generate Base64 encoded strings.
Additionally instead of a Windows Scripting Component (.wsc files), you could use .Net's interops such as System.Security.Cryptography to generating keyed hashes more effectively with power of System.Text. All of these interoperabilities are available in today's IIS web servers.
So, as an example I wrote the below script just sends a file to bucket you specified. Consider and test it.
Assumed local file name is myimage.jpg and will be uploaded with same name to root of the bucket.
<script language="javascript" runat="server">
function GMTNow(){return new Date().toGMTString()}
</script>
<%
Const AWS_BUCKETNAME = "uk-bucketname"
Const AWS_ACCESSKEY = "GOES HERE"
Const AWS_SECRETKEY = "SECRET"
LocalFile = Server.Mappath("/test.jpg")
Dim sRemoteFilePath
sRemoteFilePath = "/files/test.jpg" 'Remote Path, note that AWS paths (in fact they aren't real paths) are strictly case sensitive
Dim strNow
strNow = GMTNow() ' GMT Date String
Dim StringToSign
StringToSign = Replace("PUT\n\nimage/jpeg\n\nx-amz-date:" & strNow & "\n/"& AWS_BUCKETNAME & sRemoteFilePath, "\n", vbLf)
Dim Signature
Signature = BytesToBase64(HMACSHA1(AWS_SECRETKEY, StringToSign))
Dim Authorization
Authorization = "AWS " & AWS_ACCESSKEY & ":" & Signature
Dim AWSBucketUrl
AWSBucketUrl = "https://" & AWS_BUCKETNAME & ".s3.amazonaws.com"
With Server.CreateObject("MSXML2.ServerXMLHTTP.6.0")
.open "PUT", AWSBucketUrl & sRemoteFilePath, False
.setRequestHeader "Authorization", Authorization
.setRequestHeader "Content-Type", "image/jpeg"
.setRequestHeader "Host", AWS_BUCKETNAME & ".s3.amazonaws.com"
.setRequestHeader "x-amz-date", strNow
.send GetBytes(LocalFile) 'Get bytes of local file and send
If .status = 200 Then ' successful
Response.Write "<a href="& AWSBucketUrl & sRemoteFilePath &" target=_blank>Uploaded File</a>"
Else ' an error ocurred, consider xml string of error details
Response.ContentType = "text/xml"
Response.Write .responseText
End If
End With
Function GetBytes(sPath)
With Server.CreateObject("Adodb.Stream")
.Type = 1 ' adTypeBinary
.Open
.LoadFromFile sPath
.Position = 0
GetBytes = .Read
.Close
End With
End Function
Function BytesToBase64(varBytes)
With Server.CreateObject("MSXML2.DomDocument").CreateElement("b64")
.dataType = "bin.base64"
.nodeTypedValue = varBytes
BytesToBase64 = .Text
End With
End Function
Function HMACSHA1(varKey, varValue)
With Server.CreateObject("System.Security.Cryptography.HMACSHA1")
.Key = UTF8Bytes(varKey)
HMACSHA1 = .ComputeHash_2(UTF8Bytes(varValue))
End With
End Function
Function UTF8Bytes(varStr)
With Server.CreateObject("System.Text.UTF8Encoding")
UTF8Bytes = .GetBytes_4(varStr)
End With
End Function
%>
The Amazon Signature must be url encoded in a slightly different way to what VBSCript encodes. The following function will encode the result correctly:
JScript Version:
function amazonEncode(s)
{
return Server.UrlEncode(s).replace(/\+/g,"%20").replace(/\%2E/g,".").replace(/\%2D/g,"-").replace(/\%7E/g,"~").replace(/\%5F/g,"_");
}
VBScript Version:
function amazonEncode(s)
dim retval
retval = Server.UrlEncode(s)
retval = replace(retval,"+","%20")
retval = replace(retval,"%2E",".")
retval = replace(retval,"%2D","-")
retval = replace(retval,"%7E","~")
retval = replace(retval,"%5F","_")
amazonEncode = retval
end function
As for base64, I used .NET's already built functionality for it. I had to create a DLL to wrap it, so that I could use it from JScript (or VBScript).
Here's how to create that dll:
Download the free C# 2010 Express and install it.
You also need to use two other tools that you won’t have a path to, so you will need to add the path to your PATH environment variable, so at a cmd prompt search for regasm.exe, guidgen.exe and sn.exe (you might find several versions – select the one with the latest date).
• cd\
• dir/s regasm.exe
• dir/s sn.exe
• dir/s guidgen.exe
So as an example, a COM object that has just one method which just returns “Hello”:
Our eventual aim is to use it like this:
<%#Language=JScript%>
<%
var x = Server.CreateObject("blah.whatever");
Response.Write(x.someMethod());
%>
or
<%#Language=VBScript%>
<%
dim x
set x = Server.CreateObject("blah.whatever")
Response.Write x.someMethod()
%>
• Start C# and create a new project
• Select “Empty Project”
• Give it a name – this becomes the namespace by default (the blah in the sample above)
• Next save the project (so you know where to go for the next bit). This will create a folder structure like so:
o blah this contains your solution files that the editor needs (blah.sln etc)
 blah this contains your source code and project files
• bin
o Debug the compiled output ends up here
• Next, using the cmd console, navigate to the root blah folder and create a key pair file:
sn –k key.snk
• Next you need a unique guid (enter guidgen at the cmd prompt)
o Select registry format
o Click “New Guid”
o Click “Copy”
• Back to C# editor – from the menu, select Project – Add Class
• Give it a name – this is the whatever in the sample above
• After the opening brace just after the namespace line type:
[GuidAttribute(“paste your guid here”)]
remove the curly brackets from your pasted guid
• You will need to add another “using” at the top
using System.Runtime.InteropServices;
• Finally you need to create someMethod
The final C# code looks like this (the bits in red may be different in your version):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
namespace blah
{
[GuidAttribute("AEF4F27F-9E97-4189-9AD5-64386A1699A7")]
public class whatever
{
public string someMethod()
{
return "Hello";
}
}
}
• Next, from the menu, select Project – Properties
o On the left, select Application and, for the Output type dropdown, select “Class Library”
o On the left, select Signing and tick the “Sign the assembly” box, then browse to the key.snk file you made earlier
o Save the properties (CTRL-S)
• Next build the dll (Press F6) – This will create a dll in the Debug folder
• Open a cmd window as administrator (right click cmd.exe and select “Run as Administrator”)
• Navigate to the Debug folder and enter the following to register the assembly:
regasm blah.dll /tlb:blah.tlb /codebase blah
That’s it – the above is a genuine COM component and will work in other applications, the example below allows for event handling and only really works in ASP due to the default property mechanism of ASP:
The code for the base64 stuff would be:
// returns a base 64 encoded string that has been encrypted with SHA256
// parameters:
// s string to encrypt
// k key to use during encryption
public string getBase64SHA256(string s, string k)
{
HMACSHA256 sha = new HMACSHA256();
System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
sha.Key = encoding.GetBytes(k);
byte[] hashBytes = sha.ComputeHash(encoding.GetBytes(s));
return System.Convert.ToBase64String(hashBytes);
}
// returns a base 64 encoded string that has been encrypted with SHA1
// parameters:
// s string to encrypt
// k key to use during encryption
public string getBase64SHA1(string s, string k)
{
HMACSHA1 sha = new HMACSHA1();
System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
sha.Key = encoding.GetBytes(k);
byte[] hashBytes = sha.ComputeHash(encoding.GetBytes(s));
return System.Convert.ToBase64String(hashBytes);
}
You would need the relevant usings:
using System.Security.Cryptography;
The signature in full must have all the query string name-value pairs in alphabetical order before computing the SHA and base64. Here is my version of the signature creator function:
function buildAmazonSignature(host,req,qstring)
{
var str="", i, arr = String(qstring).split("&");
for (i=0; i<arr.length; i++)
arr[i] = arr[i].split("=");
arr.sort(amazonSortFunc);
for (i=0; i<arr.length; i++)
{
if (str != "")
str += "&";
str += arr[i][0] + "=" + arr[i][1];
}
str = "GET\n"+host+"\n"+req+"\n"+str;
var utils = Server.CreateObject("FMAG.Utils");
var b64 = utils.getBase64SHA256(str, "xxxxxxxxxx");
utils = null;
return amazonEncode(b64);
}
function amazonSortFunc(a,b)
{
return (a[0]<b[0])?-1:((a[0]>b[0])?1:0);
}
VBScript doesn't have a very good array sort facility, so you'll have to work that one out yourself - sorry
Also I have the timestamp in this format:
YYYY-MM-DDTHH:MM:SSZ
Also the stuff in the query string included the following:
AWSAccessKeyId
SignatureMethod
SignatureVersion
Version
Expires
Action
Hope that helps
Thank you so much for this question, it has been such a great help to start my WSH/VBScript for my S3 backup service ;-)
I do not have much time, so I will not go through the details of the things I have changed from Chris' code, but please find below my little prototype script which works perfectly ;-)
This is just a WSH/VBScript, so you do not need IIS to run it, you just need to paste the content in a file with the ".vbs" extension, and you can then directly execute it ;-)
Option Explicit
'-- Amazon Web Services > My Account > Access Credentials > Access Keys --'
Dim strAccessKeyID: strAccessKeyID = "..."
Dim strSecretAccessKey: strSecretAccessKey = "..."
'-- Parameters: --'
Dim strLocalFile: strLocalFile = "..."
Dim strRemoteFile: strRemoteFile = "..."
Dim strBucket: strBucket = "..."
'-- Authentication: --'
Dim strNowInGMT: strNowInGMT = NowInGMT()
Dim strStringToSign: strStringToSign = _
"PUT" & vbLf & _
"" & vbLf & _
"text/xml" & vbLf & _
strNowInGMT & vbLf & _
"/" & strBucket + "/" & strRemoteFile
Dim strSignature: strSignature = ConvertBytesToBase64(HMACSHA1(strSecretAccessKey, strStringToSign))
Dim strAuthorization: strAuthorization = "AWS " & strAccessKeyID & ":" & strSignature
'-- Upload: --'
Dim xhttp: Set xhttp = CreateObject("MSXML2.ServerXMLHTTP")
xhttp.open "PUT", "http://" & strBucket & ".s3.amazonaws.com/" & strRemoteFile, False
xhttp.setRequestHeader "Content-Type", "text/xml"
xhttp.setRequestHeader "Date", strNowInGMT 'Yes, this line is mandatory ;-) --'
xhttp.setRequestHeader "Authorization", strAuthorization
xhttp.send GetBytesFromFile(strLocalFile)
If xhttp.status = "200" Then
WScript.Echo "The file has been successfully uploaded ;-)"
Else
WScript.Echo "There was an error :-(" & vbCrLf & vbCrLf & _
xhttp.responseText
End If
Set xhttp = Nothing
'-- NowInGMT ------------------------------------------------------------------'
Function NowInGMT()
'This is probably not the best implementation, but it works ;-) --'
Dim sh: Set sh = WScript.CreateObject("WScript.Shell")
Dim iOffset: iOffset = sh.RegRead("HKLM\System\CurrentControlSet\Control\TimeZoneInformation\ActiveTimeBias")
Dim dtNowGMT: dtNowGMT = DateAdd("n", iOffset, Now())
Dim strDay: strDay = "NA"
Select Case Weekday(dtNowGMT)
Case 1 strDay = "Sun"
Case 2 strDay = "Mon"
Case 3 strDay = "Tue"
Case 4 strDay = "Wed"
Case 5 strDay = "Thu"
Case 6 strDay = "Fri"
Case 7 strDay = "Sat"
Case Else strDay = "Error"
End Select
Dim strMonth: strMonth = "NA"
Select Case Month(dtNowGMT)
Case 1 strMonth = "Jan"
Case 2 strMonth = "Feb"
Case 3 strMonth = "Mar"
Case 4 strMonth = "Apr"
Case 5 strMonth = "May"
Case 6 strMonth = "Jun"
Case 7 strMonth = "Jul"
Case 8 strMonth = "Aug"
Case 9 strMonth = "Sep"
Case 10 strMonth = "Oct"
Case 11 strMonth = "Nov"
Case 12 strMonth = "Dec"
Case Else strMonth = "Error"
End Select
Dim strHour: strHour = CStr(Hour(dtNowGMT))
If Len(strHour) = 1 Then strHour = "0" & strHour End If
Dim strMinute: strMinute = CStr(Minute(dtNowGMT))
If Len(strMinute) = 1 Then strMinute = "0" & strMinute End If
Dim strSecond: strSecond = CStr(Second(dtNowGMT))
If Len(strSecond) = 1 Then strSecond = "0" & strSecond End If
Dim strNowInGMT: strNowInGMT = _
strDay & _
", " & _
Day(dtNowGMT) & _
" " & _
strMonth & _
" " & _
Year(dtNowGMT) & _
" " & _
strHour & _
":" & _
strMinute & _
":" & _
strSecond & _
" +0000"
NowInGMT = strNowInGMT
End Function
'-- GetBytesFromString --------------------------------------------------------'
Function GetBytesFromString(strValue)
Dim stm: Set stm = CreateObject("ADODB.Stream")
stm.Open
stm.Type = 2
stm.Charset = "ascii"
stm.WriteText strValue
stm.Position = 0
stm.Type = 1
GetBytesFromString = stm.Read
Set stm = Nothing
End Function
'-- HMACSHA1 ------------------------------------------------------------------'
Function HMACSHA1(strKey, strValue)
Dim sha1: Set sha1 = CreateObject("System.Security.Cryptography.HMACSHA1")
sha1.key = GetBytesFromString(strKey)
HMACSHA1 = sha1.ComputeHash_2(GetBytesFromString(strValue))
Set sha1 = Nothing
End Function
'-- ConvertBytesToBase64 ------------------------------------------------------'
Function ConvertBytesToBase64(byteValue)
Dim dom: Set dom = CreateObject("MSXML2.DomDocument")
Dim elm: Set elm = dom.CreateElement("b64")
elm.dataType = "bin.base64"
elm.nodeTypedValue = byteValue
ConvertBytesToBase64 = elm.Text
Set elm = Nothing
Set dom = Nothing
End Function
'-- GetBytesFromFile ----------------------------------------------------------'
Function GetBytesFromFile(strFileName)
Dim stm: Set stm = CreateObject("ADODB.Stream")
stm.Type = 1 'adTypeBinary --'
stm.Open
stm.LoadFromFile strFileName
stm.Position = 0
GetBytesFromFile = stm.Read
stm.Close
Set stm = Nothing
End Function
Dear stone-edge-technology-VBScript-mates (*), let me know if it is working for you as well ;-)
(*) This is a reference to the comment from Spudley, see above ;-)

How to check is myMail.Send is true/false

<%
Dim sent
Dim YourName
Dim YourEmail
Dim YourMessage
Set myMail2=CreateObject("CDO.Message")
YourName = Trim(Request.Form("Name"))
YourEmail = Trim(Request.Form("Email"))
YourMessage = Trim(Request.Form("Message"))
Dim Body
Dim body2
Body = Body & "Their Name: " & VbCrLf & YourName & VbCrLf & VbCrLf
Body = Body & "Their Email: " & VbCrLf & YourEmail & VbCrLf & VbCrLf
Body = Body & "Their Message: " & VbCrLf & YourMessage & VbCrLf & VbCrLf
Set myMail=CreateObject("CDO.Message")
myMail.Subject="A New Enquiry!"
myMail.From="admin#musicalmatters.co.uk"
myMail.To="james#devine.eu"
myMail.TextBody=Body
myMail.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/sendusing")=2
'Name or IP of remote SMTP server
myMail.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/smtpserver")="smtp.1and1.com"
'Server port
myMail.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/smtpserverport")=25
myMail.Configuration.Fields.Update
myMail.Send
set myMail=nothing
body2="Thank you for contacting us!" & VbCrLf & "This is just a brief message to let you know your form was submitted successfully!"& VbCrLf & VbCrLf & "You may reply to this address, but you may not necessarily receive a reply, "& "you should receive a reply in 1-2 business day(s)!"& VbCrLf & "Thank you very much,"& VbCrLf & VbCrLf & "Musical Matters."& VbCrLf & "admin#musicalmatters.co.uk"
Set myMail2=CreateObject("CDO.Message")
myMail2.Subject="Thanks for Contacting Us!"
myMail2.From="admin#musicalmatters.co.uk"
myMail2.To=YourEmail
myMail2.TextBody=body2
myMail2.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/sendusing")=2
'Name or IP of remote SMTP server
myMail2.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/smtpserver")="smtp.1and1.com"
'Server port
myMail2.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/smtpserverport")=25
myMail2.Configuration.Fields.Update
myMail2.Send
If myMail2.Send="" Then
Response.Redirect("http://www.musicalmatters.co.uk/success.htm")
set myMail2=nothing
Else
Response.Redirect("http://www.musicalmatters.co.uk/error.htm")
set myMail2=nothing
End If
The problem with my asp script is that I need to check whether the emails were sent or not and redirect them to an error or success page depending on the result.
If myMail2.Send="" Then
Response.Redirect("http://www.musicalmatters.co.uk/success.htm")
set myMail2=nothing
Else
Response.Redirect("http://www.musicalmatters.co.uk/error.htm")
set myMail2=nothing
End If
in the code above mymail2.Send="" because i was testing something, i know i have to change the value to true or false, please be hasty with your answers!
Thanks in advance!
If the email address has valid syntax and the SMTP server is up and running, the Send method will never throw error, even if the email address does not exist.
There is no way to know 100% if the email reached its destination - one thing I can think is to check (using FSO) the BadMail and Queue folders in the SMTP root after few seconds from sending, and if they contain new entry it means something went wrong.
However as you're using external mail service, you'll have to contact them and ask for a way to get notified somehow when the delivery fails.
Seems to require using On Error statement.
On Error Resume Next
myMail2.Send
If Err.Number = 0 Then
set myMail2 = Nothing
Response.Redirect("http://www.musicalmatters.co.uk/success.htm")
Else
set myMail2 = Nothing
Response.Redirect("http://www.musicalmatters.co.uk/error.htm")
End If