Downloading html as string - asp.net

I am trying to download a webpage as string. Can someone please explain why the following code doesn't work?
Dim URL As String = "http://stackoverflow.com/"
Dim client As WebClient = New WebClient()
Dim data As Stream = client.OpenRead(URL)
Dim reader As StreamReader = New StreamReader(data)
Dim str As String = ""
str = reader.ReadLine()
Do While str.Length > 0
Console.WriteLine(str)
str = reader.ReadLine()
Loop
When I run it it never goes inside the loop.

Give this a shot...
Dim URL As String = "http://stackoverflow.com/"
Dim html As String = New WebClient().DownloadString(URL)
Better Solution (Releases resources that the network stack is using. Also ensure's (hope) the CLR cleans these up when needed.)
Using client As New WebClient()
html = client.DownloadString(URL)
End Using

Related

Tweetsharp Twitter API - post multiple images

The code below works and will post to Twitter, but will only ever post one image to the account, even if three images are sent.
These are only jpg or png files, not video or animated gifs.
Any ideas would be appreciated.
Dim service = New TwitterService(key, secret)
service.AuthenticateWith(token, tokenSecret)
Dim opt As New SendTweetWithMediaOptions
Dim images As New Dictionary(Of String, IO.Stream)
Dim myStream As FileStream
If Len(ImgName1) > 0 Then
myStream = New FileStream(ImgName1, FileMode.Open)
images.Add("1", myStream)
End If
If Len(ImgName2) > 0 Then
myStream = New FileStream(ImgName2, FileMode.Open)
images.Add("2", myStream)
End If
If Len(ImgName3) > 0 Then
myStream = New FileStream(ImgName3, FileMode.Open)
images.Add("3", myStream)
End If
opt.Status = TweetText
opt.Images = images
Dim TwitterStatus = service.SendTweetWithMedia(opt)
The code I used to get it working using TweetInvi https://github.com/linvi/tweetinvi (installed via Nuget) is:
(Imports Tweetinvi)
Auth.SetUserCredentials(key, secret, token, tokenSecret)
Dim params As New Tweetinvi.Parameters.PublishTweetOptionalParameters()
params.Medias = New List(Of Models.IMedia)
Dim MediaIDs As String = String.Empty
Dim ids As New List(Of Long)
If Len(ImgName1) > 0 Then
Dim imgFile1 As Byte() = System.IO.File.ReadAllBytes(ImgName1)
Dim myMedia1 = Upload.UploadImage(imgFile1)
ids.Add(myMedia1.MediaId)
imgFile1 = Nothing
End If
If Len(ImgName2) > 0 Then
Dim imgFile2 As Byte() = System.IO.File.ReadAllBytes(ImgName2)
Dim myMedia2 = Upload.UploadImage(imgFile2)
ids.Add(myMedia2.MediaId)
imgFile2 = Nothing
End If
If Len(ImgName3) > 0 Then
Dim imgFile3 As Byte() = System.IO.File.ReadAllBytes(ImgName3)
Dim myMedia3 = Upload.UploadImage(imgFile3)
ids.Add(myMedia3.MediaId)
imgFile3 = Nothing
End If
params.MediaIds = ids
Dim myTweet = Tweet.PublishTweet("blah, blah, blah", params)
The API end point called by that TweetSharp method doesn't support multiple images (I don't think it ever did, but either way the current docs say no; https://dev.twitter.com/rest/reference/post/statuses/update_with_media).
What you need to do is use the UploadMedia endpoint to upload the image and capture the id for each, then send a tweet with the list of ids.
I'm not sure which variant of TweetSharp you're using. The official/original one has known bugs in the Nuget package, and while the source in the repo has those fixed it is lacking the newer API support.
You could try TweetMoaSharp (mostly maintained by me), as I believe this supports the new end points (but it's been a while since I looked). There's also tweetsharp-alternative on Nuget and a few others floating around that might have support.

How to use ASPxFileManager 'SelectedFiles' property to attach files to MailMessage?

I am using DevExpress tools, specifically the FileManager which has a 'SelectedFiles' property which returns all the data needed to (add,insert,delete,retrieve, modify the record). However I can not figure out how to use the selectedfiles as a MailMessage.Attachment. The code below works to send the email, I've changed the credentials and host values for security. I just need some direction or thought on how to use the FileManager collection that is generated via 'SelectedFiles' and add them as an attachment to the email. I would really like to Zip the files if possible, but at this point simply attaching them is fine. Any thoughts?
Dim fileManager As ASPxFileManager = TryCast(sender, ASPxFileManager)
If ASPxFileManager1.SelectedFiles IsNot Nothing AndAlso ASPxFileManager1.SelectedFiles.Length > 0 Then
For i As Integer = 0 To ASPxFileManager1.SelectedFiles.Length - 1
Dim file = ASPxFileManager1.SelectedFiles.ToString
Dim attachments As New Attachment(fileManager.SelectedFiles.ToString)???
Next
End If
Try
Dim mail As New MailMessage("noreply", DropDownEdit.Text)
Dim smtp_Server As New SmtpClient("host") With {.Credentials = New Net.NetworkCredential("username", "password")}
mail.Subject = "SUBJECT"
mail.IsBodyHtml = False
mail.Body = "Testing"
smtp_Server.Send(mail)
successLabel.Text = "Your email was sent successfully."
Catch ex As Exception
End Try
End Sub
Dim attachments As New Attachment(ReadFile(ASPxFileManager1.SelectedFiles(i)), file)
mail.Attachments.Add(attachments)
The function below was needed to Read the bytes and then attach the items to the MailMessage.
Public Function ReadFile(file__1 As FileManagerFile) As System.IO.Stream
'This function allows us to pull the bytes from the DB value to render the file.
Dim filePath As String = (file__1.RelativeName)
Dim fileData As Byte()
Using con As New SqlConnection([Global].conn)
Dim sqlCmd As New SqlCommand()
sqlCmd.Connection = con
sqlCmd.Parameters.Add("#Name", SqlDbType.VarChar).Value = file__1.Name
sqlCmd.Parameters.Add("#APIKey", SqlDbType.Int).Value = Session("_UserAPIKey")
sqlCmd.CommandText = "SELECT STATEMENT"
con.Open()
Dim sqlReader As SqlDataReader = sqlCmd.ExecuteReader()
If sqlReader.HasRows Then
While sqlReader.Read()
fileData = CType(sqlReader(0), Byte())
End While
End If
End Using
Return New MemoryStream(fileData)
End Function

asp.net openxml open docx, change content and stream to user

My code is below. I'm trying to open a Word document with Open XML and change certain text. The document must then be send to the client where they can save it on their PC or Open it. It send a document to the client but it is blank. When I save my InMemory document it says the file cannot be open it must contain at least one root element. I'm using Visual STudio 2010 Express. Please help me. What is wrong with my code?
Dim fileName As String = "directory on server\doc.docx"
Dim myDocument As WordprocessingDocument = WordprocessingDocument.Open(fileName, True)
Dim docText As String = Nothing
Dim sr As StreamReader = New StreamReader(myDocument.MainDocumentPart.GetStream)
docText = sr.ReadToEnd
sr.Close()
Dim regexText As Regex = New Regex("XXXCourtXXX")
docText = regexText.Replace(docText, "JOHANNESBURG")
Dim ms As New MemoryStream()
Dim sw As StreamWriter = New StreamWriter(ms)
sw.Write(docText)
myDocument.MainDocumentPart.FeedData(ms)
Dim mem = New MemoryStream()
myDocument.MainDocumentPart.GetStream().CopyTo(Response.OutputStream)
Response.ContentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
Response.AppendHeader("Content-Disposition", "attachment;filename=Notice.docx")
mem.Position = 0
mem.CopyTo(Response.OutputStream)
Response.Flush()
Response.End()
You're dimming a new memory stream mem, writing nothing to it and then copying it to the output stream. Remove all lines referencing your mem variable.

xml response http post - convert request.inputstream to string - asp.net

I'm receiving an xml response and I now want to parse this.
Currently what I have to receive the XML response is:
Dim textReader = New IO.StreamReader(Request.InputStream)
Request.InputStream.Seek(0, IO.SeekOrigin.Begin)
textReader.DiscardBufferedData()
Dim Xmlin = XDocument.Load(textReader)
How can I go ahead now a process this and pick out the element values?
<subscription>
<reference>abc123</reference>
<status>active</status>
<customer>
<fname>Joe</fname>
<lname>bloggs</lname>
<company>Bloggs inc</company>
<phone>1234567890</phone>
<email>joebloggs#hotmail.com</email>
</customer>
</subscription>
If I have it in string format I can do this using
Dim xmlE As XElement = XElement.Parse(strXML) ' strXML is string version of XML
Dim strRef As String = xmlE.Element("reference")
Do I need to convert the request.inputstream to a strign format or is there another better way?
Thanks
Do I need to convert the request.inputstream to a strign format or is there another better way?
You could directly load it from the request stream, you don't need to convert it to a string:
Request.InputStream.Position = 0
Dim Xmlin = XDocument.Load(Request.InputStream)
Dim reference = Xmlin.Element("subscription").Element("reference").Value
or:
Dim reference = Xmlin.Descendants("reference").First().Value
In the end after much testing I could only get this to work:
Dim textReader = New IO.StreamReader(Request.InputStream)
Request.InputStream.Seek(0, IO.SeekOrigin.Begin)
textReader.DiscardBufferedData()
Dim Xmlin = XDocument.Load(textReader)
Dim strXml As String = Xmlin.ToString
Dim xmlE As XElement = XElement.Parse(strXml)
Dim strRef As String = xmlE.Element("reference")
Dim strStatus As String = xmlE.Element("status")
Dim strFname As String = xmlE.Element("customer").Element("fname").Value()
Dim strLname As String = xmlE.Element("customer").Element("lname").Value()
Dim strCompany As String = xmlE.Element("customer").Element("company").Value()
Dim strPhone As String = xmlE.Element("customer").Element("phone").Value()
Dim strEmail As String = xmlE.Element("customer").Element("email").Value()

How to pass parameters to SSRS report programmatically

I'm looking for a little help on programmatically passing parameters to a SSRS report via VB.NET and ASP.NET. This seems like it should be a relatively simple thing to do, but I haven't had much luck finding help on this.
Does anyone have any suggestions on where to go to get help with this, or perhaps even some sample code?
Thanks.
You can do the following,: (it works both on local reports as in Full Blown SSRS reports. but in full mode, use the appropriate class, the parameter part remains the same)
LocalReport myReport = new LocalReport();
myReport.ReportPath = Server.MapPath("~/Path/To/Report.rdlc");
ReportParameter myParam = new ReportParameter("ParamName", "ParamValue");
myReport.SetParameters(new ReportParameter[] { myParam });
// more code here to render report
If the Report server is directly accessible, you can pass parameters in the Querystring if you are accessing the repoort with a URL:
http://MyServer/ReportServer/?MyReport&rs:Command=Render&Param1=54321&Param2=product
You can add output formatting by adding the following on the end of the URL:
&rs:Format=Excel
or
&rs:Format=PDF
It's been a while since I did this code, but it may help:
Your web project has to be a Web Site, and not a project of type "ASP.Net Web Application", or you won't be able to add the reference mentioned below.
Right click on the project and add an ASP.Net folder - App_WebReferences. You'll have to specify the server where your SRS is; choose the .asmx.
Once it's added, the folder under that level is called RSService, and under that are 2 things: reportservice.discomap & .wsdl.
In my VB, I do Imports RSService and Imports System.Web.Services.Protocols, then...
Dim MyRS As New ReportingService
The reporting service is on a different server than the webserver the app is on, so I can't do the following: MyRS.Credentials = System.Net.CredentialCache.DefaultCredentials
Instead: MyRS.Credentials = New System.Net.NetworkCredential(rs1, rs2, rs3),
where the rs1/2/3 are the login to SRS box, password to SRS box, & domain name". (These are encrypted in my web.config.)
Then, a mass-paste:
MyRS.Credentials = New System.Net.NetworkCredential(rs1, rs2, rs3)
Dim ReportByteArray As Byte() = Nothing
Dim ReportPath As String = "/SRSSiteSubFolder/ReportNameWithoutRDLExtension"
Dim ReportFormat As String = "PDF"
Dim HistoryID As String = Nothing
Dim DevInfo As String = "<DeviceInfo><Toolbar>False</Toolbar></DeviceInfo>"
'Dim x As ReportParameter - not necessary
Dim ReportParams(0) As ParameterValue
ReportParams(0) = New ParameterValue()
ReportParams(0).Name = "TheParamName"
ReportParams(0).Value = WhateverValue
Dim Credentials As DataSourceCredentials() = Nothing
Dim ShowHideToggle As String = Nothing
Dim Encoding As String
Dim MimeType As String
Dim ReportHistoryParameters As ParameterValue() = Nothing
Dim Warnings As Warning() = Nothing
Dim StreamIDs As String() = Nothing
'Dim sh As New SessionHeader() - not necessary
''MyRS.SessionHeaderValue = sh - not necessary
ReportByteArray = MyRS.Render(ReportPath, ReportFormat, HistoryID, DevInfo, ReportParams, Credentials, _
ShowHideToggle, Encoding, MimeType, ReportHistoryParameters, Warnings, StreamIDs)
'(Yay! That line was giving "HTTP error 401 - Unauthorized", until I set the credentials
' as above, as explained by http://www.odetocode.com/Articles/216.aspx.)
'Write the contents of the report to a PDF file:
Dim fs As FileStream = File.Create(FullReportPath, ReportByteArray.Length)
fs.Write(ReportByteArray, 0, ReportByteArray.Length)
fs.Close()
Call EmailTheReport(FullReportPath)
If IO.File.Exists(FullReportPath) Then
IO.File.Delete(FullReportPath)
End If
ReportViewer1.LocalReport.DataSources.Clear();
ReportViewer1.Reset();
Label1.Visible = false;
ReportViewer1.Visible = true;
DataSet dataSet = new DataSet();
dataSet = new ClassBLL().Load_Report_Detail(TextBox1.Text,
ddlType.SelectedValue, levelcode, fields);
ReportDataSource datasource = new ReportDataSource("DataSet_StoreprocedureName",
dataSet.Tables[0]);
if (dataSet.Tables[0].Rows.Count == 0)
{
ReportViewer1.Visible = false;
}
ReportViewer1.LocalReport.ReportPath = Server.MapPath("") + #"\Report.rdlc";
ReportViewer1.LocalReport.DataSources.Clear();
ReportViewer1.LocalReport.DataSources.Add(datasource);
string fields="name,girish,Z0117";
string[] filedName = fields.Split(',');
ReportParameter[] param = new ReportParameter[2];
//for (int i = 0; i < filedName.Length; i++)
//{
param[0] = new ReportParameter(filedName[0], filedName[0], true);
param[1] = new ReportParameter(filedName[3], filedName[3], true);
// }
ReportViewer1.LocalReport.SetParameters(param);
ReportViewer1.ServerReport.Refresh();

Resources