Solved

How can I impliment substring() filter in asp.net XML RSS feed?

Posted on 2009-05-13
7
509 Views
Last Modified: 2012-05-06
I'm having a trouble with substring() filter used in this vb XML RSS feed which I've set up, following a tutorial via this site:
http://www.vbasic.net/detail.aspx?tid=142

The line in the code below which is giving me trouble is, line 40:
objX.WriteElementString("description", dr("NewsStory").ToString.Substring(0, 100) & "..")

The error it produces is:
System.ArgumentOutOfRangeException: Index and length must refer to a location within the string.
Parameter name: length


When I change the description to show the whole News Story, like so:
objX.WriteElementString("description", dr("NewsStory"))

It works perfectly - however isn't the desired/required result.

If you could solve this I would be most grateful.

Cheers!
Imports System.Xml
Imports System.Text
Imports System.Data
Imports System.Data.SqlClient
 
Partial Class newsFeed
    Inherits System.Web.UI.Page
 
 
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
 
        Response.Clear()
        Response.ContentType = "application/rss+xml"
        Dim objX As New XmlTextWriter(Response.OutputStream, Encoding.UTF8)
        objX.WriteStartDocument()
        objX.WriteStartElement("rss")
        objX.WriteAttributeString("version", "2.0")
        objX.WriteStartElement("channel")
 
        Dim cmd As New SqlCommand("Select top 10 * From aspnet_News ORDER BY NewsId DESC", New SqlConnection(ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString))
        cmd.Connection.Open()
        Dim dr As SqlDataReader = cmd.ExecuteReader()
 
        objX.WriteElementString("title", "RSS News Feed")
        objX.WriteElementString("link", "http://www.site.com/news.aspx")
        objX.WriteElementString("description", "The latest news and information from the www.site.com")
        objX.WriteElementString("language", "en-us")
        objX.WriteElementString("ttl", "60")
        objX.WriteElementString("image", "http://www.site.com/Resources/images/logo.gif")
        objX.WriteElementString("lastBuildDate", String.Format("{0:R}", DateTime.Now))
 
        Do While dr.Read()
            objX.WriteStartElement("item")
            objX.WriteElementString("title", dr("NewsTitle").ToString())
            objX.WriteElementString("author", "Name of Author")
            objX.WriteElementString("link", "http://www.site.com/news.aspx?id=" & dr("NewsId"))
            objX.WriteStartElement("guid")
            objX.WriteAttributeString("isPermaLink", "true")
            objX.WriteString("http://www.site.com/news.aspx?id=" & dr("NewsId"))
            objX.WriteEndElement()
            objX.WriteElementString("pubDate", String.Format("{0:R}", dr("NewsDateTime")))
            objX.WriteStartElement("category")
            objX.WriteString(dr("NewsTitle").ToString())
            objX.WriteEndElement()
            'objX.WriteElementString("description", dr("NewsStory")) '//THIS WORKS!
            objX.WriteElementString("description", dr("NewsStory").ToString.Substring(0, 100) & "..") '//THIS DOESNT
            objX.WriteEndElement()
        Loop
 
        objX.WriteEndElement()
        objX.WriteEndElement()
        objX.WriteEndDocument()
        objX.Flush()
        objX.Close()
        Response.End()
 
    End Sub
 
End Class

Open in new window

0
Comment
Question by:badstyle
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 2
7 Comments
 
LVL 6

Expert Comment

by:ViceroyFizzlebottom
ID: 24379336
You need to ensure that the substring you're asking for isn't longer than the columns data. So you could use:
objX.WriteElementString("description", dr("NewsStory").ToString.Substring(0, dr("NewsStory").Length - 1) & "..")

Simply asking for string data from 0 - 100 will throw an exception if the data is < 100.
0
 
LVL 6

Expert Comment

by:ViceroyFizzlebottom
ID: 24379343
Whoops, in my last line I meant "if the data > 100"
0
 
LVL 2

Author Comment

by:badstyle
ID: 24380069
hmm that's a little awkward, as there may be occasions when the data is less than the maximum required...

Is it possible to interrogate the data so that even if it is less than 100 it will still work?

Better than that... is it possible to interrogate the data so as not to clip words, or even round it to the nearest full stop? If so can you provide a solution on how that would work?

Thanks for your speedy assistance, really appreciate it!
0
Forrester Webinar: xMatters Delivers 261% ROI

Guest speaker Dean Davison, Forrester Principal Consultant, explains how a Fortune 500 communication company using xMatters found these results: Achieved a 261% ROI, Experienced $753,280 in net present value benefits over 3 years and Reduced MTTR by 91% for tier 1 incidents.

 
LVL 6

Assisted Solution

by:ViceroyFizzlebottom
ViceroyFizzlebottom earned 50 total points
ID: 24380263
Below is a sample of something that would work. If the total length is > 100, we only work with the first 100 characters, taking from that the last space position (which we'll assume here is a word break).



string s = dr["NewsStory"].ToString();
string truncatedText = String.Empty;
 
if(s.Length > 100)
{
    truncatedText = s.Substring(0, 100).Substring(0, s.LastIndexOf(" "));
}
 
objx.WriteElementString("description", truncatedText + "...");

Open in new window

0
 
LVL 6

Assisted Solution

by:ViceroyFizzlebottom
ViceroyFizzlebottom earned 50 total points
ID: 24380316
Actually in the code above, you can't append the last .Substring() (My brain was in LINQ mode). So it would end up as:

truncatedText = s.Substring(0,100);
truncatedText = truncatedText.Substring(0, truncatedText.LastIndexOf(" "));

0
 
LVL 3

Accepted Solution

by:
channa_m earned 75 total points
ID: 24387276
How about something like this,

        Dim newsStory = dr("NewsStory").ToString
        Dim len = newsStory.Length - 1
 
        If len > 100 Then
            len = 100
        End If
 
        newsStory = newsStory.SubString(0, len)
        objX.WriteElementString("description", newsStory & "..")

Open in new window

0
 
LVL 2

Author Closing Comment

by:badstyle
ID: 31581198
Although both gave desirable results I preferred Channa M's solution on the basis that it would show part of the parameters value even though its content may have contained less than the substrings maximum length.

Many thanks people!
0

Featured Post

Is Your DevOps Pipeline Leaking?

Is your CI/CD pipeline a hodge-podge of randomly connected tools? You’ve likely got a tool to fix one problem & then a different tool to fix another, resulting in a cluster of tools with overlapping functionality. Learn how to optimize your pipeline with Gartner's recommendations

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Browsing the questions asked to the Experts of this forum, you will be amazed to see how many times people are headaching about monster regular expressions (regex) to select that specific part of some HTML or XML file they want to extract. The examp…
A long time ago (May 2011), I have written an article showing you how to create a DLL using Visual Studio 2005 to be hosted in SQL Server 2005. That was valid at that time and it is still valid if you are still using these versions. You can still re…
Nobody understands Phishing better than an anti-spam company. That’s why we are providing Phishing Awareness Training to our customers. According to a report by Verizon, only 3% of targeted users report malicious emails to management. With compan…
Attackers love to prey on accounts that have privileges. Reducing privileged accounts and protecting privileged accounts therefore is paramount. Users, groups, and service accounts need to be protected to help protect the entire Active Directory …

752 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question