Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

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

0.00/5 (No votes)
23 May 2005 1  
Vertical/horizontal Marquee Web Custom Control consuming SQL Server DB/XML, with great design time attributes.

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