Building Simple Shoutcast Web Interface for Mobile Part 4

by nolovelust 30. March 2010 21:28

For part 3 click Building Simple Shoutcast Web Interface for Mobile Part 3

App_Data/Genres.xml

<?xml version="1.0" encoding="utf-8" ?>
<categories>
<cat>Top500</cat>
<cat>70s</cat>
<cat>80s</cat>
<cat>Alternative</cat>
<cat>Blues</cat>
<cat>Classical</cat>
<cat>Comedy</cat>
<cat>Country</cat>
<cat>Dance</cat>
<cat>Decades</cat>
<cat>Easy Listening</cat>
<cat>Electronic</cat>
<cat>Folk</cat>
<cat>Funk</cat>
<cat>Inspirational</cat>
<cat>International</cat>
<cat>Jazz</cat>
<cat>Latin</cat>
<cat>Live</cat>
<cat>Metal</cat>
<cat>Mixed</cat>
<cat>New Age</cat>
<cat>Old</cat>
<cat>Pop</cat>
<cat>Rap</cat>
<cat>Reggae</cat>
<cat>Regional</cat>
<cat>Rnb</cat>
<cat>Rock</cat>
<cat>Soundtracks</cat>
<cat>Talk</cat>
<cat>Themes</cat>
<cat>Techno</cat>
<cat>World</cat>
</categories>

 

Create Download folder under App_Data and give Write access. Feeds will be cached there.

Finally 500.htm. Shoutcast web server usually busy and gives 503 error

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//WAPFORUM//DTD XHTML Mobile 1.0//EN" "http://www.wapforum.org/DTD/xhtml-mobile10.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Shoutcast Mobile</title>
<link rel="stylesheet" href="style.css" type="text/css"/>
<meta name="keywords" content="shoutcast, online radio, mobile radio" />
<meta name="description" content="Shoutcast for mobile devices and iphone" />
</head>
<body>
    <div class="top">
    <a href="Default.aspx"><img src="logo.png" alt="Shoutcast mobile" title="Shoutcast mobile"/></a>
    <br />Shoutcast Mobile Internet radio database
    </div>
    <div class="gap"></div>
    <div class="title">Error</div>
    
    <div class="center">
    <span class="small">
    Shoutcast server didn't respond in time. Please go to <a href="Default.aspx">home page</a> and try again. This is a common error especially when Shoutcast server is busy.
    </span>
    <br /><a href="Default.aspx">Home</a>
    </div>

</body>
</html>

Tags: , ,

ASP.NET | Mobile web | Open Source

Building Simple Shoutcast Web Interface for Mobile Part 3

by nolovelust 30. March 2010 21:25

For part 2 click Building Simple Shoutcast Web Interface for Mobile Part 2

 App_Code/ScEngine.cs

using System;
using System.Data;
using System.IO;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Data.Common;

/// 
/// Summary description for ScEngine
/// 
public class ScEngine
{
    public DataSet GetStationList(string q, string job)
    {
        q = ScEngine.ReturnAlphaNumericForSearch(q);
        q = ScEngine.LimitString(q, 30);
        DataSet ds = new DataSet();
        string genreXmlFile = ScSettings.DownloadFolder + q + ".xml";

        if (File.Exists(genreXmlFile))
        {
            FileInfo fi = new FileInfo(genreXmlFile);

            if (DateTime.Now.Subtract(fi.LastWriteTime).TotalDays > 1)
            {
                File.WriteAllText(genreXmlFile, DownloadXML(q, job), Encoding.UTF8);
            }
            // read from local file
            ds.ReadXml(genreXmlFile);

        }
        else
        {
            string newDownload = DownloadXML(q, job);
            MemoryStream mStream = new MemoryStream(ASCIIEncoding.Default.GetBytes(newDownload));
            File.WriteAllText(genreXmlFile, newDownload, Encoding.UTF8);
            ds.ReadXml(mStream);
        }



        return ds;

    }
    public string DownloadXML(string q, string job)
    {
        string url = (job == "search") ? ScSettings.strURLsearch + q : ScSettings.strURLbrowse + q;

        StringBuilder sb = new StringBuilder();
        string tempString = null;
        int count = 0;
        byte[] buf = new byte[8192];
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
        request.Timeout = 4000; request.Accept = "*/*"; 
        request.Method = "GET"; 
        request.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; .NET CLR 3.5.30729; .NET CLR";
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        Stream resStream = response.GetResponseStream();
        do
        {
            count = resStream.Read(buf, 0, buf.Length);
            if (count != 0)
            {
                tempString = Encoding.UTF8.GetString(buf, 0, count);
                sb.Append(tempString);
            }
        }
        while (count > 0);

        return sb.ToString();
    }
    public static int ReturnNumeric(string input)
    {
        if (String.IsNullOrEmpty(input) == true)
        {
            return 0;
        }
        else
        {
            try
            {
                return Convert.ToInt32(input);
            }
            catch
            {
                return 0;
            }
        }
    }
    public static string ReturnAlphaNumeric(string input)
    {
        if (String.IsNullOrEmpty(input) == true)
        {
            return string.Empty;
        }
        else
        {
            try
            {
                return Regex.Replace(input, @"[^a-zA-Z0-9\.\-_]", "_").ToString();
            }
            catch
            {
                return string.Empty;
            }
        }
    }
    public static string ReturnAlphaNumericForSearch(string input)
    {
        if (String.IsNullOrEmpty(input) == true)
        {
            return string.Empty;
        }
        else
        {
            try
            {
                return Regex.Replace(input, @"[^a-zA-Z0-9\.\-_]", " ").ToString();
            }
            catch
            {
                return string.Empty;
            }
        }
    }
    public static string LimitString(string strToLimit, int limitTo)
    {
        if (strToLimit != null && strToLimit.Length > 0)
        {
            strToLimit = strToLimit.Trim();

            if (strToLimit.Length > limitTo)
            {
                return strToLimit.Substring(0, limitTo);
            }
            else
            {
                return strToLimit;
            }
        }
        return strToLimit;
    }
    public static void DeleteOldXML(int days)
    {
        try
        {
            // used in global.asax app start
            DateTime KeepDate = DateTime.Now.AddDays(days);
            DirectoryInfo fileListing = new DirectoryInfo(ScSettings.DownloadFolder);
            foreach (FileInfo f in new DirectoryInfo(ScSettings.DownloadFolder).GetFiles())
            {
                if (f.LastWriteTime <= KeepDate && f.Extension.ToLower() == ".xml")
                    f.Delete();
            }
        }
        catch
        {
        }

    }
}

 

App_Code/ScGenres.cs

using System;
using System.Data;
using System.IO;
using System.Web;

/// 
/// Summary description for ShoutCastCategoreies
/// 
public class ScGenres
{
    public DataSet GetGenres()
    {

        string myXMLfile = HttpContext.Current.Server.MapPath("~/App_Data/Genres.xml");
        DataSet ds = new DataSet();
        if (HttpContext.Current.Cache["SCGenres"] == null)
        {
            FileStream fsReadXml = new FileStream
                (myXMLfile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            try
            {
                ds.ReadXml(fsReadXml);
                //HttpContext.Current.Cache["Genres"] = ds;
                HttpContext.Current.Cache.Insert("SCGenres", ds, null,
                            System.Web.Caching.Cache.NoAbsoluteExpiration,
                            TimeSpan.FromMinutes(60));
                return ds;
            }
            catch (Exception ex)
            {
                return null;
            }
            finally
            {
                fsReadXml.Close();
            }
        }
        else
        {
            ds = (DataSet)HttpContext.Current.Cache["SCGenres"]; ;
            return ds;
        }
    }
}

 

App_Code/ScSettings.cs

/// 
/// Summary description for Settings
/// 
using System.Web;
public class ScSettings
{
    public ScSettings()
    {

    }

    public static string strURLsearch = "http://www.shoutcast.com/sbin/newxml.phtml?search=";
    public static string strURLbrowse = "http://www.shoutcast.com/sbin/newxml.phtml?genre=";
    public static string DownloadFolder = HttpContext.Current.Server.MapPath("~/App_Data/Downloads/");

}

Tags: , ,

ASP.NET | Mobile web | Open Source

Building Simple Shoutcast Web Interface for Mobile Part 2

by nolovelust 30. March 2010 21:20

For part 1 click Building Simple Shoutcast Web Interface for Mobile Part 1

Listen.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="listen.aspx.cs" Inherits="listen" %>

 

Codebehind Listen.aspx.cs

 

using System;
using System.Net;
using System.IO;
using System.Text;
using System.Web;

public partial class listen : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string radio = Request.QueryString["rn"];
        //Response.Redirect("http://www.shoutcast.com/sbin/shoutcast-playlist.pls?rn="+ radio);
        Response.Redirect("http://yp.shoutcast.com/sbin/tunein-station.pls?id=" + radio);
        //DownloadPls(radio);



    }
    protected void DownloadPls(string radioid)
    {
        HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://yp.shoutcast.com/sbin/tunein-station.pls?id=" + radioid);
        req.Timeout = 4000;
        req.Accept = "*/*";
        req.Method = "GET";
        req.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; .NET CLR 3.5.30729; .NET CLR";

        HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
        Stream st = resp.GetResponseStream();
        StreamReader sr = new StreamReader(st);
        string buffer = sr.ReadToEnd();

        Response.ContentType = "audio/x-scpls";
        Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode("radio" + radioid + ".pls", System.Text.Encoding.UTF8)); Response.ContentType = "audio/x-scpls";
        Response.Write(buffer);
    }
}

 

 

Search.aspx

 

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="search.aspx.cs" Inherits="_Search" %><?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//WAPFORUM//DTD XHTML Mobile 1.0//EN" "http://www.wapforum.org/DTD/xhtml-mobile10.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Shoutcast Mobile</title>
<link rel="stylesheet" href="style.css" type="text/css"/>
<meta name="keywords" content="shoutcast, online radio, mobile radio" />
<meta name="description" content="Shoutcast for mobile devices and iphone" />
</head>
<body>
<form id="form1" runat="server">
       <asp:ScriptManager ID="RadioUpdater" runat="server" ScriptMode="Release">
       </asp:ScriptManager>
       <asp:UpdateProgress ID="ajaxupdateindicator" DynamicLayout="true" runat="server"><ProgressTemplate><div style="background-color:#CF4342;color:#fff;top:0px;right:0px;position:fixed;">Loading...</div></ProgressTemplate></asp:UpdateProgress>

    <div>
    <div class="top">
    <table id="table1" style="width: 100%;">
	        <tr>
		        <td style="text-align: left;">
		            <a href="Default.aspx"><img src="logo.png" alt="Shoutcast mobile" title="Shoutcast mobile"/></a>
                </td>
		        <td style="text-align: right;">
		        <asp:TextBox ID="qt" runat="server" Columns="4"></asp:TextBox>
                <asp:DropDownList ID="BitRates" runat="server">
                <asp:ListItem Text="All bitrates" Value="0"></asp:ListItem>
                <asp:ListItem Text="256 kbps" Value="256"></asp:ListItem>
                <asp:ListItem Text="192 kbps" Value="192"></asp:ListItem>
                <asp:ListItem Text="128 kbps" Value="128"></asp:ListItem>
                <asp:ListItem Text="96 kbps" Value="96"></asp:ListItem>
                <asp:ListItem Text="64 kbps" Value="64"></asp:ListItem>
                <asp:ListItem Text="48 kbps" Value="48"></asp:ListItem>
                <asp:ListItem Text="32 kbps" Value="32"></asp:ListItem>
                <asp:ListItem Text="24 kbps" Value="24"></asp:ListItem>
                </asp:DropDownList>
        <asp:Button ID="ViewB" runat="server" Text="Go" onclick="ViewB_Click" />
        </td>
	        </tr>
        </table>
    </div>
    <div class="gap"></div>
     
        <asp:UpdatePanel ID="RadioUpdaterUpdatePanel" runat="server" UpdateMode="Conditional">
        <Triggers>
        <asp:AsyncPostBackTrigger ControlID="ViewB" EventName="Click" />
        </Triggers>
        <ContentTemplate>
        
        <div class="list" id="list">
           <asp:ListView ID="StationList" runat="server" ItemPlaceholderID="itemContainer">
           <LayoutTemplate>
               <ul>
                   <asp:PlaceHolder ID="itemContainer" runat="server" />
               </ul>
           </LayoutTemplate>
           <ItemTemplate>
               <li>
               <a target="_blank" href="listen.aspx?rn=<%#Eval("id") %>"><%#Server.HtmlEncode(Eval("name").ToString())%>
               <span class="tiny"><%#Server.HtmlEncode(Eval("br").ToString())%> kbps</span>
               </a>
               </li>
           </ItemTemplate>
           <EmptyDataTemplate>
           <li>No station found</li>
           </EmptyDataTemplate>
           <EmptyItemTemplate>
           <li>No station found</li>
           </EmptyItemTemplate>
        </asp:ListView>
        <div class="gap"></div>
        <div class="center">
                  <asp:DataPager ID="DataPager1" runat="server" PagedControlID="StationList" PageSize="5">
                <Fields>
        <asp:NextPreviousPagerField
            ButtonType="Button"
            ShowFirstPageButton="true"
            FirstPageText="&lt;&lt;"
            ShowNextPageButton="false"
            ShowPreviousPageButton="false" />

          <asp:NumericPagerField 
            PreviousPageText="&lt;"
            NextPageText="&gt;" ButtonType="Button"
            ButtonCount="5" />

          <asp:NextPreviousPagerField
            ButtonType="Button"
            LastPageText="&gt;&gt;"
            ShowLastPageButton="true"
            ShowNextPageButton="false"
            ShowPreviousPageButton="false" />
            
            <asp:TemplatePagerField>
            <PagerTemplate>
            <br />
            <b>Page
            <asp:Label runat="server" ID="CurrentPageLabel"
            Text="<%# Container.TotalRowCount>0 ? (Container.StartRowIndex / Container.PageSize) + 1 : 0 %>" />
            of
            <asp:Label runat="server" ID="TotalPagesLabel"
            Text="<%# Math.Ceiling ((double)Container.TotalRowCount / Container.PageSize) %>" />
            (<asp:Label runat="server" ID="TotalItemsLabel" Text="<%# Container.TotalRowCount%>" />
            records)
            </b>
            </PagerTemplate>
            </asp:TemplatePagerField>
            
        </Fields>              
            </asp:DataPager>
            <br /><a href="Default.aspx">Home</a>
          </div>
        </div>
        
       </ContentTemplate>
        </asp:UpdatePanel>
        
    </div>
    </form>
</body>
</html>

Codebehind Search.aspx.cs

 

using System;
using System.Data;
using System.Linq;

public partial class _Search : System.Web.UI.Page
{
      protected override void FrameworkInitialize()
    {
        base.FrameworkInitialize();
        ClientTarget = "ie5";
    }

    protected override void OnPreRender(EventArgs e)
    {
        base.OnPreRender(e);
        string q = ScEngine.ReturnAlphaNumericForSearch(Request.QueryString["q"]);
        string filterBitRate = Request.QueryString["br"];
        if (String.IsNullOrEmpty(q))
            q = "pop";

        BindListView(q);
        DataPager1.PageSize = 5;
        qt.Text = q;
        BitRates.SelectedValue = filterBitRate;
        Page.Title = "Shoutcast Mobile | " + q;

    }
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void BindListView(string q)
    {
        int filterBitRate = ScEngine.ReturnNumeric(Request.QueryString["br"]);
        DataTable dt = new DataTable();
        if (GetSearchlist(q).Tables.Count > 1)
        {
            dt = GetSearchlist(q).Tables[1];
            object LINQfilteteredResult;
            //Response.Write(filterBitRate);
            if (filterBitRate == 0)
            {
                LINQfilteteredResult = (from dr in dt.AsEnumerable()
                                        orderby ScEngine.ReturnNumeric(dr.Field("lc")) descending
                                        select new
                                        {
                                            id = dr.Field("id"),
                                            name = dr.Field("name"),
                                            br = dr.Field("br"),
                                            ct = dr.Field("ct"),
                                            lc = dr.Field("lc")
                                        }).ToList();
            }
            else
            {
                LINQfilteteredResult = (from dr in dt.AsEnumerable()
                                        where (ScEngine.ReturnNumeric(dr.Field("br")) == filterBitRate)
                                        select new
                                        {
                                            id = dr.Field("id"),
                                            name = dr.Field("name"),
                                            br = dr.Field("br"),
                                            ct = dr.Field("ct"),
                                            lc = dr.Field("lc")
                                        }).ToList();
            }

            //StationList.DataSource = GetListOfStations(GetSearchlist.SelectedValue.ToString());
            StationList.DataSource = LINQfilteteredResult;
            StationList.DataBind();
            //columns returned are
            //name - station name
            //mt - media type
            //id - station id
            //br - bitrate
            //genre - genre
            //ct - current title
            //lc - listener count
        }
        else
        {
        }
    }
    private DataSet GetSearchlist(string q)
    {
        if (Cache["SCGetSearchlist" + q] == null)
        {
            ScEngine se = new ScEngine();
            DataSet ds = new DataSet();
            ds = se.GetStationList(q, "search");
            if (ds != null)
            {
                //Cache["GetSearchlist" + genre] = ds;
                Cache.Insert("SCGetSearchlist" + q, ds, null,
                             System.Web.Caching.Cache.NoAbsoluteExpiration,
                            TimeSpan.FromMinutes(10));
            }
            return ds;
        }
        else
        {
            return (DataSet)Cache["SCGetSearchlist" + q];
        }
    }
    protected void ViewB_Click(object sender, EventArgs e)
    {
        Response.Redirect("search.aspx?q=" + qt.Text + "&br=" + BitRates.SelectedValue);
    }
}

 

 

style.css

 

body {
color:#ffffff;
margin:0;
padding:0;
font-family:verdana, sans-serif;
font-size: large;
background: #000;
}
a 
{
    color:#fec100;
}
a[selected], a:active {	
	background-color: #f40000 !important;
    color: #FFFFFF !important;
}

.small
{
    font-size:medium;
}
.tiny
{
    font-size:small;
}
input,button,form,select
{
font-family: Helvetica;
font-size: large;
}
ul {
list-style-type:none;
padding-left:5px;
margin:0;
}

li {
padding-bottom:7px;
padding-top:7px;
/*background-image:url('header_bg.gif');*/
border-bottom:dotted 2px #EAEAED;
}
#list a:hover,li:hover
{
    background: #333333;
    color:#ffffff;
}
.title
{
    
}
.list
{
}
.center
{
    text-align:center;
}
.gap
{
    padding:5px;
}
.top
{
    border-bottom:dotted 2px #EAEAED;
    font-size:x-large;
}
img 
{
    border:0px;
}
input, button, textarea, select
{
    margin:1px;
    padding: 5px;
    font-size:25px; 
}
.loading
{
   
}

Web.config

 

<?xml version="1.0"?>
<!-- 
    Note: As an alternative to hand editing this file you can use the 
    web admin tool to configure settings for your application. Use
    the Website->Asp.Net Configuration option in Visual Studio.
    A full list of settings and comments can be found in 
    machine.config.comments usually located in 
    \Windows\Microsoft.Net\Framework\v2.x\Config 
-->
<configuration>
  <configSections>
    <sectionGroup name="system.web.extensions" type="System.Web.Configuration.SystemWebExtensionsSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
      <sectionGroup name="scripting" type="System.Web.Configuration.ScriptingSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
        <section name="scriptResourceHandler" type="System.Web.Configuration.ScriptingScriptResourceHandlerSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>
        <sectionGroup name="webServices" type="System.Web.Configuration.ScriptingWebServicesSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
          <section name="jsonSerialization" type="System.Web.Configuration.ScriptingJsonSerializationSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="Everywhere"/>
          <section name="profileService" type="System.Web.Configuration.ScriptingProfileServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>
          <section name="authenticationService" type="System.Web.Configuration.ScriptingAuthenticationServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>
          <section name="roleService" type="System.Web.Configuration.ScriptingRoleServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>
        </sectionGroup>
      </sectionGroup>
    </sectionGroup>
  </configSections>
  <connectionStrings/>

  <system.web>
    <!-- 
            Set compilation debug="true" to insert debugging 
            symbols into the compiled page. Because this 
            affects performance, set this value to true only 
            during development.
        -->
    <httpRuntime maxRequestLength="10240" />
    <identity impersonate="true" />
    <!-- have asp.net use iis user set for the web site instead of asp.net/network user -->
    <globalization culture="en-GB" uiCulture="en-GB"/>
    <compilation debug="false">
      <assemblies>
        <add assembly="System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
        <add assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
        <add assembly="System.Data.DataSetExtensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
        <add assembly="System.Xml.Linq, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
      </assemblies>
    </compilation>
    <!--
            The <authentication> section enables configuration 
            of the security authentication mode used by 
            ASP.NET to identify an incoming user. 
        -->
    <authentication mode="None"/>
    <!--
            The <customErrors> section enables configuration 
            of what to do if/when an unhandled error occurs 
            during the execution of a request. Specifically, 
            it enables developers to configure html error pages 
            to be displayed in place of a error stack trace.
        -->
    <customErrors mode="RemoteOnly" defaultRedirect="500.htm">
      <error statusCode="500" redirect="500.htm" />
    </customErrors>
    <pages>
      <controls>
        <add tagPrefix="asp" namespace="System.Web.UI" assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
        <add tagPrefix="asp" namespace="System.Web.UI.WebControls" assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
      </controls>
    </pages>
    <httpHandlers>
      <remove verb="*" path="*.asmx"/>
      <add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
      <add verb="*" path="*_AppService.axd" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
      <add verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" validate="false"/>
    </httpHandlers>
    <httpModules>
      <add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
    </httpModules>
  </system.web>
  <system.codedom>
    <compilers>
      <compiler language="c#;cs;csharp" extension=".cs" warningLevel="4" type="Microsoft.CSharp.CSharpCodeProvider, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
        <providerOption name="CompilerVersion" value="v3.5"/>
        <providerOption name="WarnAsError" value="false"/>
      </compiler>
      <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" warningLevel="4" type="Microsoft.VisualBasic.VBCodeProvider, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
        <providerOption name="CompilerVersion" value="v3.5"/>
        <providerOption name="OptionInfer" value="true"/>
        <providerOption name="WarnAsError" value="false"/>
      </compiler>
    </compilers>
  </system.codedom>
  <!-- 
        The system.webServer section is required for running ASP.NET AJAX under Internet
        Information Services 7.0.  It is not necessary for previous version of IIS.
    -->
  <system.webServer>
    <validation validateIntegratedModeConfiguration="false"/>
    <modules>
      <remove name="ScriptModule"/>
      <add name="ScriptModule" preCondition="managedHandler" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
    </modules>
    <handlers>
      <remove name="WebServiceHandlerFactory-Integrated"/>
      <remove name="ScriptHandlerFactory"/>
      <remove name="ScriptHandlerFactoryAppServices"/>
      <remove name="ScriptResource"/>
      <add name="ScriptHandlerFactory" verb="*" path="*.asmx" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
      <add name="ScriptHandlerFactoryAppServices" verb="*" path="*_AppService.axd" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
      <add name="ScriptResource" preCondition="integratedMode" verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
    </handlers>
  </system.webServer>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Extensions" publicKeyToken="31bf3856ad364e35"/>
        <bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="3.5.0.0"/>
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Extensions.Design" publicKeyToken="31bf3856ad364e35"/>
        <bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="3.5.0.0"/>
      </dependentAssembly>
    </assemblyBinding>
  </runtime>

  <system.serviceModel>
    <behaviors>
      <endpointBehaviors>
        <behavior name="ServiceAspNetAjaxBehavior">
          <enableWebScript/>
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
    <services>
      <service name="Service">
        <endpoint address="" behaviorConfiguration="ServiceAspNetAjaxBehavior" binding="webHttpBinding" contract="Service"/>
      </service>
    </services>
  </system.serviceModel>
</configuration>

 

 

Tags: , ,

ASP.NET | Mobile web | Open Source

Building Simple Shoutcast Web Interface for Mobile Part 1

by nolovelust 30. March 2010 21:15

UPDATE 14/01/2011  Shoutcast stopped providing public API for their dataabse. You need to register at http://dev.aol.com/SHOUTcast/ to get your API Key.

After that you can simply edit /App_Code/ScESettings.cs and replece settings with below ones.

 

public static string strURLsearch = "http://api.shoutcast.com/legacy/stationsearch?k=YOURAPIKEY&search=";
public static string strURLbrowse = "http://api.shoutcast.com/legacy/genresearch?k=YOURAPIKEY&genre=";

 

Before all here is the complete script shoutcast-mobile.zip (592.97 kb) and here is the working version at http://mobile.web.tr/shoutcast

This app designed for high-end mobile phones that are capable of doing AJAX requests

Now, lets start from Default.aspx

 

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %><?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//WAPFORUM//DTD XHTML Mobile 1.0//EN" "http://www.wapforum.org/DTD/xhtml-mobile10.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Shoutcast Mobile Internet radio database</title>
<link rel="stylesheet" href="style.css" type="text/css"/>
<meta name="keywords" content="shoutcast, online radio, mobile radio, shoutcast mobile" />
<meta name="description" content="Shoutcast for mobile devices and iphone. Listen 100s of internet radios on your mobile phone" />
</head>
<body>
<form id="form1" runat="server">
       <asp:ScriptManager ID="RadioUpdater" runat="server" ScriptMode="Release">
       </asp:ScriptManager>
       <asp:UpdateProgress ID="ajaxupdateindicator" DynamicLayout="true" runat="server"><ProgressTemplate><div style="background-color:#CF4342;color:#fff;top:0px;right:0px;position:fixed;">Loading...</div></ProgressTemplate></asp:UpdateProgress>
    <div>
    <div class="top">
            <table id="table1" style="width: 100%;">
	        <tr>
		        <td style="text-align: left;">
		            <img src="logo.png" alt="Shoutcast mobile" title="Shoutcast mobile"/>
                </td>
		        <td style="text-align: right;">
		        <asp:DropDownList ID="GenreList" runat="server">
                </asp:DropDownList> <asp:DropDownList ID="BitRates" runat="server">
                <asp:ListItem Text="All bitrates" Value="0"></asp:ListItem>
                <asp:ListItem Text="256 kbps" Value="256"></asp:ListItem>
                <asp:ListItem Text="192 kbps" Value="192"></asp:ListItem>
                <asp:ListItem Text="128 kbps" Value="128"></asp:ListItem>
                <asp:ListItem Text="96 kbps" Value="96"></asp:ListItem>
                <asp:ListItem Text="64 kbps" Value="64"></asp:ListItem>
                <asp:ListItem Text="48 kbps" Value="48"></asp:ListItem>
                <asp:ListItem Text="32 kbps" Value="32"></asp:ListItem>
                <asp:ListItem Text="24 kbps" Value="24"></asp:ListItem>
                </asp:DropDownList>
                <asp:Button ID="ViewB" runat="server" Text="Go" 
                onclick="ViewB_Click" />
        </td>
	        </tr>
        </table>
  </div>
  
  <div class="gap"></div>
   
        <asp:UpdatePanel ID="RadioUpdaterUpdatePanel" runat="server" UpdateMode="Conditional">
        <Triggers>
        <asp:AsyncPostBackTrigger ControlID="ViewB" EventName="Click" />
        </Triggers>
        <ContentTemplate>

        <div class="list" id="list">
           <asp:ListView ID="StationList" runat="server" ItemPlaceholderID="itemContainer">
           <LayoutTemplate>
               <ul>
                   <asp:PlaceHolder ID="itemContainer" runat="server" />
               </ul>
           </LayoutTemplate>
           <ItemTemplate>
               <li>
               <a target="_blank" href="http://yp.shoutcast.com/sbin/tunein-station.pls?id=<%#Eval("id") %>"><%#Server.HtmlEncode(Eval("name").ToString())%>
                <span class="tiny"><%#Server.HtmlEncode(Eval("br").ToString())%> kbps</span>
               </a>
               </li>
           </ItemTemplate>
           <EmptyDataTemplate>
           <li>No station found</li>
           </EmptyDataTemplate>
           <EmptyItemTemplate>
           <li>No station found</li>
           </EmptyItemTemplate>
        </asp:ListView>
        <div class="gap"></div>
        <div class="center">
        
        <asp:DataPager ID="DataPager1" runat="server" PagedControlID="StationList" PageSize="5">
        <Fields>
        <asp:NextPreviousPagerField
            ButtonType="Button"
            ShowFirstPageButton="true"
            FirstPageText="&lt;&lt;"
            ShowNextPageButton="false"
            ShowPreviousPageButton="false" />

          <asp:NumericPagerField 
            PreviousPageText="&lt;"
            NextPageText="&gt;" ButtonType="Button"
            ButtonCount="5" />

          <asp:NextPreviousPagerField
            ButtonType="Button"
            LastPageText="&gt;&gt;"
            ShowLastPageButton="true"
            ShowNextPageButton="false"
            ShowPreviousPageButton="false" />
            
            
            <asp:TemplatePagerField>
            <PagerTemplate>
            <br />
            <b>Page
            <asp:Label runat="server" ID="CurrentPageLabel"
            Text="<%# Container.TotalRowCount>0 ? (Container.StartRowIndex / Container.PageSize) + 1 : 0 %>" />
            of
            <asp:Label runat="server" ID="TotalPagesLabel"
            Text="<%# Math.Ceiling ((double)Container.TotalRowCount / Container.PageSize) %>" />
            (<asp:Label runat="server" ID="TotalItemsLabel" Text="<%# Container.TotalRowCount%>" />
            records)
            </b>
            </PagerTemplate>
            </asp:TemplatePagerField>
        </Fields>              
            </asp:DataPager>
          </div>
        </div>
       
        </ContentTemplate>
        </asp:UpdatePanel>
        
    </div>
    </form>
     <div class="gap"></div>
    <form action="search.aspx">
        <div class="center">
        <input id="SearchT" type="text" name="q"/><input id="Submit1" type="submit" value="Search" />
        <br />
        <a href="shoutcast.zip">Get source code source code</a>
        <br />
        <span class="small">We have no affiliation to <a href="http://shoutcast.com/">http://shoutcast.com/</a>. We simply provide mobile interface to their public web site.</span>
        </div>
        </form>
</body>
</html>

 

 

Codebehind Default.aspx.cs

 

using System;
using System.Data;
using System.Linq;
using System.Web.UI;

public partial class _Default : System.Web.UI.Page
{
    protected override void FrameworkInitialize()
    {
        base.FrameworkInitialize();
        ClientTarget = "ie5";
    }

    protected override void OnPreRender(EventArgs e)
    {
        base.OnPreRender(e);
        BindListView();
        DataPager1.PageSize = 5;

    }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            BindGenres();

        }

    }
    private void BindGenres()
    {
        ScGenres g = new ScGenres();
        GenreList.DataSource = g.GetGenres();
        GenreList.DataTextField = "cat_Text";
        GenreList.DataValueField = "cat_Text";
        GenreList.DataBind();
    }
    protected void ViewB_Click(object sender, EventArgs e)
    {
        BindListView();
    }
    protected void BindListView()
    {
        int filterBitRate = ScEngine.ReturnNumeric(BitRates.SelectedValue.ToString());
        DataTable dt = new DataTable();
        dt = GetListOfStations(GenreList.SelectedValue.ToString()).Tables[1];
        object LINQfilteteredResult;
        if (filterBitRate == 0)
        {
            LINQfilteteredResult = (from dr in dt.AsEnumerable()
                                    orderby ScEngine.ReturnNumeric(dr.Field("lc")) descending
                                    select new
                                    {
                                        id = dr.Field("id"),
                                        name = dr.Field("name"),
                                        br = dr.Field("br"),
                                        ct = dr.Field("ct"),
                                        lc = dr.Field("lc")
                                    }).ToList();
        }
        else
        {
            LINQfilteteredResult = (from dr in dt.AsEnumerable()
                                    where (ScEngine.ReturnNumeric(dr.Field("br")) == filterBitRate)
                                    select new
                                    {
                                        id = dr.Field("id"),
                                        name = dr.Field("name"),
                                        br = dr.Field("br"),
                                        ct = dr.Field("ct"),
                                        lc = dr.Field("lc")
                                    }).ToList();
        }

        //StationList.DataSource = GetListOfStations(GenreList.SelectedValue.ToString());
        StationList.DataSource = LINQfilteteredResult;
        StationList.DataBind();
        //columns returned are
        //name - station name
        //mt - media type
        //id - station id
        //br - bitrate
        //genre - genre
        //ct - current title
        //lc - listener count
    }
    private DataSet GetListOfStations(string genre)
    {
        if (Cache["SCGenreList" + genre] == null)
        {
            ScEngine se = new ScEngine();
            DataSet ds = new DataSet();
            ds = se.GetStationList(genre, "list");
            if (ds != null)
            {
                //Cache["GenreList" + genre] = ds;
                Cache.Insert("SCGenreList" + genre, ds, null,
                             System.Web.Caching.Cache.NoAbsoluteExpiration,
                            TimeSpan.FromMinutes(180));
            }
            return ds;
        }
        else
        {
            return (DataSet)Cache["SCGenreList" + genre];
        }
    }
}

 

Tags: , ,

ASP.NET | Mobile web | Open Source

Tag cloud

Month List