Click here to Skip to main content
Click here to Skip to main content

Fully Customized Reusable ASP+ Vertical/Horizontal Marquee Consuming XML/MS SQL

By , 23 May 2005
 

Introduction

In every project I need a way to show the latest articles, news, weathercast, etc. Some projects process links with query strings while others not.. My ideal solution would be a quick, simple, lightweight Marquee Web Custom Control...

If you are not familiar with custom web controls, here is a partial definition from the Microsoft documentation:

Web controls run on the server and include form controls such as buttons and text boxes, as well as special purpose controls such as a calendar. This allows you to programmatically control these elements on a web page. Web controls are more abstract than HTML controls. Their object model does not necessarily reflect HTML syntax. (See MSDN.)

Features

  • great design-time attributes.
  • allows you to choose database: XML or SQL Server.
  • you can apply your web template.
  • each topic has ID, description, date, anchor URL, anchor text.

Database

In the case of XML as database:

<?xml version="1.0" encoding="utf-8" ?> 
<marquee>
    <topic tpID='1' postDate='1/1/2002'>
        <url value='http://www.....com'> Link... </url>
        <hint><![CDATA[ Link Description goes here ]]></hint>
    </topic>
</marquee>

Using the code

Our control has three classes:

  • Marquee: WebControl (which renders the control).
  • Data (reads data from database (XML or SQL Server) and generates a collection of topics).
  • Anchor (data holder).

First, we will preview the Data class code:

public class Data
{
    public ArrayList GetNews(string str,bool _isXML)
    {        
        //setup Array List
        ArrayList AnchorsArrayList=new ArrayList();

        if(!_isXML)// Read From MSSQL DB :::::::::::::
        {
            try
            {
                //Select SQl Query : text,url,id,date,title , Table Name links
                string sqlSelectStr="SELECT text, url, id, date, title FROM links";
                SqlConnection myConnection;

                //connect DB And check without overload on the DB Server.
                myConnection=new SqlConnection(str);
                if(myConnection.State==ConnectionState.Closed){myConnection.Open();}

                //pass our SQL Str within new Command
                SqlCommand myCommand=new SqlCommand(sqlSelectStr,myConnection);

                //Creating  A Reader to store Returned Database Data
                SqlDataReader myReader=myCommand.ExecuteReader();

                //looping thrugh Reader.
                while(myReader.Read())
                {
                    //intialize Anchor Object
                    Anchor anc=new Anchor();
                    //set Object id
                    anc.Id=Convert.ToInt32(myReader["id"]);
                    //set Object url
                    anc.Url=myReader["url"].ToString();
                    //set Object text
                    anc.Text=myReader["text"].ToString();
                    //set Object date
                    anc.Date=(DateTime)myReader["date"];
                    //set Object Hints
                    anc.Title=myReader["title"].ToString();

                    //add it to our Collection
                    AnchorsArrayList.Add(anc);
                }
                //Dispose any relation with DB
                myReader.Close();
                myConnection.Close();
            }
            catch(Exception ex)
            {
                throw ex;
            }
        }
        else // Read From XML DB ::::::::::::::::::::::::::::::::::
        {
            try
            {
                // create XMLDocument and Load Xml File
                XmlDocument xmlDoc=new XmlDocument();
                xmlDoc.Load(str);

                //create XPath Navigator in order to navigate XML Nodes...
                XPathNavigator nav=xmlDoc.CreateNavigator();

                // create Two NodeItrators in order to loop throw Topics
                XPathNodeIterator navIterator;//topic
                XPathNodeIterator navIterator2;//details

                //Set XPath to Topic Node...
                navIterator=nav.Select("marquee/topic");

                //topic number
                int topicNo=1;
                while(navIterator.MoveNext())
                {
                    //intialize Anchor Object
                    Anchor anc=new Anchor();

                    //read current topic ID and Date...I didnt 
                    //use id or Date in this article 
                    //but you can use it in sorting 
                    //search or Quary Strings between pages
                    anc.Id=
                      Convert.ToInt32(navIterator.Current.GetAttribute("tpID",
                      "").ToString());
                    anc.Date=
                      Convert.ToDateTime(navIterator.Current.GetAttribute("postDate",
                      "").ToString());
                        
                    //set Anchor/Link details XPath  
                    navIterator2=nav.Select("marquee/topic["+topicNo+"]/url");
                    navIterator2.MoveNext();

                    //read URL and Text o the current topic
                    anc.Url=
                      navIterator2.Current.GetAttribute("value",
                      "").ToString();
                    anc.Text=navIterator2.Current.Value.ToString();

                    //set description XPath  
                    navIterator2=nav.Select("marquee/topic["+topicNo+"]/hint");
                    navIterator2.MoveNext();
                    //read
                    anc.Title=navIterator2.Current.Value.ToString();

                    //finally... Save Our Link
                    AnchorsArrayList.Add(anc);

                    //moveNext
                    topicNo++;

                }
            }
            catch(Exception ex)
            {
                throw ex;
            }
        }
        //you are welcome......
        return AnchorsArrayList;
    }
}

Now we look at the Marquee class. There are two methods:

  • Render(...)
  • AnchorsListHtmlGenerator(.....)
        ///    <summary>
        ///     Generate Links Html Tags according to user setting.
        ///    </summary>
        ///    <param name="aList">Type:ArrayList :collection
        ///                        of Anchor Objects</param>
        ///    <returns>HTML as string</returns>
        protected string AnchorsListHtmlGenerator(ArrayList aList)
        {
            StringBuilder s = new StringBuilder();
            string dir;
            bool pFlag;

            //Set Langauge Direction Left-Right or Right-Left
            if (arabicSupport){dir = "rtl";}else{dir = "ltr";}

            //Set Marquee direction up-Down-Let-Right using enum
            switch (marqueeDirection)
            {
                case Direction.up:
                case Direction.down:
                    {
                        pFlag = true;
                        break;
                    }
                default:
                    {
                        pFlag = false;
                        break;
                    }
            }

            //looping through Arraylist    collection of Links.
            for (int i = 0; i < aList.Count; i++)
            {
                //Check    If User    need to    Show Hints Or not.
                if (showTitle)
                {
                    //Is Bold
                    if (TitleFontBold) { s.Append("<b>"); }

                    // <p> tag
                    if (pFlag) { s.Append("<p dir=\"" + dir + "\">"); }

                    //Font and Size
                    s.Append("<font    size=\"" + titleFontSize + 
                             "\" color=\"" + 
                             urlTitleForeColor.Name.ToString() + 
                             "\"" + ">");

                    //retrive Titles by    looping    through    Passed ArrayList
                    s.Append((((Anchor)aList[i]).Title).ToString());

                    //</font>
                    s.Append("</font>");

                    //</p>
                    if (pFlag) { s.Append("</p>"); }

                    //</b>
                    if (TitleFontBold) { s.Append("</b>"); }
                }

                //<p> tag and set Direction
                if (pFlag) { s.Append("<p dir=\"" + dir + "\">"); }

                //set Image    Source
                if (showImage)
                {
                    s.Append("<img    src=" + listItemImageSrc + ">");
                }

                //
                //<a> Tag
                s.Append("<A href=\"");
                //retrive and set Url from Passed ArrayList
                s.Append((((Anchor)aList[i]).Url).ToString());
                s.Append("\"");

                //URL UnderLine    Check and close    </a>
                if (urlUnderLine)
                {
                    s.Append(" style=\"text-decoration:    none\" ");
                }
                s.Append(">");

                //Set text Font&Color
                s.Append("<font    size=\"");
                s.Append(linkFontSize + "\"    color=\"" + 
                   urlForeColor.Name.ToString() + "\"" + ">");
                s.Append((((Anchor)aList[i]).Text).ToString());
                s.Append("</font></A>");
                //
                //

                //</p>
                if (pFlag) { s.Append("</p><p> </p>"); }

            }
            //Return Full HTML Code    As String
            return s.ToString();
        }

Render method:

        /// <summary>
        /// Render this control to web solution
        /// </summary>
        /// <param name="output"> The HTML writer to write out to </param>
        protected override void Render(HtmlTextWriter output)
        {
            try
            {
                // make instance from Data Class
                Data myData = new Data();
                //Write Marquee Tag with Custome Attributes
                output.Write("<marquee onmouseover=this.stop() " + 
                             "onmouseout=this.start() scrollamount=1 " + 
                             "scrolldelay=10 direction=" + 
                             marqueeDirection.ToString() + " width=" + 
                             width + " height=" + height + ">");
                //check Bold Option
                if (FontBold) { output.Write("<b>"); }
                //write the Links Tag which returned 
                //by GetNew(connectionStr) Method
                output.Write(AnchorsListHtmlGenerator(myData.GetNews(connectionStr, 
                                                                          isXML)));
                //Bold Close Tag
                if (FontBold) { output.Write("</b>"); }
                //Marquee Close Tage
                output.Write("</marquee>");

            }
            catch (Exception ex)
            {
                output.Write(ex.Message);
            }

        }

How? ..

After registering the DLL file within your web solution, you must:

  • Decide the database type: XML Or MS SQL Server. If your choice is XML, then set the property IsXML=true.

  • Then specify your XML file full path ConnectionString="C:\resources\xml\XMLFile1.xml" or your MS SQL DB connection string in the case of IsXml=false...

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Ameen Abudbash
Team Leader
Egypt Egypt
Member
• Over 8 years of experience in software developing, designing and implementing High Available web based applications specialized in Microsoft & IBM technologies.
• Extensive experience in developing, designing and implementing ECM solutions using IBM Filenet,Workplace, IBM BPM, REST services, AND Partial Experience in major CMS (Documentum and Oracle ECM).
• Extensive experience in Designing & Implementing Web2 Enterprise Apps using Leading RIA Frameworks (ExtJs , YUI… ).
• Partial experience in development with Microsoft SharePoint 2007 & 2010.
• Practical experience in Microsoft BI tools SSAS, SSIS, SSRS and Excel Services.
• Deep understanding of the OOP and Strong Design patterns background
• Interactive and fast enough to learn new technologies and sciences.
 
• Extensive experience in problem-to-resolution troubleshooting skills
• Playing different IT roles including designing, implementing, supporting, consulting and development, Managing teams composed of analyst, developers & QA.
• Agile project management methodologies and managed teams with Scrum.
• Deliver technical workshops, presentations, documents and POCs.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
QuestionHow can you change the Scrolling speed?membermikelopilato28 May '09 - 8:49 
How can you change the Scrolling speed of the text?
QuestionSQL DataviewsmemberTcode26 Aug '08 - 11:00 
How would I display data from a sql database using this control?Confused | :confused:
QuestionHow to use this controlmemberSharonRao27 Feb '07 - 12:23 
hello,
 
I am confused as how to use this control, i have included the dll in my web project but how to use it in my webform please help.
 
Thanks in Advance for your help. Best Regards

GeneralNew to .Netmembermikelopilato25 Oct '06 - 14:36 
I confused s to how to install and use this.
I opened a new project an built the dll. Placed it in my /bin/ folder in my website. There is where I get lost.
Help!
GeneralText Coloring &amp; RefershmemberAviram Solomon17 Oct '05 - 5:10 
Hi,
Good job
 
I add a functionality to set the color of the text:

public ArrayList GetNews(string str,bool _isXML)
{
...
anc.Color = myReader["Color"].ToString();
...
}
 
protected string AnchorsListHtmlGenerator(ArrayList aList)
{
...
s.Append("");
...
}
 

 
but how you refesh the control when the data has changed ?
 
Thanks
Aviram


GeneralUsing Database values and the URLmemberaschell13 Jul '05 - 4:18 
Unsure | :~ I am using a table of values to populate the marquee and it works like a dream. However, the URL is causing me issues. For example, I have a value in a table for the URL to be www.codeproject.com, but when I hit the link in the marquee it comes up as http://localhost/www.codeproject.com. Obviously I want to drop the 'localhost' part. Where in the code do I need to change this? The data.cs where IsXML = false, adds the correct URL to the anchor. I'm not sure where to go from here.
 
Any help would be fantastic!!
GeneralRe: Using Database values and the URLmemberAmeen Abudbush13 Jul '05 - 20:45 
Try to append the anchor HTML Tag in the following part:
// Tag
s.Append("<A href=\"");
 --to--> s.Append("<A href=\"http://");
//retrive and set Url from Passed ArrayList
s.Append((((Anchor)aList[i]).Url).ToString());
s.Append("\"");
 
//URL UnderLine Check and close </a>
if (urlUnderLine)
{
s.Append(" style=\"text-decoration: none\" ");
}
s.Append(">");
 
//Set text Font&Color
s.Append("<font size=\"");
s.Append(linkFontSize + "\" color=\"" +
urlForeColor.Name.ToString() + "\"" + ">");
s.Append((((Anchor)aList[i]).Text).ToString());
s.Append("</font></A>");
//
//

Then rebuild your Control....

 
Regards.....
Ameen Abudbush
GeneralRe: Using Database values and the URLmembermikelopilato28 May '09 - 8:48 
Add 'http://' to the url in the DB
So it should read 'http://www.codeproject.com'
GeneralMarquee Hesitattes on the browsermemberpkonaje6 Jun '05 - 18:07 
My application uses the browser to display scrolling text (Marquee) at the top frame and the bottom frame displays various media files like jpegs, quicktime movies, flash movies etc. as a playlist, controlled by javascript.
My problem is that, whenever the switchover from one media file to another takes place, the scrolling text hesitates and stops moving for a couple of seconds and then resumes. This happens while the media file is loaded on the browser. Can someone suggest a solution to prevent the hesitation of the scrolling marquee text.
 
Thanks a lot in advance.
 
-Pkonaje
 
Only those who see the invisible can do the impossible
GeneralRe: Marquee Hesitattes on the browsermemberscscsc7 Jun '05 - 22:57 
the idea of this control is to read from DB, then fill Html Marquee Tags:
<marquee onmouseover=this.stop() onmouseout=this.start()......> Text... </marquee>
 
we have two events(onmouseover and onmouseout) which handled with javascript,
when you move your mouse over the control the first event fired and the marquee stoped,and when you release or leave it the second you will fire the second event then your marquee will cont...
 
SO,
...if you develop your solution with VS.Net >> Try to set the pageLayout properity to FlowLayout and DONT use GridLayout in your work any more....
 
...try browse your page with onther browsers,,,
 
...try to view your page sourcecode during browes the page by right click browsers body then select view source,then find <marquee.. and read it carefully, you must found :
<marquee onmouseover=this.stop() onmouseout=this.start() scrollamount=1 scrolldelay=10 direction= width="width" height="height">
your text goes here....
</marquee>

 
Elshanawny
INFO@AMEEN.TK
GeneralGood Job...memberncsol4 Jun '05 - 8:36 
screenshot or not, you did a bangup job on this. I created one also, but yours works much cleaner abd quicker and works as advertised. The only thing I would suggest is a border around the control, which I will work in to your dll.
 
thanks,,,,,,
 
ncsol
GeneralScreenshotmemberNovacaine1 Jun '05 - 6:48 
A screenshot would have been nice i think. Seeing as there's no screenshot, i'm not even going to bother with this one.

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web03 | 2.6.130523.1 | Last Updated 24 May 2005
Article Copyright 2005 by Ameen Abudbash
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid