reading text file lines into asp.net contentplaceholder - asp.net

I am new to ASP.Net and am trying to set up some content pages to work with my master page.
I currently have the following text hardcoded into an asp:contentplaceholder and it works just fine. I want to read lines in from a text file to produce those headlines and retain the current formatting. I tried using the tag i need each line as a separate tag. Below is the code in the content place holder. Id like to have this done in the Page_Load or the pre Init.
<p class="text1">--- We recently completed an evaluation for a large Ocean Tug fleet showing 70% particulate reduction, 11% NOx reduction and an 8% fuel economy improvement.</p>
<p class="text1">--- Our Product was added to the Grainger catalog as its primary emissions and fuel efficiency Catalyst.</p>
<p class="text1">--- Our Product is recommended by Mann-Hummel to promote better performance in Diesel Particulate Filters.</p>

The
IO.File.ReadAllLines()
method will read a text file and return to you an array of strings; one for each line of text.
You can then loop through that, building up the HTML string to place into the ContentPlaceHolder

Try the following:
Dim Lines() As String = IO.File.ReadAllLines(Path)
For Each f As String In Lines
Response.Write("<p class='text1'>" & f & "</p>")
Next
Edit: I noticed you want it inside a ContentPlaceHolder, therefore can't use Response.Write. If that's the case you can try using a Literal control and then append the previous code using LiteralName.Text &= f
Hopefully it helps!
Edit: Adding more code, supporting what #Brian M. has said:
Dim Content As String = String.Empty
Dim Lines() As String = IO.File.ReadAllLines(Path)
For Each TxtFromFile As String In Lines
Content &= "<p class='text1'>" & TxtFromFile & "<p>"
Next
Me.ContentPlaceHolder1.Controls.Add(New LiteralControl(Content))
I hope it helps.

Related

Classic ASP render a template and send variables

I have a classic ASP page, and I need to create a loop for each row on a table and then create an html document and save it to the hard drive, but I want to create a template so I just send the two variables to the template so I don't have to write the HTML document each time on the loop.
This is what I have so far:
SQL = "select Title, Article from [ASPTest].[dbo].[articles]"
set rs = conn.execute(SQL)
arrRecs = rs.GetRows
For row = 0 To UBound(arrRecs, 2) 'Rows
For col = 0 To UBound(arrRecs, 1) 'Columns
Response.Write rs.Fields(col).Name & " = " & arrRecs(col, row) & " "
dim fs,f
set fs=Server.CreateObject("Scripting.FileSystemObject")
set f=fs.CreateTextFile("C:\Users\User\Documents\ASP Pages\"+arrRecs(col, row)+".html",true)
f.write("<html><body><div>It kinda works</div></body></html>")
f.close
set f=nothing
set fs=nothing
Next
Response.Write "<br />"
Next
Is there a way to use a template that has 2 variable holders and send the article name and title to the template and then save it to the disk?
Thank you.
I think you could probably achieve what you want using a template stored as a text file, and the Replace function.
Your template should be a fully-formed html page, but with placeholder values for the title and article. The placeholders need to be unique, so something like [[[~~~Title~~~]]] or a similar sequence that will not occur in your actual titles, articles, or the template itself.
<html>
<head><title>[[[~~~Title~~~]]]</title></head>
<body>
<h1>[[[~~~Title~~~]]]</h1>
<div id="article">[[[~~~Article~~~]]]</div>
</body>
</html>
In your code, read the template from the file and store it in a variable. (So technically, you could just write it to a variable in the first place, but VBScript is bad at string concatenation... anyway.) Get your array of titles & articles and loop through it (though only once: I'm not sure why you're looping through both rows and columns in your attempt). For each row, make a copy of the template, replace the title placeholder with the current row's title, replace the article placeholder with the current row's article, and write the result to a file.
Dim template, t
Dim fso, file
Dim rs, conn, SQL
Dim records, row
SQL = "SELECT ID, Title, Article FROM [ASPTest].[dbo].[articles]"
'[...database stuff...]
records = rs.GetRows
'[...close database...]
Set fso = Server.CreateObject("Scripting.FileSystemObject")
Set file = fso.OpenTextFile("path/to/template.txt",1) '- 1 = For reading
template = file.ReadAll
file.Close
Set file = Nothing
For row = 0 to UBound(records,2)
t = template
t = Replace(t,"[[[~~~Title~~~]]]",records(1,row))
t = Replace(t,"[[[~~~Article~~~]]]",records(2,row))
Set file = fso.CreateTextFile("path/to/html/" & records(0,row) & ".html")
file.Write(t)
file.Close
Set file = Nothing
Next
Set fso = Nothing
Back in the day I created the KudzuASP template engine to solve this rather complex deficiency in Classic ASP. In KudzuASP you can have ASP code pages that have absolutely NO HTML in them.
KudzuASP is as small include file roughly under 1000 lines of code that turns your hosting ASP page into an event driven object used by the template engine.
In short you create an instance of the template engine, set some variables, install custom code objects, and invoke it after which the template engine reads your template and make callbacks to your ASP page when and where appropriate. It has a library system so you can load libraries of custom tags handlers/components via code or by tags placed in your HTML template.
One of the best features is that for those still under the Classic ASP umbrella it makes 100% separation of application code and logic from presentation possible. Coding Classic ASP pages using KudzuASP is much easier than without and because of the way ASP compiles pages the callbacks are "native" and very fast.
You can find it here KudzuASP where the project is still maintained.

I want to replace new line with break and spaces before/After the text must be same present

I want to replace new line with break and spaces before the text must be same.
For eg:
Text:
This is .net class with 100 students.
They are able to perform well.
They require certification for career improvement.
This is the above format i require with same indent.
I have regular expression i.e lblQuestion.Text = lang.Replace("\n", "");
but it is replacing only text to next line but it is missing the spaces and giving me output as
PRESENT OUTPUT:
This is .net class with 100 students.
They are able to perform well.
They require certification for career improvement.
REQUIRED OUTPUT:
This is .net class with 100 students.
They are able to perform well.
They require certification for career improvement.
Please help me on this.
You will need to also replace each of the starting spaces with no break spaces ( ), so browsers will not collapse the whitespace to a single one.
A simple alternative is to enclose the output in <pre></pre> elements (stands for pre-formatted).
The pre tag can be used to display text is the way you want, and without having to replace line-breaks with br tags. However, you might need to style the pre tag's font, as the default font seems to be mono-space for some browsers.
Edit:
Assuming you're using Web Forms, to do this dynamically, define a Literal control in your aspx markup, as follows:
<pre style="font-family:arial">
<asp:Literal ID="litText" runat="server"></asp:Literal>
</pre>
Then in your code-behind, set the Literal's Text:
protected void Page_Load(object sender, EventArgs e)
{
litText.Text = #"This is .net class with 100 students.
They are able to perform well.
They require certification for career improvement.";
}

How to add a hyperlink in a text file in ASP.NET using VB

I have tow pages, first one for displaying the data in the text file and the other one is to store the data. I want to save a site in the text file but when i display the data will be just text and I can't click it as a link. The code I post is when I write to a file in display page.
Try
Dim fs As String
fs = Server.MapPath("Footer.txt")
lblsplittext.Text = ""
Dim filestream As StreamReader
filestream = New IO.StreamReader(fs)
Dim readcontents As String = filestream.ReadToEnd()
Dim textdelimiter As String = "#"
Dim splitout = Split(readcontents, textdelimiter)
Dim i As Integer
For i = 0 To UBound(splitout)
lblsplittext.Text &= splitout(i) & "<br>"
Next
filestream.Close()
Catch ex As Exception
Dim str As String
str = ex.Message
End Try
If you have a different suggestion about how to read from a file or database (it doesnt matter from where for now) just keep in mine when i display them i just need to have hyperlinks among my text... Or can I write to html file instead of text file if so what is the difference i need to make to write to html. I really really need help here and i have done many searches but i found nothing.
Thanks in advance.
There are a number of ways you could do this. One would be to use a series of dynamically-added Label controls. Your Hyperlink control could simply be inserted between one Label control and the next.
Do you intend to retrieve information from your series of labels on postback? (It would be redundant to do that, since you already know what the information is, but just in case.) Using multiple controls would make that more complicated. You could try one or more Literal controls, created dynamically and added as child controls to a Panel control. Again, the Hyperlink control would be added at whatever time you need it.

VB.net - RsData / Cleaning up code

I have a question regarding VB.net and the use of rsData connections to an SQL database.
Basically we have a few inline pages that will display course information of courses that my institution runs. The code will connect to an SQL DB and pull through live data directly in the following format.
html += "<tr><td>" & rsData("M_Start") & "</td><td>" & rsData("WEEKS") & "</td><td>" & rsData("DAYSTIME") & "</td></tr>"
Now I was wondering if people would suggest pulling directly from an open DB connection or map the RsData results to strings? All data connections open and close after they have done their required portions and we have around 5 different procedures that occur within the page.
I'm worried that the code isn't as clean as it could be and would really like to tidy up this inherited nightmare. Also can people shed any best practice with inline code and the multiple data connections?
Thanks!
It's difficult to give you a full solution on how to clean-up the code without seeing it all. Better ways to display your data might be using a GridView or Repeater.
However, if you are going to build up the HTML in a String variable I'd suggest doing the portion you've posted like this:
Dim html As New Text.StringBuilder
html.Append(String.Format("<tr><td>{0}</td><td>{1}</td><td>{2}</td></tr>",
rsData("M_Start"),
rsData("WEEKS"),
rsData("DAYSTIME")))
It makes it more readable and a StringBuilder performs better than incrementing a String variable multiple times.
I'm not sure how you are dealing with repetition, but you could then do something like this (assuming rsData belongs to a DataTable):
Const htmlRowFormat As String = "<tr><td>{0}</td><td>{1}</td><td>{2}</td></tr>"
Dim html As New Text.StringBuilder
For Each dr As DataRow In rsDataTable.Rows
html.Append(String.Format(htmlRowFormat,
rsDataTable("M_Start"),
rsDataTable("WEEKS"),
rsDataTable("DAYSTIME")))
Next
To get your html: html.ToString

Replace(Environment.NewLine, "<br/>") is not working as expected when displaying text on a web page

I'm not sure why the following code is not working as intended:
litMessage.Text = messageBody.Replace(Environment.NewLine, "<br/>")
Where litMessage is the name of the literal control and messageBody is the name of the string variable.
My intention is to output a string onto a web page and to replace the line breaks with a br tag so that it can be displayed on the page correctly. However, nothing is replaced. When viewing the page source, it looks like the line breaks still exist in the string. Similarly, when displaying the string via MsgBox, it displays normally as well. I have also tried wrapping the output with the pre tag and it displays the line breaks properly as well.
The string was originally entered by a user through the use of an asp:Textbox and saved into a MSSQL database. It's retrieved and displayed on another webpage using an asp:Literal control. The only thing that happens to the string before it is submitted is that it is trimmed (i.e. textbox.Text.Trim()).
Perhaps there is something I did not consider?
Edit #1: Due to time constraints, I've decided to just wrap the text with the pre tag. It's an acceptable work around as it preserves the line breaks. Unfortunately, it doesn't explain why the code didn't work in the first place. In the meantime, I'll just leave the question unanswered until I find a proper answer.
Edit #2: Solution found and answered below. UpdatePanel tag added to the question for future reference.
After revisiting this issue, I have found that updatepanels were causing the problem.
Doing some more testing, I looked into what the string contained using the following code:
MsgBox(textbox.Text.Contains(vbCr))
MsgBox(textbox.Text.Contains(vbCrLf))
MsgBox(textbox.Text.Contains(vbNewLine))
MsgBox(textbox.Text.Contains(Environment.Newline))
All four statements returned false. This was tested on the string before sending to the database as well as on the string retrieved from the database.
From my point of view, there had to be something on the markup that was removing the line breaks. At first, I thought the Literal, Textbox, and Label controls did something funny to line breaks when retrieved in the code behind. This is not the case (and would be bizarre if Microsoft let this happen).
Combing through the code some more, I found that all these controls were inside an UpdatePanel. Remembering my previous negative experiences with UpdatePanels, I then thought that this might just be the culprit. I removed it and lo and behold, the line breaks did not go away in the code. The code I posted just above all returned true.
Both pages had the controls for submitting the text and displaying the text inside an UpdatePanel. I found that the line breaks disappeared when retrieving the text from the page. When displaying the text onto the page, the UpdatePanel does not alter the string in any way. The following code ended up working just fine:
litMessage.Text = messageBody.Replace(Environment.NewLine, "<br/>")
Although I'm still not sure why line breaks were still displayed correctly when using the pre tag or even displaying the retrieved value using a javascript alert box.
It's hard to say from the code you've posted, but if you're passing the myString varaible itself to the page (and not the return value of the Replace function) you'll need to do -
myString = myString.Replace(Environment.NewLine, "<br/>")
before passing it to the page.
If you use an UPDATEPANEL the myText..Replace(Environment.NewLine, "<br/>") WILL NOT WORK. I found out the hard way (spent 2 hours already)
The solution (when using updatepanel) is to set a "PostBackTrigger" like this:
<asp:UpdatePanel runat="server" ID="pnlUpdate" UpdateMode="Conditional">
<Triggers>
<asp:PostBackTrigger ControlID="btnDoThatShitAlready" />
</Triggers>
Just found this while looking for a solution for replace not working with text in the literal control while it resides within a formview. The way I solved it was, in the databinding for the literal, to pass the text to a string, do the replace on the string then put the processed text back into the literal's text field.
Protected Sub MyLit_DataBinding(ByVal sender As Object, ByVal e As EventArgs)
Dim text1 As String
text1 = CType(myFormView.FindControl("MyLit"), Literal).Text
text1 = Replace(text1, Environment.NewLine, "<br />")
CType(myFormView.FindControl("MyLit"), Literal).Text = text1
End Sub
I hope this helps you, and anyone else who might visit this site for a solution.
Regarding the 4 tests above that failed (author: nullexception)...
MsgBox(textbox.Text.Contains(vbCr))
MsgBox(textbox.Text.Contains(vbCrLf))
MsgBox(textbox.Text.Contains(vbNewLine))
MsgBox(textbox.Text.Contains(Environment.Newline))
I tried those tests and they failed for me as well. Then, I noticed there was no test for just vbLf, so I tested it. BINGO! That was it!
So, this works...
Label.Text = MultiLineTextBox.Text.Replace(ControlChars.Lf, "<br />")
I wasted my two hours finding what was actually wrong.
Well, solution is instead of Environment.NewLine, use ControlChars.Lf
You can remove updatepanel which will sort out the problem for future data. But if you already have some data, using ControlChars.Lf will help.
You can use it like this, because the System.NewLine returns a "\r\n" string
dim messageBody as string = "some text here";
litMessage.Text = messageBody.Replace("\r\n", "< br />");
litMessage.Text = messageBody.Replace("\\\\n","< br />").Replace(Environment.NewLine, "< br />")
It has worked for me. Hope this might work for you as well.
var str = "Text sample to replace carriage return + newline ("
+ (char)13 + (char)10
+ #") and
the Environment.NewLine and "
+ Environment.NewLine
+ " and the unix \n new line character.";
str.Replace("\r\n","<br />")
.Replace(Environment.NewLine, "<br />")
.Replace("\n", "<br />");
The output is
Text sample to replace carriage return + newline (<br />) and<br /> the Environment.NewLine and <br /> and the unix <br /> new line character.
To put the label text next line we can use the below mentioned solution.
<asp:Label ID="lblAppointmentLocation" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "Location").ToString().Replace(Environment.NewLine, "<br/>").Replace("\n", "<br />") %>'></asp:Label>
What you are really looking for is:
#Html.Raw(#Regex.Replace(input_to_be_printed_correctly, #"\r\n?|\n", "<br />"))
I'm using this code and it works :
Instead of
.Replace(Environment.NewLine, "<br/>")
use
.Replace("\n", "<br />")
Hope to be useful.

Resources