Email ASP.NET webpage with Chart Controls - asp.net

I have an asp.net 4.0 webpage which has 10 chart controls on it. I have been to email the chart controls to the current logged in user when they open the page. The chart controls will be different for each user. I have been testing this by trying to send 1 chart control but the body of the email doesnt show the chart only the image outline. I have tried several things but cant get it to work. The code i have just now is -
web.config
<add key="ChartImageHandler" value="storage=memory;deleteAfterServicing=true;"/>
webpage
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
SendMail()
End Sub
Private Sub SendMail()
Dim SB As New StringBuilder()
Dim SW As New StringWriter(SB)
Dim htmlTW As New HtmlTextWriter(SW)
'SB.Append("<td><img src=""cid:chart17""></td>")
Chart10.RenderControl(htmlTW)
Dim MyHTML As String = SB.ToString()
Dim from As String = "EMAIL ADDRESS"
Dim recip As String = "EMAIL ADDRESS"
'Dim recip As String = Membership.GetUser.Email.ToString
Dim subject As String = "Test Email"
'Create message object and populate w/ data from form
Dim message As System.Net.Mail.MailMessage = New System.Net.Mail.MailMessage()
message.From = New System.Net.Mail.MailAddress(from.Trim())
message.To.Add(recip.Trim())
message.Subject = subject.Trim()
message.IsBodyHtml = True
message.Body = MyHTML
'Setup SmtpClient to send email. Uses web.config settings.
Dim smtpClient As System.Net.Mail.SmtpClient = New System.Net.Mail.SmtpClient()
'Error handling for sending message
Try
smtpClient.Send(message)
'Exception contains information on each failed receipient
Catch recExc As System.Net.Mail.SmtpFailedRecipientsException
For recipient = 0 To recExc.InnerExceptions.Length - 1
Dim statusCode As System.Net.Mail.SmtpStatusCode
'Each InnerException is an System.Net.Mail.SmtpFailed RecipientException
statusCode = recExc.InnerExceptions(recipient).StatusCode
If (statusCode = Net.Mail.SmtpStatusCode.MailboxBusy) Or (statusCode = Net.Mail.SmtpStatusCode.MailboxUnavailable) Then
'Log this to event log: recExc.InnerExceptions(recipient).FailedRecipient
System.Threading.Thread.Sleep(5000)
smtpClient.Send(message)
Else
'Log error to event log.
'recExc.InnerExceptions(recipient).StatusCode or use statusCode
End If
Next
'General SMTP execptions
Catch smtpExc As System.Net.Mail.SmtpException
'Log error to event log using StatusCode information in
'smtpExc.StatusCode
Catch ex As Exception
'Log error to event log.
End Try
End Sub
As you can see i have tried some examples on forums like "SB.Append" and "chart10.rendercontrol(htmlTW) but both do not work for me.
Any helpo would be greatful.

You are not attaching the image to the e-mail.
''I am not sure how to handle memory streams in vb but it should be something like so.
Dim ms as MemoryStream = new MemoryStream()
Chart10.SaveImage(ms, ChartImageFormat.Png)
Dim A As System.Net.Mail.Attachment = New System.Net.Mail.Attachment(ms, "MyChart.png")
A.ContentId = "chart17"
A.ContentDisposition.Inline = True
message.Attachments.Add(A)

Related

Needs to retrieve data first and then update the new entry into DB

I need to retrieve data from the database first and then update the table with the new entry, following is my code but I am having an error:
"Invalid attempt to call Read when reader is closed."
I know I need to open the datareader by commenting dr1.close, but as soon as I did that I face an another exception:
"there is already an open datareader associated with this command which must be closed first. vb.net"
Imports System.IO
Imports System.Data.Sql
Imports System.Data.SqlClient
Imports System.Data
Partial Class Officer_Module_GST_id_password
Inherits System.Web.UI.Page
Dim sscript As String
Dim sms As New smsgw
Dim mail As New MailSender
Dim cmd As New SqlCommand
Dim ds As New DataSet
Dim dr As SqlDataReader
Dim objconn As New connectioncls
Dim name As String
Dim pid As String
Dim pwd As String
Dim email_sent As Integer
Dim email_status As String
Dim mobile As String
Dim message As String
Dim subject As String
Dim email As String
Dim mtext As String
Protected Sub validatedeal_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles validatedeal.Click
containertwo.Visible = True
txt_subject.Text = "Communication of the Provisional Identification Number and Password"
txt_mail.Text = "Instance mail"
End Sub
Protected Sub btnsendmail_Click(ByVal sender As Object, ByVal e As System.EventArgs)
objconn.openconn()
cmd.Connection = objconn.conn
cmd.CommandText = "Select Trade_name,provissional_id,access_token,reg_mobile_no,reg_email_id,email_status,isnull(no_of_email_sent,0) from Provisional_details"
Dim dr1 As SqlDataReader = cmd.ExecuteReader()
While (dr1.Read())
name = dr1(0).ToString()
pid = dr1(1).ToString()
pwd = dr1(2).ToString()
mobile = dr1(3).ToString()
email = dr1(4).ToString()
email_status = dr1(5).ToString()
email_sent = dr1(6).ToString()
subject = "subject to instance"
mtext = "new instance email"
message = "new instance message"
Try
MailSender.SendEmail("riteshbhatt93" + "#gmail.com", "rock_on", email, subject, mtext, System.Web.Mail.MailFormat.Text, "")
Try
Call sms.SendSMSUsingNICGW(mobile, message)
Catch
sscript = "<script language=javascript>alert('Message not sent!!')</script>"
Page.ClientScript.RegisterStartupScript(Me.GetType(), "Empty", sscript)
sscript = Nothing
Exit Try
Finally
End Try
Try
Call sms.SendSMSUsingMGOVGW(mobile, message)
Catch
sscript = "<script language=javascript>alert('Message not sent!!')</script>"
Page.ClientScript.RegisterStartupScript(Me.GetType(), "Empty", sscript)
sscript = Nothing
Exit Try
Finally
End Try
Catch
Dim cmd1 As New SqlCommand
cmd1.Connection = objconn.conn
cmd1.Parameters.AddWithValue("#mobile", mobile)
cmd1.Parameters.AddWithValue("#Email_status", "NO")
cmd1.CommandText = "Update Provisional_details set Email_sent = #Email_status where reg_mob_no = #mobile"
cmd1.ExecuteNonQuery()
cmd1.Parameters.Clear()
Exit Sub
Finally
End Try
dr1.Close()
Dim cmd2 As New SqlCommand
cmd2.Connection = objconn.conn
cmd2.Parameters.AddWithValue("#mobile", mobile)
cmd2.Parameters.AddWithValue("#Email_status", "YES")
cmd2.Parameters.AddWithValue("#emailsent", email_sent + 1)
cmd2.CommandText = "Update Provisional_details set email_status = #Email_status,no_of_email_sent = #emailsent where reg_mobile_no = #mobile"
cmd2.ExecuteNonQuery()
cmd2.Parameters.Clear()
End While
sscript = "<script language=javascript>alert('Your Mail has been sent to all applied dealers!!')</script>"
Page.ClientScript.RegisterStartupScript(Me.GetType(), "Empty", sscript)
sscript = Nothing
End Sub
End Class
I've pared this down to just the method that matters (like you should have done when posting the question). Updates are in the method, using comments to annotate what's going on.
Protected Sub btnsendmail_Click(ByVal sender As Object, ByVal e As System.EventArgs)
'Best practice in .Net is use a brand new connection instance for most DB calls. Really.
'Don't try to be clever and re-use one connection. Just use the same string.
Dim connString As String = "Connection String Here"
'Using block will guarantee connection closes properly, even if an exception is thrown
Using cn As New SqlConnection(connString), _
cmd As New SqlCommand("Select Trade_name,provissional_id,access_token,reg_mobile_no,reg_email_id,email_status,isnull(no_of_email_sent,0) from Provisional_details", cn), _
cn2 As New SqlConnection(connString), _
cmd2 As New SqlCommand("Update Provisional_details set email_status = #Email_status,no_of_email_sent = #emailsent where reg_mobile_no = #mobile", cn2)
'Define your parameters as early as possible, and be explicit about parameter types and lengths
' This will avoid potentially crippling performance gotchas
cmd2.Parameters.Add("#mobile", SqlDbType.NVarChar, 14)
cmd2.Parameters.Add("#Email_status", SqlDbType.VarChar, 5)
cmd2.Parameters.Add("#emailsent", SqlDbType.Int)
'Separate SQL statements in a tight loop like this is one of the few places to re-use a connection object...
' Even here, it should be a BIG RED FLAG that there's a better way to handle this whole process that avoids multiple calls to the DB.
' For example, it might be better to assume success, Update the DB accordingly in the original statement, and then only write failures back when needed
cn2.Open()
cn.Open()
dr1 As SqlDataReader = cmd.ExecuteReader()
While (dr1.Read())
'Best practice in .Net are to declare these variables in the method where you use them
Dim name As String = dr1(0).ToString()
Dim pid As String = dr1(1).ToString()
Dim pwd As String = dr1(2).ToString() 'You're not really storing passwords in plain-text are you? Please say, "No".
Dim mobile As String = dr1(3).ToString()
Dim email As String = dr1(4).ToString()
Dim email_status As String = dr1(5).ToString()
Dim email_sent As Integer = dr1.GetInt32(6) 'It's a number. You do math on it later. Get the INTEGER value
Dim subject As String = "subject to instance"
Dim mtext As String = "new instance email"
Dim message As String = "new instance message"
cmd2.Parameters("#mobile").Value = mobile
Try
MailSender.SendEmail("riteshbhatt93" + "#gmail.com", "rock_on", email, subject, mtext, System.Web.Mail.MailFormat.Text, "")
Try
' Also... the "Call" keyword is a vb6-era relic that has no purpose any more. Don't use it
sms.SendSMSUsingMGOVGW(mobile, message)
Catch
Page.ClientScript.RegisterStartupScript(Me.GetType(), "Empty", "<script language=javascript>alert('Message not sent!!')</script>")
'Don't set values to "Nothing" to free them in VB.Net.
'It doesn't help the way it used to in vb6/vbscript, and can actually be HARMFUL in rare cases in .Net
End Try
' Do you really mean to try both gateways, even if the first succeeds?
' Because that's what the original code is doing.
Try
sms.SendSMSUsingNICGW(mobile, message)
Catch
Page.ClientScript.RegisterStartupScript(Me.GetType(), "Empty", "<script language=javascript>alert('Message not sent!!')</script>")
'No need to call Exit Try here,
' and no need for an empty Finally section
End Try
Catch
cmd2.Parameters("#emailsent") = email_sent
cmd2.Parameters("#Email_status") = "NO"
cmd2.ExecuteNonQuery()
End Try
cmd2.Parameters("#Email_status").Value = "YES"
cmd2.Parameters("#emailsent").Value = email_sent + 1
cmd2.ExecuteNonQuery()
End While
End Using
End Sub

parameters not passing to ssrs ServerReport - rendering report to pdf using ServerReport.Render

My code that sets up a ServerReport object on a web forms page, and then renders the report from SSRS to a pdf. Parameter and report name is passed by URL.
Private Sub Page_Load(sender As Object, e As EventArgs)
Dim reportname As String
'Dim parameter(0) As ReportParameter
reportname = Request("reportname").ToString
Dim v As New ReportViewer
v.ProcessingMode = ProcessingMode.Remote
Dim serverreport As New ServerReport
serverreport = v.ServerReport
serverreport.ReportServerUrl = New Uri("http://xxxxxx:80/ReportServer")
serverreport.ReportPath = "/Reports/Aramid/Sheeter/" & reportname
Select Case reportname
Case Is = "NomexBlockCard" 'Or "NomexBlockLabel" Or "NomexInternalLabel"
Dim paramList As New Generic.List(Of ReportParameter)
paramList.Add(New ReportParameter("paramBlock", Request("paramBlock").ToString, False))
serverreport.SetParameters(paramList)
Case Is = "NomexRoutingData"
Dim paramList As New Generic.List(Of ReportParameter)
paramList.Add(New ReportParameter("paramWO", Request("paramWO").ToString, False))
serverreport.SetParameters(paramList)
End Select
serverreport.ReportServerCredentials = New ReportViewerCredentials(user name here, password here, "CORE")
Save(serverreport, "C:\WebReports\" & reportname & ".pdf")
'now print
Response.Redirect("reports.ashx?fileName=" & reportname)
End Sub
Public Sub Save(ByVal sr As ServerReport, ByVal savePath As String)
Try
Dim warnings As Warning() = Nothing
Dim streamids As String() = Nothing
Dim mimeType As String = Nothing
Dim encoding As String = Nothing
Dim extension As String = Nothing
Dim deviceInfo As String
Dim bytes As Byte()
deviceInfo = "True" '<DeviceInfo><SimplePageHeaders>True</SimplePageHeaders></DeviceInfo>"
bytes = sr.Render("PDF", Nothing, mimeType, _
encoding, extension, streamids, warnings)
Using Stream As New FileStream(savePath, FileMode.Create)
Stream.Write(Bytes, 0, Bytes.Length)
Stream.Close()
End Using
Catch ex As Exception
End Try
End Sub
The report renders and saves as a pdf but the parameter value does not seem to be getting used in the report.
I have confirmed over and over that there is a value in paramBlock.
I don't know what I am doing wrong.
Am I missing a step or something?
Ryan
As your report is being rendered and saved, I'm assuming the credentials are set up correctly.
You can use the ServerReport.GetParameters function before saving the report to check what the parameters (and their values/properties) actually are.
Also, make sure you're setting every parameter required by the report (even those hidden or internal), and that every parameter value is within the allowed values of the parameter (if limits are set).
If the problem doesn't lie in passing the parameters, you might want to take a look at the report itself and how it handles its parameters.
From your recent comment about a "Parameter validation failed" error, it sounds like your issue is not with your calling code structure, but rather matching the parameters to the report definition.
The most common issue is hidden or internal parameters which you are ignoring. You need to carefully review the parameter design in SSRS Report Designer, and make sure your passed parameters comply with what it expects.
Consider following suggestions. It might help you to resolve your issue. After considering every point, you can try your code
Place following code just above the Select Case reportname statement line
serverreport.ReportServerCredentials = New ReportViewerCredentials(user name here, password here, "CORE")
You can also try changing code line
serverreport.ReportServerCredentials = New ReportViewerCredentials(user name here, password here, "CORE")
To
ServerReport.ReportServerCredentials.NetworkCredentials = System.Net.CredentialCache.DefaultCredentials
If your report has default parameters, then remove default parameters and test your code
And also remove exception handling from your method
Public Sub Save(ByVal sr As ServerReport, ByVal savePath As String)
You can try following code:
Private Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
Dim reportname As String = Request("reportname").ToString
'Dim parameter(0) As ReportParameter
Dim v As New ReportViewer
v.ProcessingMode = ProcessingMode.Remote
Dim ServerReport As ServerReport
ServerReport = v.ServerReport
serverreport.ReportServerUrl = New Uri("http://xxxxxx:80/ReportServer")
serverreport.ReportPath = "/Reports/Aramid/Sheeter/" & reportname
ServerReport.ReportServerCredentials.NetworkCredentials = System.Net.CredentialCache.DefaultCredentials
Select Case reportname
Case Is = "NomexBlockCard" 'Or "NomexBlockLabel" Or "NomexInternalLabel"
Dim paramList As New Generic.List(Of ReportParameter)
paramList.Add(New ReportParameter("paramBlock", Request("paramBlock").ToString, False))
serverreport.SetParameters(paramList)
Case Is = "NomexRoutingData"
Dim paramList As New Generic.List(Of ReportParameter)
paramList.Add(New ReportParameter("paramWO", Request("paramWO").ToString, False))
serverreport.SetParameters(paramList)
End Select
Save(serverreport, "C:\WebReports\" & reportname & ".pdf")
End Sub
Public Sub Save(ByRef sr As ServerReport, ByVal savePath As String)
Try
Dim warnings As Warning() = Nothing
Dim streamids As String() = Nothing
Dim mimeType As String = Nothing
Dim encoding As String = Nothing
Dim extension As String = Nothing
Dim deviceInfo As String
Dim bytes As Byte()
deviceInfo = "True" '<DeviceInfo><SimplePageHeaders>True</SimplePageHeaders></DeviceInfo>"
bytes = sr.Render("PDF", Nothing, mimeType, _
encoding, extension, streamids, warnings)
Using Stream As New FileStream(savePath, FileMode.Create)
Stream.Write(bytes, 0, bytes.Length)
Stream.Close()
End Using
Catch ex As Exception
End Try
End Sub
Maybe this is not the case, but I remember that Parameters value can be lost during PostBack.
So I would try a syntax like this:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Me.Page.IsPostBack Then
'your code to setup and print report
End If
End Sub
If this solution doesn't work please provide the code used in Report Definition.

Login page not working in vb asp.net

I am having an issue with my login page. I am not getting any errors so am not able to know where the problem is?
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Login.Click
'connection string
Dim mysqlconn As MySqlConnection = New MySqlConnection("server=localhost;user id=root;Password=123;database=users;persist security info=False")
Dim cmd As New MySqlCommand
Dim da As New MySqlDataAdapter
Dim mydata As New DataTable
Dim reader As MySqlDataReader
Try
mysqlconn.Open()
Dim query As String
query = "SELECT * FROM login_form where Username = '" & rfvUser.Text & "' and Password='" & rfvPWD.Text & "'"
cmd = New MySqlCommand(query, mysqlconn)
reader = cmd.ExecuteReader
While reader.Read()
If rfvUser.Text = "admin" And rfvPWD.Text = "admin" Then
Me.Session("User") = Me.rfvUser.Text
Server.Transfer("Admin.aspx")
ElseIf (rfvUser.Text = reader("UserName").ToString()) And (rfvPWD.Text = reader("Password").ToString()) Then
Me.Session("User") = Me.rfvUser.Text
Server.Transfer("Ersal_send.aspx")
Else
ClientScript.RegisterStartupScript(Page.[GetType](), "validation", "<script language='javascript'>alert('Invalid Username or Password')</script>")
reader.Close()
End If
End While
Catch ex As Exception
MsgBox(ex.Message)
Finally
mysqlconn.Dispose()
End Try
End Sub
End Class
Have you tried running the query directly via a SQL client? If your query is not returning any rows, then your procedure will simply exit without any errors as it will never enter the While loop.
Another advice: It is never a good idea to pass user input directly into a query. This leads to SQL injection. Use parameterised queries. Google for it.

Format of the initialization string does not conform to specification starting at index 0 Error

I'm writing a simple update-password page (studying purposes). The page consist of two text-box controls that will allow the user to enter their new password, followed by confirming their password by entering it into the second text-box control and finally clicking the submit bottom to update their password in the table stored in a database. My problem is that I receive the following error upon button-click: Format of the initialization string does not conform to specification starting at index 0 Error.
This is the code in behind he button:
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
If TextBox2.Text = TextBox3.Text Then
Dim myConnectionString As String
myConnectionString = "myDbIIConnectionString1"
Dim myConnection As New SqlConnection(myConnectionString)
myConnection.Open()
Dim mySQLQuery As String
mySQLQuery = "UPDATE myTb SET password VALUES (#password)"
Dim myCommand As New SqlCommand(mySQLQuery, myConnection)
myCommand.Parameters.AddWithValue("#password", TextBox3.Text)
myCommand.Connection = myConnection
myCommand.ExecuteNonQuery()
myCommand = Nothing
myConnection.Close()
myConnection = Nothing
Label2.Text = "Your Password has been changed"
Else
Label2.Text = "Retype your Password"
End If
Response.Redirect("login.aspx")
End Sub
Could someone assist me as to what I'm missing here? Thank You
There is problem in your update query . Correct it as :
mySQLQuery = "UPDATE myTb SET password=#password"
I figured it out; I should have been using configurationmanager.connectionstrings["the name goes here"]. to access my connection string.

WebException was caught When Consuming RSS Feed on ASP.net

I want to consume my blog's RSS feed from other asp.net site. I can't get rss data. I try different methods (like HttpWebRequest) for consuming RSS feed but I always get same error.
WebException was caught.
The underlying connection was closed: An unexpected error occurred during an import operation.
What was the problem ?
feed address: http://blog.melihmucuk.com/feed/
I need post title, link and posted date.
for example :
Try
Dim reader As XmlTextReader = New XmlTextReader("http://blog.melihmucuk.com/feed/")
Dim ds As DataSet = New DataSet()
ds.ReadXml(reader) // incorrect line
Catch ex As Exception
End Try
I think, that's a simple task, but I don't know what is the problem.
Also I try this:
Try
Dim title As String
Dim link As String
Dim description As String
Dim reader = XmlReader.Create("http://blog.melihmucuk.com/feed/")//incorrect line
Dim feed = SyndicationFeed.Load(reader)
For Each item In feed.Items
title = item.Title.Text
link = item.Links(0).Uri.ToString
Next
HyperLink1.Text = title
HyperLink1.NavigateUrl = link
Label1.Text = description
Catch ex As Exception
End Try
Try this out:-
Imports System.Web
Imports System.Net
Imports System.IO
Public Class Reader
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Try
Dim rssFeed = New Uri("http://blog.melihmucuk.com/feed/")
Dim request As WebRequest = WebRequest.Create(rssFeed)
Dim response As WebResponse = request.GetResponse()
Using reader As New StreamReader(response.GetResponseStream())
Dim xdoc As XDocument = New XDocument()
xdoc = XDocument.Load(reader)
'Read the nodes and display as per your requirement.
End Using
Catch ex As Exception
End Try
End Sub
End Class
Also add this block in your web.config file:-
<configuration>
<system.net>
<defaultProxy useDefaultCredentials="true">
<proxy usesystemdefault="true"/>
</defaultProxy>
</system.net>
</configuration>

Resources