How do I read all X Headers in asp.net - asp.net

I want to be able to identify a mobile device using some form of ID.
I read this answer: Get unique, static id from a device via web request about reading x headers in asp.net but when I list all the headers using the following code I don't get any useful x headers
For Each var As String In Request.ServerVariables
Response.Write("<b>" & var & "</b>: " & Request(var) & "<br>")
Next
On my andoid device the only X header I get is HTTP_X_WAP_PROFILE

If you want to read HTTP headers you are going about it the wrong way. ServerVariables only holds some information from the headers.
You should be looking at the Request.Headers property. The following code will list all headers from the HTTP Request. Presumable the "x" headers you refer to will be there..
For Each headerName As String In Request.Headers.AllKeys
Response.Write("<b>" & headerName & "</b>: " & Request.Headers(headerName) & "<br>")
Next

To read the header values you can use the code below.
I thin by using user-agent from which you can get an idea about the browser.
C#
var headers = Request.Headers.ToString();
// If you want it formated in some other way.
var headers = String.Empty;
foreach (var key in Request.Headers.AllKeys)
headers += key + "=" + Request.Headers[key] + Environment.NewLine;
VB.NET:
Dim headers = Request.Headers.ToString()
' If you want it formated in some other way.'
Dim headers As String = String.Empty
For Each key In Request.Headers.AllKeys
headers &= key & "=" & Request.Headers(key) & Environment.NewLine
Next
From Detecting mobile device user agents in ASP.NET (Android):
//for Mobile device
protected override void OnInit(EventArgs e)
{
string userAgent = Request.UserAgent;
if (userAgent.Contains("BlackBerry")
|| (userAgent.Contains("iPhone") || (userAgent.Contains("Android"))))
{
//add css ref to header from code behind
HtmlLink css = new HtmlLink();
css.Href = ResolveClientUrl("~/mobile.css");
css.Attributes["rel"] = "stylesheet";
css.Attributes["type"] = "text/css";
css.Attributes["media"] = "all";
Page.Header.Controls.Add(css);
}
}

Related

how to send an email using SendGrid V3 to multiple recipients, in a .NET app

It sends to one ok. But not to 2 or more. I've tried separating addresses by , and ; and space in the to_addr string, but failed.
What format does class EmailAddress expect for multiple addresses?
public async sub send_message( msg_subject, msg_body, from_addr_text, to_addr_text, optional commands = "")
dim apiKey = Environment.GetEnvironmentVariable("SENDGRID_API_KEY")
dim client as new SendGridClient( apiKey, , , "v3", )
dim from = new EmailAddress( from_addr_text, "INSTRUMENT")
dim subject = msg_subject
if subject = ""
subject = " " ' won't send if empty
End If
dim to_addr = new EmailAddress( to_addr_text, "INSTRUMENT")
dim plainTextContent = msg_body
dim htmlContent = "<strong>" & msg_body & "</strong>"
dim msg = MailHelper.CreateSingleEmail(from, to_addr, subject, plainTextContent, htmlContent)
dim response = await client.SendEmailAsync(msg)
if instr( commands, "SKIP POPUPS") ' TEST TEXT MSG !!!
exit sub
End If
popup_information( "MESSAGE SENDING", "Sent..." & vbcrlf & vbcrlf & "SUBJECT: " & vbcrlf & subject & vbcrlf & vbcrlf & "BODY: " & vbcrlf & msg_body )
end sub
Not sure which SDK version are you using , but if you follow the Sendgrid V3 api SDK for C# , you should find a method like below in the MailHelper class
public static SendGridMessage CreateSingleEmailToMultipleRecipients(EmailAddress from, List<EmailAddress> tos, string subject,string plainTextContent,string htmlContent)
which accepts a List<EmailAddress> to send email to multiple recipients. So instead of using the below line in your code
dim msg = MailHelper.CreateSingleEmail(from, to_addr, subject, plainTextContent, htmlContent)
you should use the below code
var to_addr = new List<EmailAddress>();
to_addr.Add(new EmailAddress( to_addr_text, "INSTRUMENT"));
to_addr.Add(new EmailAddress( "secondperson#test.com", "secondperson")); // you can add multiple email in this list
and then you can use to_addr in the code below
dim msg = MailHelper.CreateSingleEmailToMultipleRecipients(from, to_addr, subject, plainTextContent, htmlContent)
Pardon me for the example in C# but the same should be applicable for your VB.NET code
The stack overflow answer here shows how to implement SendGrid using dependency injection into a Net 6 Web API application using controllers.
The scenario of sending an email to multiple recipients is covered in the referenced example code here: https://github.com/Davidmendoza1987/dotnet-sendgrid-examples

Saving the current running aspx page

I have an aspx page with a table that runs at server. I wrote a code to insert a row in the table, as the code bellow shows. I want to save the now updated aspx page (i.e overwriting the current if possible) so that the next time I visit the page, all information shows. I don't want to use a database to store this information because this is only temporary and my hosting package does not support a database. Please help.
Below is my code:
Dim trow As New HtmlTableRow
Dim tcell As New HtmlTableCell
tcell.InnerText = "Code: " & TextBox1.Text & ". Weight: " & TextBox2.Text & ". Date: " & Now
trow.Cells.Add(tcell)
trow.Cells.Add(tcell)
Table.Rows.Add(trow)
TextBox1.Text = ""
TextBox2.Text = ""
'Save the aspx page
Me.SaveControlState()
Me.SaveViewState()
You can save the data in cookies. Try this.
Writing a cookie.
HttpCookie myCookie = new HttpCookie("MyTestCookie");
DateTime now = DateTime.Now;
// Set the cookie value.
myCookie.Value = now.ToString();
// Set the cookie expiration date.
myCookie.Expires = now.AddYears(50); // For a cookie to effectively never expire
// Add the cookie.
Response.Cookies.Add(myCookie);
Response.Write("<p> The cookie has been written.");
Reading a cookie
HttpCookie myCookie = new HttpCookie("MyTestCookie");
myCookie = Request.Cookies["MyTestCookie"];
// Read the cookie information and display it.
if (myCookie != null)
Response.Write("<p>"+ myCookie.Name + "<p>"+ myCookie.Value);
else
Response.Write("not found");
Use session:
to access a value:
System.Web.HttpContext.Current.Session(“MyVariable”).ToString()
to set a value:
System.Web.HttpContext.Current.Session(“MyVariable”) = “NewValue”

Save Base64 to an image using Classic ASP

I have been trying to save a base64 file as an image from server side using classic ASP. What I want is it to autosave the file to a specific location and give it a filename, Now I am fine coding that aspect of it. However I can't get the code to save the image without first rendering on a browser. This isn't going to work for me as the script I am using will be an automatic export and have no user input.
Code follows as yet that renders in the webpage and asks the user where to save the image. Just to reiterate I need it to auto save (no user input)
base64String ="base64 code goes here - Wont add it as its huge amount of text"
Set tmpDoc = Server.CreateObject("MSXML2.DomDocument")
Set nodeB64 = tmpDoc.CreateElement("b64")
nodeB64.DataType = "bin.base64" ' stores binary as base64 string
nodeB64.Text = Mid(base64String, InStr(base64String, ",") + 1) ' append data text (all data after the comma)
vehicleAuditName= "Audit1"
With Response
.Clear
.ContentType = "image/png"
.AddHeader "Content-Disposition", "attachment; filename=" & vehicleAuditName & ".png"
.BinaryWrite nodeB64.NodeTypedValue 'get bytes and write
.end
End With
use an adodb.stream object to store the image on the server side like so:
dim bStream : set bStream = server.CreateObject("ADODB.stream")
bStream.type = adTypeBinary
call bStream.Open()
call bStream.Write( binData )
call bStream.SaveToFile( FullName, adSaveCreateOverWrite)
call bStream.close()
set bStream = nothing
The server side code that receives the base64 string is below, please note that this is code that is taken from a working system so there are variables such as carreg / auditdate that are used as unique identifiers for giving the created file a name:
function convBase64 (convVal, getCarReg, convType, AuditDate, AuditReference)
base64String = convVal
carReg = (UCase(getCarReg))
carReg = (Replace(getCarReg," ",""))
AuditDate= CDate(AuditDate)
ConvAuditDate = ((DatePart("d",AuditDate))& "_" & (DatePart("m",AuditDate)) & "_" & (DatePart("YYYY",AuditDate)))
select case convType
Case "Sig1"
FileNameSuffix = "AuditorsSignature"
Case "Sig2"
FileNameSuffix = "BodyShopSignature"
Case "Car"
FileNameSuffix = "DamageCanvas"
end select
ImageFileName = FileNameSuffix & "-" & carReg & "-" & ConvAuditDate & ".jpg"
Set tmpDoc = Server.CreateObject("MSXML2.DomDocument")
Set nodeB64 = tmpDoc.CreateElement("b64")
nodeB64.DataType = "bin.base64" ' stores binary as base64 string
nodeB64.Text = Mid(base64String, InStr(base64String, ",") + 1) ' append data text (all data after the comma)
dim bStream : set bStream = server.CreateObject("ADODB.stream")
bStream.type = 1
call bStream.Open()
call bStream.Write( nodeB64.NodeTypedValue )
call bStream.SaveToFile(Server.Mappath("NoneVehicleImages/" & AuditReference & "/" & ImageFileName), 2 )
call bStream.close()
set bStream = nothing
convBase64 = "\\iis_fdg$\AuditExport\NoneVehicleImages\" & AuditReference & "\" & ImageFileName
end function
You cannot do this due to security reasons. If web pages could randomly choose where to store files on our local systems without any user interaction, there would chaos.

Export to word with a filename doesn't seem to work

I export a datatable to word, when I pass a file name it doesn't seem to get the file name in Open/Save dialog box.
Here is what I am doing
public static void Convertword(DataTable dt, HttpResponse Response,string filename)
{
try
{
Response.Clear();
Response.AddHeader("content-disposition", "attachment;filename=" + filename + ".doc");
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/vnd.word";
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new System.Web.UI.HtmlTextWriter(stringWrite);
System.Web.UI.WebControls.GridView dg = new System.Web.UI.WebControls.GridView();
dg.DataSource = dt;
dg.DataBind();
dg.RenderControl(htmlWrite);
Response.Write(stringWrite.ToString());
Response.End();
}
catch(Exception err)
{
throw err;
}
}
When I pass filename "report(" + System.DateTime.Now.ToString("dd/MM/yyyy");
+ ")" it doesn't take the value as dd/MM/YYYY instead it shows file name as dd_MM_YYYY
Few remarks about your code:
You are setting the content type header to a word document but you are actually sending HTML contents by rendering a GridView
dd/MM/YYYY is not a valid filename because of the / character.
You don't need a try/catch block if in the catch statement you are only doing throw err
Calling Response.End at the end is not necessary.
Always use using statement when dealing with disposable objects such as streams and readers/writers to ensure that the Dispose method is invoked in all cases.
You should to use a filename like
String.Format("report{0:ddMMyyyy}.doc", DateTime.Now);
A filename cannot have "/".
That's most likely because / isn't a valid character for filenames. Your name must fulfill certain criteria, be sure not to use any of
* . " / \ [ ] : ; | = ,
If you have forward slashes in the filename, I would assume that this would break the URL to the file and hence the slashes are being replaced at some point?

ATT00006.dat file autmatically attached in mail attachment

I have a page that have fileupload control, on the submission of the form, when the fileupload control has file, file is sent via attachment in a mail and working absulutly fine, but when the fileupload control does not have file, ATT00006.dat file is automatically sent via email attachment.
Reference URL: http://nextech.pk/Enquiry.aspx?Enq=cu
Advance Thanks for any help
Edit -- Code:
hpf = fup1.PostedFile;
String toEmail = "test#hotmail.com";
String fromEmail = "mailer#hotmail.com";
MailMessage objMail = new MailMessage(fromEmail, toEmail);
objMail.IsBodyHtml = true;
StringBuilder MailBody = new StringBuilder();
MailBody.Append("<html><head></head><body> <br>");
MailBody.Append("<br>" + "An enquiry is filed <br><br>");
MailBody.Append("<strong><u>Enquirer Information</u></strong>" + "<br><br>");
MailBody.Append("<strong>Contact Name:</strong> " + txtFirstName.Text + "<br>");
MailBody.Append("<strong>Email:</strong> " + txtEmail.Text + "<br>");
MailBody.Append("<strong>Institute:</strong> " + txtInstitute.Text + "<br>");
MailBody.Append("<strong>Phone #:</strong> " + txtPhone.Text + "<br>");
MailBody.Append("<br><strong>Description:</strong><br>         " + txtEnquiry.Text + "<br>");
if (hpf != null)
{
MailBody.Append("<br>" + "This email also contains an attachment:- <Strong>(" + hpf.FileName + ")</Strong><br>");
}
MailBody.Append("</body></html>");
objMail.Body = MailBody.ToString();
if (hpf != null)
{
System.IO.Stream inputStream = hpf.InputStream;
String fileName = hpf.FileName;
Attachment attach = new Attachment(inputStream, fileName);
objMail.Attachments.Add(attach);
}
SmtpClient SmtpClnt = new SmtpClient();
SmtpClnt.Send(objMail);
I don't know if you ever got an answer to this, but I've recently studied the problem in detail. The problem occurs because you did not provide an explicit name for the attachment. ASP.NET will always attach as .DAT unless the name is explicitly defined.
The problem is that people assume ASP.NET will use the Filename as the attachment name, which doesn't happen!
In your code, you should create an instance of the attachment, then provide the name explicitly using the FileUpload.FileName property:
Dim att As New System.Net.Mail.Attachment(fu.PostedFile.InputStream, System.Net.Mime.MediaTypeNames.Application.Octet) ' use Octet for binary files '
att.Name = fu.FileName ' get the file name and type automatically '
mm.Attachments.Add(att)
A full explanation of ASP.NET attaching .DAT files is available here
Its a mis-match in the attachment type that the system doesn't understand. Please post your code and what you do when there is not file as an attachment.
I think the mail server you are using (or antivirus software used by the mail server) is automatically adding this file.
Does the file in question contain anything, or is it empty?

Resources