Programmatically Speaking ...

This site

Fav Blogs

Sponsors

  • MaximumASP
  • Packet Sniffer

String.format problem with MS AJAX javascript

One of the string method in MS Ajax library is String.format. It works well in a statement like this:

alert(String.format("Format me now, first is {0}, second is {1}, third is {2}", "first", "second", "third"));

However, if you want to put the last three parameters in an array as such:

var values = new array();

values[0] = "first";

values[1] = "second";

values[2] = "third";

Then you run the statement again:

alert(String.format("Format me now, first is {0}, second is {1}, third is {2}", values));

You will found the alerted string is "Format me now, first is first, second, third, second is , third is "

Totally not what it should be.

So instead, we have to go back the old-timer javascript and do a replacement as such 

  

if (values.length > 0) {
                    url = "
Format me now, first is {0}, second is {1}, third is {2}", 
                    for (var i = 0; i < values.length; i++) {
                        var exp = new RegExp('\\{' + (i) + '\\}', 'gm');
                        url = url.replace(exp, valuesIdea);
                    }

Guess we all make mistakes.

var values = new array();

values[0] = "first";

values[1] = "second";

values[2] = "third";

Just Published on DNS: JQuery and ASP

Just Published on DNS

Using jQuery with ASP .NET

In September 2008 Scott Guthrie, the head of the ASP.NET team, announced in a blog post that Visual Studio would be shipping with the jQuery library. He writes:

“jQuery is a lightweight open source JavaScript library (only 15kb in size) that in a relatively short span of time has become one of the most popular libraries on the web. A big part of the appeal of jQuery is that it allows you to elegantly (and efficiently) find and manipulate HTML elements with minimum lines of code … There is a huge ecosystem and community built up around JQuery. The jQuery library also works well on the same page with ASP.NET AJAX and the ASP.NET AJAX Control Toolkit.”

With that, JQuery is officially embraced by ASP.NET.

kick it on DotNetKicks.com

Silverlight HomePage is a good Laugh!

I have long found the flagsite of Silverlight disappointing, especially on the video-streaming side. Early this year, I blogged about my quite unhappy experience watching Bill Gate's performance on SilverLight, in this post:

http://dotnetslackers.com/Community/blogs/xun/archive/2008/01/11/a-disastrous-experience-with-silverlight.aspx

Of course my voice was buried in the chorus of praises for Silverlight. I thought I was wrong and bitchy.

Now, the very big candid voice of Rick Strahl blogged about his experience viewing Obama's inauguration. It made a splash.

http://www.west-wind.com/Weblog/posts/602131.aspx

...

On another note, what is the deal with the Microsoft's attempt of reinventing / rebranding itself by having Seinfield complain on air: he has so many cars, he gets caught in his own traffic; and Bill Gates did a little butt-wriggling dance ...

I heard it was a one million deal. What happened to it now?

 

  

ASP .net treeview control 2.0

I am a lazy googler, or, Google makes me lazy.

For example, recently I wanted to implement a treeview. Habitually I started to goole, which landed me right in an article in Code project. Unfortunately Google sure can rank popularity, however, it cannot pick the real gold. So the article leads me through a long archaic progress of downloading a suite of asp .net 1.0 web controls, including treeview, tab, multipage.

While trudging along, my brain finally managed to remind me of the asp .net 2.0 treeview I have used more than a few times:  stop, stop.

Indeed while google does not know anything about the newest development in asp .net, I should know better. The asp .net 2.0 treeview control answers all of my needs, and the little quick start tutorial on treeview (http://quickstarts.asp.net/QuickStartv20/aspnet/doc/ctrlref/navigation/treeview.aspx)  states it better:

"It supports a variety of programming models, from statically-defined trees, to dynamically constructed trees, to databound trees. The TreeView's rendering is fully customizable, allowing for a wide-range of look-and-feels for the control. The TreeView supports both postback-style events and simple hyperlink navigation, as well as a unique event handling model that allows data to be retrieved directly from a client without requiring a server postback. It also supports rendering on a variety of browsers, and can take advantage of up-level capabilities, such as client-script on later desktop browser versions."

Twitter News, Yahoo News, Tweet news

Wall-street is crashing, main-street is suffering, however, the web-street is forever booming.

There are cool exciting applications sprung up everyday. For example, Twitter-Yahoo news mash-up.

 Very old-fashioned people read newspapers, less old fashioned read google aggregated news, liberals / gossip seekers read huffington posts, the real news geeks, they turn to twitter for the newest, most breaking news of the newest news.

However, with timing, sometimes twitter news would be lacking in substance and depth. For example, the lastest Mumbai attack, users were frustrated to get the complete coverage and details, more details.

So the newest web tech breakthrough, Yahoo-Twitter mash-up.

"TweetNews mashup, combining the real-time search Yahoo’s BOSS tools with the freshness of Twitter. As an added bonus each story listed in TweetNews’ results also shows the relevant tweets, which themselves often have additional links. A quick search this morning for "flight 1549" yielded seven unique links from just the top result."

And the real web tech triumph, the developer Singh was able to create it with less than one hundred lines of code.

Wow, I wish I could be that good.

kick it on DotNetKicks.com

Dynamic ADC controls, master-child nested ADC controls

The AJAX Data Controls (ADC) created by www.dotnetslackers.com are a set of server controls using ASP .net AJAX and JavaScript library, it closely mirrors the functionalities of the pure server side ASP .net data controls such as gridview, datalist and repeater.

To create a ASP .net server control dynamically, we need to do so on the server side, in the code behind of page_init method. For example, to create a dynamic textbox control:

override protected void OnInit(EventArgs e)
{
    // Create dynamic controls here.
    // Use "using System.Web.UI.WebControls;"
    TextBox1 = new TextBox();
    TextBox1.ID = "TextBox1";
    TextBox1.Style["Position"] = "Absolute";
    TextBox1.Style["Top"] = "25px";
    TextBox1.Style["Left"] = "100px";
    Form1.Controls.Add(TextBox1);

    TextBox2 = new TextBox();
    TextBox2.ID = "TextBox2";
    TextBox2.Style["Position"] = "Absolute";
    TextBox2.Style["Top"] = "60px";
    TextBox2.Style["Left"] = "100px";
    Form1.Controls.Add(TextBox2);

    this.TextBox1.TextChanged += new System.EventHandler(this.TextBox_TextChanged);
    this.TextBox2.TextChanged += new System.EventHandler(this.TextBox_TextChanged);

    //
    // CODEGEN: This call is required by the ASP.NET Web Form Designer.
    //
    InitializeComponent();
    base.OnInit(e);
}

 

Recently I discovered that It is possible to create dynamic ADC controls too, however on the client side, using the following syntax:

  1. $create(controlName,    // class   
  2.             {},                     // properties   
  3.             {},                     // events   
  4.             {},                     // references   
  5.             null);                  // associated element     

For example, to create a repeater dynamically,

$create(AjaxDataControls.Repeater, {'itemTemplate': '<li><span id=\"spnProductName\"></span></li>'}, {'itemDataBound': onChildItemDataBound}, null, ulProducts);

In life, relationship is everything, parallel, hierarchical. Sometimes in data representation, we need to dynamically reflect data hierarchy too.

With asp .net, we can define the nested relationship among datatables in a dataset, then in a web form, we can set the relationship between a gridview and datalist as parent-child.

With ADC controls, is it possible to implement nested structures between two controls?

It turns out, Yes (this is my one of my recent discoveries). It turns out, it is pretty easy too.

The secret lies in the capacity of creating dynamic controls in the RowDataBoundEvent event of each parent row/item. The following is a dummy sample of nested gridview.

 

<%@ Page Language="C#" MasterPageFile="~/Site.master" Title="GridView Basic" %>
<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="Server">
    <h3>
        Supplier Information</h3>
    <AjaxData:GridView ID="GridView1" runat="server" CssClass="DataWebControlStyle" CellSpacing="0"
        CellPadding="3" RowDataBoundEvent="RowDataBound" DataKeyName="ID">
        <AlternatingRowStyle CssClass="AlternatingRowStyle" />
        <RowStyle CssClass="RowStyle" />
        <HeaderStyle CssClass="HeaderStyle" />
        <Columns>
            <AjaxData:GridViewBoundColumn DataField="Company" HeaderText="Company">
            </AjaxData:GridViewBoundColumn>
            <AjaxData:GridViewTemplateColumn>
                <ItemTemplate>

                    <a id="lnk" >show this</a><br />
                     <table id="ulProducts" style="display:none"></table>

                </ItemTemplate>
            </AjaxData:GridViewTemplateColumn>
        </Columns>
        <EmptyDataTemplate>
            There is no records available.
        </EmptyDataTemplate>
        <EmptyDataRowStyle HorizontalAlign="Center" />
    </AjaxData:GridView>
    
   

    <script type="text/javascript">
        var rIndex;
        function RowDataBound(sender, e) {
            var row = e.get_row(); //.get_rowIndex()
            if (row.get_isDataRowType()) {
                rIndex = row.get_rowIndex();
                var ulProducts = row.findControl('ulProducts');
                if (ulProducts) {
                    var childRepeaterID = ulProducts.id;
             //       alert(childRepeaterID);
                    var childRepeater = $find(childRepeaterID);
                    if (childRepeater) {

                        //There is a previous instance so we need to remove it.

                        Sys.Application.removeComponent(childRepeater);
                    }
                    childRepeater = $create(AjaxDataControls.GridView,
                      { }, { },
                     null, ulProducts);
                    
                    var data = new Array();
                    data[0] = { Id: 1, Name: "Sonu Kapoor" };
                    data[1] = { Id: 2, Name: "Xun Ding" };
                    data[2] = { Id: 3, Name: "Gabriel" };
                    data[3] = { Id: 3, Name: "Onur" };
                    childRepeater.set_dataSource(data);
                    childRepeater.dataBind();
                }
                var id = GridView1.get_dataKeys()[rIndex];
                var context = { tablename: ulProducts };
                var callback = Function.createCallback(showNested, context);
                //  alert(rIndex);
                var lnk = row.findControl('lnk');
                if (lnk) {
                    //      alert("agag");
                    $addHandler(lnk, "click", callback);
                }
            }
        }

        function onChildItemDataBound(sender, e) {
        }

        function showNested(evt, context) {
            var table = context.tablename;
            if (table.style.display == "none")
                table.style.display = "block";
            else
                table.style.display = "none";
        }
       
        function pageLoad(sender, e) {
            Pager1.set_recordCount(100);
         
            DataService.GetAllSupplier(onLoadSuccess);
        }

        function onLoadSuccess(result) {
            GridView1.set_dataSource(result);
            GridView1.dataBind();
        }

    </script>
</asp:Content>

 

ItemCommandEvent of ADC Repeater Control

The suite of AJAX Data Controls have three major controls: Gridview, DataList, Repeater, in a progression of more flexibilities yet a bit less of in-built functionalities. In the code downloaded from www.dotnetslackers.com,  there are many samples given for Gridview, though not nearly as many for the Repeater.

Makes sense, for Repeater gives you the wildest space to define your own data template, which means, you have to do your own plumbing.

For example, how does the commandEvent of ADC repeater work?

It took me a while to work out an dummy sample.

 <%@ Page Language="C#" MasterPageFile="~/Site.master" Title="Repeater Render Bullet" %>
<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" Runat="Server">
    <h4>Categories</h4>
    <AjaxData:Repeater ID="Repeater1" runat="server" ItemDataBoundEvent="onItemDataBound"
    RenderAs="Ul" ItemCommandEvent="onItemCommad">
        <ItemTemplate>
            <li><input button="View"></span><span id="spnName"></span></li>
        </ItemTemplate>
    </AjaxData:Repeater>

    <script type="text/javascript">

        function pageLoad(sender, e)
        {
            DataService.GetAllCategory(onLoadSuccess);
        }

        function onLoadSuccess(result)
        {
            var repeater = Repeater1;

            repeater.set_dataSource(result);
            repeater.dataBind();
        }

        function onItemCommand(sender, e) {
            var item = e.get_item();

            if (item.get_isDataItemType()) {
                if(e.commandName =="View")
                alert('You clicked me');
            }
        }
       
       
        function onItemDataBound(sender, e)
        {
            var item = e.get_item();

            if (item.get_isDataItemType())
            {
                var category = item.get_dataItem();

                var spnName = item.findControl('spnName');

                setText(spnName, category.Name);
            }
        }

        function setText(element, text)
        {
            if (typeof element.textContent != 'undefined')
            {
                element.textContent = text;
            }
            else if (typeof element.innerText != 'undefined')
            {
                element.innerText = text;
            }
        }

    </script>
</asp:Content>

Of course .NET is deep

 

 

Of course, this is not my original.

I stole it from http://codeclimber.net.nz/archive/2008/08/23/.net-vs-php-in-the-enterprise-comics-strip.aspx. Cannot help it. 

New Year's Resolution

 

 

For the past two months, I gave myself a long break. Two reasons, a plate full of trivial and not-so-trivial projects and tasks, then, lazy in nature, I let every free minute go out of my hands. 
 
Now the year of 2008 is gone, almost.
 
Time to take a deep breath and make a list of new year's wishes and resolutions.
 
All of them vague.
 
Reading
 
First of all, I need to step up my reading. Not just randomly articles, code samples turned up by Google, or even those kicked on the Dotnetkicks. But also the list of blogs, such as Rick Strahl's blog, and Esconia, and Coding Horror and The secret Life of a spaghetti coder. Also books. As much I want to go paperless, books still provide me anchor and structure. In the year of 2008, the best programming book I read is "ASP. NET 2.0 website programming Problem - Design - Solution". This year, I wish I could read more.
 
Writing
 
Blog and articles. JQuery, MVC, Silverlight, .NET 3.5 (Is 4.0 on the horizon?) Coding experiences, ah-ha moments, problems encountered and solved. Writing to me is a perfect way of learning.
 
Coding
 
This goes without saying. However it would be best if I could jump out of my comfort zone and take a look the new, the powerful and the hot. I am always dread downloading/installing new software and playing with it. Still half-baked (or little-baked) in MVC, Silverlight, JQuery, still new to the .net 3.5, WCFs. I am pretty clueless about Ruby, LINQ. 
 
Even with my coding, I am bad at testing and commenting and commenting well. 
 
Well, hope in the new year, I do better
Visual Studio 2010 and ASP .NET 4.0

 When you are a new kid, you cannot wait to grow up. However, when you are older then older, every passing year makes you feel the loss and the tick of the clock.

That is how I also feel about the forward-and-fast moving versions of software and programming models, frameworks and technologies.

Here it comes: Visual Studio 2010.

http://visualstudiomagazine.com/columns/article.aspx?editorialsid=2848

Here it comes again: asp .net 4.0.

http://www.codeplex.com/aspnet/Release/ProjectReleases.aspx?ReleaseId=14924

Other people's work

 

Shame to say, there are so many cool functionalities I have never coded nor used in my websites, such as programmatically generate screenshots, generate animated gif using a sequence of screenshot, create captcha, in-progress animated image.
 
Fortunately, there are many pieces of working code up for taking on the web.
 
ASP .NET Captcha server control :
 
 
Very popular (meaning it has been widely tested)
 
Screenshot of Webpage with ASP.NET
 
Make use of IECapt.exe to capture screenshot of a web page given by an URL
 
Create an animated GIF using .Net (C#)
 
This seems to be a hard one. Most animated GIFs are created by using offline imaging software, however, I sometimes I really want to streamline this process, especially when I want to demo a running web page.
 
 
This one seems to work, though it has only given only minimal explanations.
 
Animated "Wait" image and long-running progress
 
There are so many progress-bar type of applications, however, this one is breathtakingly simple and ingenious.
 
AJAX: JavaScript, or ASP .net AJAX or JQuery

 There are hundreds of AJAX frameworks and libraries. And the number is still growing (Face it, because the web, with the demand of rich data and fast, smooth user experience, is AJAXified overnight).

 However, I only know three: JavaScript AJAX, JQuery, and ASP.net AJAX.
 
JavaScript AJAX uses the very raw XMLHttpRequest. It's quite wordy, and needs to be always careful with different browser traps. That is, you always have to detect if XMLHttpRequest is supported, as such:
 
    var request;
    if (window.XMLHttpRequest())
        request = new XMLHttpRequest();
    else if(window.ActiveXObject)
        request = new ActiveXObject("Msxml2.XMLHTTP")
   else
      // throw an error here
 
ASP .net ajax is the Microsoft /asp .net team's approach to AJAX. It uses a ScriptManager and carries with it the quite bulk ASP .net ajax library. In the beginning, UpdatePanel, a partial postback web page refreshing model, plays a big role in ASP .net ajax, however, because of the heavy toll it exerts on bandwidth and performance, most people have abandoned its usage. ASP .net AJAX makes calling web service easy, and you get to use many of nice features in asp .net, such as membership, profile system.
 
JQuery has a number of functions that made AJAX easy. And as it is the case with JQuery, it is lightweighted and succinct. The list of functions are:
 
$.load (url, parameters, callback) : to load server response data to an element
 
$.get (url, parameters, callback): GET request with parameters
 
$.post (url, parameters, callback): POST request with paramenters
 
$.getJSON(url, parameters, callback): send a get request, response is interpreted as a JSON string
 
$.ajax (options) : send AJAX request with a number of options, including url, type, dataType, timeout, global, contentType, etc.
JQuery, the very very basics - Lesson 6
 
On with my JQuery learning series. 

For every programming language, there is invariably string manipulation and array fiddling. No exception with JQuery. Being unobtrusive in principal and complimentary in nature, it does not try to replace the existing bulk of JavaScript functions with its own, rather, it simply adds some of the most sorely missed functions.  

Trimming a string: $.trim(value)
In dealing with strings, JavaScript already has quite a comprehensive set of functions, such as split, substr, charAt (see references at http://www.w3schools.com/jsref/jsref_obj_string.asp), however, for some mysterious reasons, it does not have a trim function for ridding of leading and trailing white space. Smart and generous people have contributed to the web various versions of their trim functions. Such as:
var trimmed = str.replace(/^\s+|\s+$/g, '') ;
It works perfectly. However, how about simply call trim() function provided by JQuery? The syntax is $.trim(value) 
var trimmed = $.trim(" this really needs to be trimmed ");

Clean and plain English, right?

Array functions:
 
$.each (container, callback)
 
In JQery, in addition to the conventional JavaScript array (array of strings, numerics, elements), there is also specifically object array in the form of key-value pairs.
 
The former array is coded as: 
var arr = [ "one", "two", "three", "four", "five" ];
 The later (each pair seperated by a colon :) :
var obj = { item1: "one", item2: "two" ,item3: "three", item4: "four"};
It has always been easy to loop through an JavaScript array. However, it can be easier with the JQuery $.each function. The syntax is
$.each (container, callback). The callback function receives two arguments with the passing of each element: with [] type (traditional JavaScript) array, index and value; with {} type (array of objects with properties), key and value.
 
So we can access JQuery array elements as such (forgive me for using so many alerts):
 
$.grep (array, callback, invert) 
 
JQuery offers a $.grep() function to return an array of elements that matches a certain condition. The callback function is passed two parameters: the current value and its index. For example,
 
$.map (array, callback) 
 
One convenient function to transform all of the elements in an array in one shot. Change a string array into a numeric array? Yes; Change the numeric array back to a string array? Yes; Add a 10 to every number in an array? Yes. Just call the $.map function.
 
For example:
 
Other extremely useful JQuery array functions are:
 
$.inArray(value, array), returns the position of the first occurance of the element by a specified value. As in:

$.unique(array), returns a deduplicated array. As in:

$.makeArray(object), create an array out of a selected elements. As in:
 
$.extend(target, source1, source2, ... sourceN), extends the target object with the properties of the sources. For example:
  
 
 

kick it on DotNetKicks.com

Posted: Oct 21 2008, 01:12 AM by xxxd | with 4 comment(s)
Filed under:
Good links: ASP .NET and JQuery

Found a great bunch of links about using JQuery with asp .net

Using jQuery to directly call ASP.NET AJAX page methods

encosia.com An example of how to use jQuery to call an ASP.NET AJAX page method, without using a ScriptManager.

 

Using jQuery to consume ASP.NET JSON Web Services

encosia.com An overview of consuming ASP.NET web services that are JSON serialized by the ASP.NET AJAX extensions, including a specific example of using jQuery to do so.

 

Using jQuery To Call ASP.NET Page Methods and Web Services

dexign.net Seems like more and more ASP.NET devs are using jQuery. There are similar things on DNK but none that actually do provide code that uses jQuery to callback.

 

Integrating jQuery with ASP.NET

An alternative AJAX solution to use jQuery instead of ASP.NET AJAX

 

How to manage ASP.NET validation from Javascript with jQuery

codeclimber.net.nz This article outlines how to enable and disable ASP.NET client side validation from Javascript using jQuery

 

Ajax and json for ASP.NET MVC with jQuery

chrisvandesteeg.nl an example project that uses the jQuery library to create an ajax enabled ASP.NET MVC website. Generally what this project does: * Load views through ajax (with back-button support) * Do ajax-style form-posts and retrieve only the messages, errors and updated content * Do json form-posts and retrieve the errors an

 

3 mistakes to avoid when using jQuery with ASP.NET AJAX

encosia.com Three common problems that I've seen when using jQuery with ASP.NET AJAX, their underlying causes, and simple solutions to them.

 

 

(Better) JQuery IntelliSense in VS2008

weblogs.asp.net If you are like me and you've read the many articles about how to get other javascript libraries to work in VS2008, you'll know that all you really need to do is install the visual studio HOTFIX.

 

Client Side Templating with jQuery

west-wind.com When building AJAX applications there's often the requirement to choose between client and server side rendering. Server side ASP.NET controls provide rich templating, but updating those controls on the client can be difficult. Or is it? Here's one approach using jQuery and HTML templates in markup script to dynamically create complex layout on the client without writing reams of script code.

 

kick it on DotNetKicks.com

Posted: Oct 15 2008, 08:49 PM by xxxd | with 2 comment(s)
Filed under: ,
JQuery, the very very basics - Lesson 5
On with our journey of learning JQuery. Thanks to all of you who has stayed and cheered me and made me go on, against my own lazy nature. So far, we have slowly walked through the bunch of commands by which we select, dress up, manipulate chains of elements and make them action bound.
 
Now, let's look at the tiny set of commands for special-effects: show / hide with a speed, slide up / slide down, fade in and out. After all, we are human, insatiable for animations and wow factors. (However, please do not overplay your hand. :))
 
Show / Hide, Slower and slower, then faster and faster
 
Show / Hide a layer is such a common-place practice, yet before JQuery, I always have to be a little verbose (and most surely I have to do a quick search and grab some code, as in this case the vicitim of my theft is: http://www.geocities.com/technofundo/tech/js/showhide.html ):
 
Now, with JQuery, we can just say, (yes, you guessed it), show() to show, hide() to hide, an element or a matched set of elements:
 
$('div').show();

$('div').hide();

Of course, we can also tap the good sense of toggle() command, which can detect then reverse the state of a given element. Is it shown now? Yes -> then hide it; No -> show it.
 
Easy. 
 
One cool thing about this show/hide/toggle business is that we can now add a speed element to really animate the magic of appearance, disappearance and reappearance.
 
Speed in other languages is a rare thing, however, it is a norm in JQuery. From now on, we will speed things up and down often and very much at ease, for example, slide, fade, animate, etc. There are three predefined speeds: slow, normal and fast. Of course you can always come up with a speed in measure of milliseconds that suits you.
 
The following one line of code slowly alternates a layer's showing and hiding.  

$('div#toggle').toggle('slow'">);

Slide up and down, fade in and out

Sliding up and down a layer used to be a challenge. Not anymore. Now we can just use these tell-it-all commands: slideUp(speed, callback), slideDown(speed, callback). Of course, do not forget toggle. With sliding, the toggle command is slideToggle(speed, callback). 

So is the case with fading in and out. The commands for fading are: fadeIn(speed, callback), fadeOut(speed, callback).

An example:

All right, see you next week (I wish I could give you a Sarah Palin wink :).

kick it on DotNetKicks.com

Posted: Oct 13 2008, 09:17 PM by xxxd | with 4 comment(s)
Filed under:
More Posts Next page »