Google+ Peter Bromberg's .NET Blog | All Things Programming

Peter Bromberg's .NET Blog All Things Programming

Display RSS Feed with JSONP and AJAX UI-blocking Loader

2. July 2013 08:38 by admin in ASP.NET, JSON

Here is a technique to display an RSS feed with the jQuery $ajax method, using Yahoo's YQL query API to retrieve the feed and return it as JSON:

<!DOCTYPE HTML>
<html>
 <head>
<title> Feed Demo with Ajax Loader </title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="Scripts/jquery.blockUI.js"></script>
  <script>
function stopUI() {
    $.blockUI({ message: '<img id="AjaxLoader" src="Images/ajax-loader.gif" />',
        css: {
            padding: '25px',
            margin: 0,
            width: '5%',
            top: '40%',
            left: '40%',
            color: '#000',
            textAlign: 'center',
            border: '3px solid #aaa',
            backgroundColor: '#efefef',
            cursor: 'wait'
        },
        overlayCSS: {
            backgroundColor: '#000',
            opacity: 0.2
        }
    });
    $('body').css('cursor', 'wait');
}
 
// REMOVE THE BLOCKED INTERFACE
function startUI() {
    $.unblockUI();
    $('body').css('cursor', 'default');
}
 
$(function() {
    stopUI();
     getFeed();
});
 
function getFeed()
{ 
    $.ajax({
// ajax request to yql public json url 
      url : 'http://query.yahooapis.com/v1/public/yql',
      jsonp : 'callback',
// tell jQuery that we need JSON format
      dataType : 'jsonp',
// tell YQL that what we want and to output in JSON format
      data : {
          q : 'select * from rss where url ="http://www.peterbromberg.net/syndication.axd"',
          format : 'json'
      },
// parse response data
      success : function(data) {
        $.each(data.query.results.item, function(i,data)
        {
var news_data =
"<div><a href='"+data.link+"'>" + data.title + "</a>" + 
          data.description +"</div>";
          $(news_data).appendTo("#news");
        });
 
      }    ,
      complete: function(){
          startUI();
          } 
    });
 
}
</script>
 </head>
 <body>
<div id="news"></div>
 </body>
</html>


The download includes the Ajax-loader image as well as the required jquery.blockUI.js javascript.


 

blockUi.zip (9.58 kb)

How to Format JSON -Style Dates With Javascript

26. June 2013 10:52 by admin in ASP.NET, JSON

 

Formatting JSON - style Javascript dates can be tricky. Here's some sample code that shows how to do it:

<!DOCTYPE HTML >
<html><head><script>
function formatDate( jsonDate)
{
var date = new Date(parseInt(jsonDate.substr(6)));
return date.getMonth()+'/'+date.getDay()+'/'+date.getFullYear()+' '+date.getHours()+':'+date.getMinutes();  // 12/1/2013 13:46 
}
</script></head><body>  
<div id=dte><script>document.write(formatDate('/Date(1225243290011)/'));</script></div>  </body>
</html>

Using the AJAX Autocomplete Extender With Multiple Values

18. May 2013 12:50 by admin in ASP.NET

The MS Ajax Autocomplete extender allows you to change a texbox into a typeahead dropdown list allowing you to select one of the matches to a search. Here is how it can be used to handle  both display text and value items with a bit of Javascript.

 

First let’s have a look at key elements of the markup:

<script type = "text/javascript">function clientItemSelected(sender, e) {
             $get("<%=hfZipcode.ClientID %>").value = e.get_value();
        }
    </script><asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true"></asp:ScriptManager>
        <asp:Label runat="server" ID="lblText" Text="Enter City Search string" />
        <asp:TextBox ID="txtZip" runat="server"></asp:TextBox>
        <asp:AutoCompleteExtender ID="AutoCompleteEx" runat="server"  TargetControlId="txtZip"
ServiceMethod="GetCompletionList"
              ServicePath="Default.aspx"
            MinimumPrefixLength="2" 
            CompletionInterval="1000"
            EnableCaching="true"
            CompletionSetCount="20" 
            CompletionListCssClass="autocomplete_completionListElement" 
            CompletionListItemCssClass="autocomplete_listItem" 
            CompletionListHighlightedItemCssClass="autocomplete_highlightedListItem"
            DelimiterCharacters=";, :"
            OnClientItemSelected = "clientItemSelected" >
             <Animations>
                    <OnShow>
                        <Sequence>
                            <%-- Make the completion list transparent and then show it --%>
                            <OpacityAction Opacity="0" />
                            <HideAction Visible="true" /> 
                            <%--Cache the original size of the completion list the first time
                                the animation is played and then set it to zero --%>
                            <ScriptAction Script="
                                // Cache the size and setup the initial size
                                var behavior = $find('AutoCompleteEx');
                                if (!behavior._height) {
                                    var target = behavior.get_completionList();
                                    behavior._height = target.offsetHeight - 2;
                                    target.style.height = '0px';
                                }" />
                            <%-- Expand from 0px to the appropriate size while fading in --%>
                            <Parallel Duration=".4">
                                <FadeIn />
                                <Length PropertyKey="height" StartValue="0" EndValueScript="$find('AutoCompleteEx')._height" />
                            </Parallel>
                        </Sequence>
                    </OnShow>
                    <OnHide>
                        <%-- Collapse down to 0px and fade out --%>
                        <Parallel Duration=".4">
                            <FadeOut />
                            <Length PropertyKey="height" StartValueScript="$find('AutoCompleteEx')._height" EndValue="0" />
                        </Parallel>
                    </OnHide>
                </Animations>
            </asp:AutoCompleteExtender> 
          <asp:HiddenField ID="hfZipcode" runat="server" />
        <asp:Button ID="btnSubmit" runat="server" Text="Submit" 
            onclick="btnSubmit_Click" /> <asp:Label ID="lblMessage" runat ="server" />
    </form>

 

 
Here is the associated codebehind class for the page, which includes the Page Method that returns the requested data:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;namespace Autocomplete
{public partial class Default : System.Web.UI.Page{protected void Page_Load(object sender, EventArgs e){}[System.Web.Script.Services.ScriptMethod()][System.Web.Services.WebMethod]public static List<string> GetCompletionList(string prefixText, int count){using (SqlConnection conn = new SqlConnection()){conn.ConnectionString = 
            ConfigurationManager.ConnectionStrings["default"].ConnectionString;
                using (SqlCommand cmd = new SqlCommand())
                {cmd.CommandType = CommandType.StoredProcedure;cmd.CommandText = "GetZipInfoByCityName";cmd.Parameters.AddWithValue("@SearchTerm", prefixText);cmd.Parameters.AddWithValue("@maxRecs", 20);cmd.Connection = conn;conn.Open();List<string> zips = new List<string>();using (SqlDataReader sdr = cmd.ExecuteReader()){while (sdr.Read()){string item = 
                 AjaxControlToolkit.AutoCompleteExtender.CreateAutoCompleteItem(sdr["CityState"].ToString(), 
                                   sdr["Zipcode"].ToString());zips.Add(item);}}conn.Close();return zips;}}}protected void btnSubmit_Click(object sender, EventArgs e){lblMessage.Text = "You selected " + hfZipcode.Value;}}
}

The trick for handling the value that gets submitted upon a selection is the little javascript clientItemSelected function. This is triggered by the OnClientItemSelected = "clientItemSelected" attribute of the Autocomplete extender. The downloadable code includes the SQL Server database files for a ZIP CODE database. Simply attach this database to your local copy of Sql Server and you should be ready to test it out.

 

Autocomplete.zip (3.33 mb)

An Easy Way to Render HTML From an ASP.NET UserControl

20. March 2013 09:59 by admin in

Often we need to call RenderControl on a UserControl to get the rendered HTML and be able to pass it to a PDF or Report generator. This can be problematic because you will get exceptions saying that the control must be within a FORM tag with runat=server. Also, If there are any AJAX script - related controls such as TextBoxExtenders, you will be warned that a ScriptManager is required. Here is an easy way to avoid these issues and get back "clean" HTML:

public static string RenderUserControl(Control ctrl)

{

Control control = null;

const string STR_BeginRenderControlBlock = "";

const string STR_EndRenderControlBlock = "";

StringWriter tw = new StringWriter();

Page page = new Page();

page.EnableViewState = false;

HtmlForm form = new HtmlForm();

form.ID = "__temporanyForm";

page.Controls.Add(form);

form.Controls.Add(new LiteralControl(STR_BeginRenderControlBlock));

// add a ScriptManager to prevent Ajax Extender control exceptions

ScriptManager m = new ScriptManager();

form.Controls.Add(m);

form.Controls.Add(ctrl);

form.Controls.Add(new LiteralControl(STR_EndRenderControlBlock));

HttpContext.Current.Server.Execute(page, tw, true);

string Html = tw.ToString();

int start = Html.IndexOf("");

int end = Html.Length - start;

Html = Html.Substring(start, end);

// return the rendered HTTML and send it into the PDF generator

return Html;

}